本文整理汇总了C++中VirtualQuery函数的典型用法代码示例。如果您正苦于以下问题:C++ VirtualQuery函数的具体用法?C++ VirtualQuery怎么用?C++ VirtualQuery使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了VirtualQuery函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: guard
int StackTraceResolverImpl<ObjectFileFormat::Windows>::resolve(
StackTrace *stackTrace,
bool demangle)
// Given a specified stack trace object 'stackTrace' of stack trace frames
// with only their 'address' fields valid, set as many other fields of the
// frames as possible. The 'demangle' argument is ignored, demangling
// always happens on Windows. Return 0 if successful and a non-zero value
// otherwise.
{
typedef bsl::map<HMODULE, const char *> LibNameMap;
bdlma::HeapBypassAllocator hbpAlloc;
bslmt::QLockGuard guard(&DbghelpDllImpl_Windows::qLock());
DbghelpDllImpl_Windows::symSetOptions(SYMOPT_NO_PROMPTS
| SYMOPT_LOAD_LINES
| SYMOPT_DEFERRED_LOADS);
// | SYMOPT_DEBUG);
int numFrames = stackTrace->length();
LibNameMap libNameMap(&hbpAlloc);
char *libNameBuf = (char *) hbpAlloc.allocate(MAX_PATH);
enum { MAX_SYMBOL_BUF_NAME_LENGTH = 2000 };
#ifdef BSLS_PLATFORM_CPU_32_BIT
enum { SIZEOF_SEGMENT = sizeof(SYMBOL_INFO) +
MAX_SYMBOL_BUF_NAME_LENGTH * sizeof(TCHAR) };
SYMBOL_INFO *sym = (SYMBOL_INFO*) hbpAlloc.allocate(SIZEOF_SEGMENT);
#else
enum { SIZEOF_SEGMENT = sizeof(IMAGEHLP_SYMBOL64) +
MAX_SYMBOL_BUF_NAME_LENGTH * sizeof(TCHAR) };
IMAGEHLP_SYMBOL64 *sym = (IMAGEHLP_SYMBOL64 *)
hbpAlloc.allocate(SIZEOF_SEGMENT);
#endif
for (int i = 0; i < numFrames; ++i) {
StackTraceFrame *frame = &(*stackTrace)[i];
DWORD64 address = (DWORD64) frame->address();
IMAGEHLP_LINE64 line;
ZeroMemory(&line, sizeof(IMAGEHLP_LINE64));
line.SizeOfStruct = sizeof(line);
DWORD offsetFromLine;
int rc = DbghelpDllImpl_Windows::symGetLineFromAddr64(address,
&offsetFromLine,
&line);
if (rc) {
frame->setSourceFileName(line.FileName);
frame->setLineNumber(line.LineNumber);
}
else {
reportError("stack trace resolver error: symGetLineFromAddr64"
" error code: ");
}
DWORD64 offsetFromSymbol = 0;
ZeroMemory(sym, SIZEOF_SEGMENT);
sym->SizeOfStruct = sizeof(*sym);
#ifdef BSLS_PLATFORM_CPU_32_BIT
sym->MaxNameLen = MAX_SYMBOL_BUF_NAME_LENGTH;
rc = DbghelpDllImpl_Windows::symFromAddr(address,
&offsetFromSymbol,
sym);
#else
BSLMF_ASSERT(sizeof(void *) == 8);
sym->MaxNameLength = MAX_SYMBOL_BUF_NAME_LENGTH;
rc = DbghelpDllImpl_Windows::symGetSymFromAddr64(address,
&offsetFromSymbol,
sym);
#endif
if (rc) {
// windows is always demangled
((TCHAR *) sym)[SIZEOF_SEGMENT - 1] = 0;
frame->setMangledSymbolName(sym->Name);
frame->setSymbolName(frame->mangledSymbolName());
frame->setOffsetFromSymbol((bsl::size_t) offsetFromSymbol);
}
else {
#ifdef BSLS_PLATFORM_CPU_32_BIT
reportError("stack trace resolver error: SymFromAddr"
" error code: ");
#else
reportError("stack trace resolver error: SymGetSymFromAddr64"
" error code: ");
#endif
}
HMODULE hModule = NULL;
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQuery((LPCVOID) address, &mbi, sizeof(mbi))) {
hModule = (HMODULE)(mbi.AllocationBase);
}
LibNameMap::iterator it = libNameMap.find(hModule);
if (libNameMap.end() != it) {
// If the library name in the map is "", leave the library file
// name in the frame null.
//.........这里部分代码省略.........
示例2: getLibraryInfo
bool CSignatureFunction::getLibraryInfo(const void *libPtr, DynLibInfo &lib)
{
uintptr_t baseAddr;
if (libPtr == NULL)
{
return false;
}
#ifdef _WIN32
MEMORY_BASIC_INFORMATION info;
IMAGE_DOS_HEADER *dos;
IMAGE_NT_HEADERS *pe;
IMAGE_FILE_HEADER *file;
IMAGE_OPTIONAL_HEADER *opt;
if (!VirtualQuery(libPtr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
{
return false;
}
baseAddr = reinterpret_cast<uintptr_t>(info.AllocationBase);
// All this is for our insane sanity checks :o
dos = reinterpret_cast<IMAGE_DOS_HEADER *>(baseAddr);
pe = reinterpret_cast<IMAGE_NT_HEADERS *>(baseAddr + dos->e_lfanew);
file = &pe->FileHeader;
opt = &pe->OptionalHeader;
// Check PE magic and signature
if (dos->e_magic != IMAGE_DOS_SIGNATURE || pe->Signature != IMAGE_NT_SIGNATURE || opt->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)
{
return false;
}
// Check architecture, which is 32-bit/x86 right now
// Should change this for 64-bit if Valve gets their act together
if (file->Machine != IMAGE_FILE_MACHINE_I386)
{
return false;
}
//For our purposes, this must be a dynamic library
if ((file->Characteristics & IMAGE_FILE_DLL) == 0)
{
return false;
}
//Finally, we can do this
lib.memorySize = opt->SizeOfImage;
#else
Dl_info info;
Elf32_Ehdr *file;
Elf32_Phdr *phdr;
uint16_t phdrCount;
if (!dladdr(libPtr, &info))
{
return false;
}
if (!info.dli_fbase || !info.dli_fname)
{
return false;
}
// This is for our insane sanity checks :o
baseAddr = reinterpret_cast<uintptr_t>(info.dli_fbase);
file = reinterpret_cast<Elf32_Ehdr *>(baseAddr);
// Check ELF magic
if (memcmp(ELFMAG, file->e_ident, SELFMAG) != 0)
{
return false;
}
// Check ELF version
if (file->e_ident[EI_VERSION] != EV_CURRENT)
{
return false;
}
// Check ELF architecture, which is 32-bit/x86 right now
// Should change this for 64-bit if Valve gets their act together
if (file->e_ident[EI_CLASS] != ELFCLASS32 || file->e_machine != EM_386 || file->e_ident[EI_DATA] != ELFDATA2LSB)
{
return false;
}
// For our purposes, this must be a dynamic library/shared object
if (file->e_type != ET_DYN)
{
return false;
}
//.........这里部分代码省略.........
示例3: find_maps
/*******************MemHeap内存改写处理************************/
INT find_maps(ULONG addr, ULONG *start, ULONG *end)
{
#ifdef _OS_LINUX_
char mapFile[30];
char buf[120];
char attr[4];
FILE *fp;
ULONG pid = vos_get_pid();
sprintf(mapFile, "/proc/%lu/maps", pid);
if(NULL == (fp = fopen(mapFile, "r")))
return FALSE;
while(NULL != fgets(buf, 120, fp))
{
sscanf(buf, "%lx-%lx %s", start, end, attr);
if((addr >= *start) && (addr < *end) &&
(attr[0] == 'r') && (attr[1] == 'w'))
{
fclose(fp);
return TRUE;
}
else if(addr < *start)/* 位于空洞 */
break;
else/* 下一个 */
continue;
}
fclose(fp);
*start = (ULONG)NULL; *end = (ULONG)NULL;
return FALSE;
#endif
#ifdef _OS_WINNT_
MEMORY_BASIC_INFORMATION info;
BYTE *head, *tail;
BYTE *page = (BYTE*)round_down(addr, PAGE_SIZE);
*start = (ULONG)NULL; *end = (ULONG)NULL;
if(0 == VirtualQuery(page, &info, sizeof(info)))
return FALSE;
if((info.Protect != PAGE_READWRITE) ||
(info.AllocationProtect != PAGE_READWRITE) ||
(info.State != MEM_COMMIT))
return FALSE;
*end = (ULONG)(page + info.RegionSize);
tail = (BYTE*)(info.AllocationBase);
do
{
head = tail;
VirtualQuery(head, &info, sizeof(info));
tail = head + info.RegionSize;
}while(addr >= (ULONG)tail);
*start = (ULONG)head;
return TRUE;
#endif
}
示例4: Sym_Init
/*
==================
Sym_Init
==================
*/
void Sym_Init( long addr )
{
TCHAR moduleName[MAX_STRING_CHARS];
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery( (void*)addr, &mbi, sizeof(mbi) );
GetModuleFileName( (HMODULE)mbi.AllocationBase, moduleName, sizeof( moduleName ) );
char *ext = moduleName + strlen( moduleName );
while( ext > moduleName && *ext != '.' )
{
ext--;
}
if ( ext == moduleName )
{
strcat( moduleName, ".map" );
}
else
{
strcpy( ext, ".map" );
}
module_t *module = (module_t *) malloc( sizeof( module_t ) );
module->name = (char *) malloc( strlen( moduleName ) + 1 );
strcpy( module->name, moduleName );
module->address = (int)mbi.AllocationBase;
module->symbols = NULL;
module->next = modules;
modules = module;
FILE *fp = fopen( moduleName, "rb" );
if ( fp == NULL )
{
return;
}
int pos = ftell( fp );
fseek( fp, 0, SEEK_END );
int length = ftell( fp );
fseek( fp, pos, SEEK_SET );
char *text = (char *) malloc( length+1 );
fread( text, 1, length, fp );
text[length] = '\0';
fclose( fp );
const char *ptr = text;
// skip up to " Address" on a new line
while( *ptr != '\0' )
{
SkipWhiteSpace( &ptr );
if ( idStr::Cmpn( ptr, "Address", 7 ) == 0 )
{
SkipRestOfLine( &ptr );
break;
}
SkipRestOfLine( &ptr );
}
int symbolAddress;
int symbolLength;
char symbolName[MAX_STRING_CHARS];
symbol_t *symbol;
// parse symbols
while( *ptr != '\0' )
{
SkipWhiteSpace( &ptr );
ParseHexNumber( &ptr );
if ( *ptr == ':' )
{
ptr++;
}
else
{
break;
}
ParseHexNumber( &ptr );
SkipWhiteSpace( &ptr );
// parse symbol name
symbolLength = 0;
while( *ptr != '\0' && *ptr != ' ' )
{
symbolName[symbolLength++] = *ptr++;
if ( symbolLength >= sizeof( symbolName ) - 1 )
{
break;
}
}
//.........这里部分代码省略.........
示例5: GetMappedFileName
// Check that the address is backed by a file,
// get the binary's load address,
// get the PE header, assuming there is one,
// see if the last section has been tagged with "DYNINST_REWRITE"
// get trap-table header from last binary section's end - label - size
// sets allocBase to the binary's load address
static struct trap_mapping_header *getStaticTrapMap(unsigned long addr, unsigned long *allocBase)
{
struct trap_mapping_header *header = NULL;
char fileName[ERROR_STRING_LENGTH];
DWORD actualNameLen = 0;
MEMORY_BASIC_INFORMATION memInfo;
int numSections = 0;
PIMAGE_NT_HEADERS peHdr = NULL;
IMAGE_SECTION_HEADER curSecn;
int sidx=0;
char *str=NULL;
//check that the address is backed by a file
actualNameLen = GetMappedFileName(GetCurrentProcess(),
(LPVOID)addr,
fileName,
ERROR_STRING_LENGTH);
if (!actualNameLen) {
fileName[0] = '\0';
goto done; // no file mapped at trap address
}
fileName[ERROR_STRING_LENGTH-1] = '\0';
// get the binary's load address, size
if (!VirtualQuery((LPCVOID)addr, &memInfo, sizeof(memInfo))
|| MEM_COMMIT != memInfo.State)
{
fprintf(stderr, "ERROR IN RTLIB: getStaticTrapMap %s[%d]\n", __FILE__,__LINE__);
goto done; // shouldn't be possible given previous query, but hey
}
*allocBase = (unsigned long) memInfo.AllocationBase;
rtdebug_printf("RTLIB: getStaticTrapMap addr=%lx meminfo.BaseAddress=%lx "
"meminfo.AllocationBase = %lx, memInfo.RegionSize = %lx, "
"%s[%d]\n", addr, memInfo.BaseAddress,
memInfo.AllocationBase, memInfo.RegionSize,
__FILE__,__LINE__);
// get the PE header, assuming there is one
peHdr = ImageNtHeader( memInfo.AllocationBase );
if (!peHdr) {
fprintf(stderr, "ERROR IN RTLIB: getStaticTrapMap %s[%d]\n", __FILE__,__LINE__);
goto done; // no pe header
}
// see if the last section has been tagged with "DYNINST_REWRITE"
numSections = peHdr->FileHeader.NumberOfSections;
curSecn = *(PIMAGE_SECTION_HEADER)
(((unsigned char*)peHdr)
+ sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER)
+ peHdr->FileHeader.SizeOfOptionalHeader
+ sizeof(IMAGE_SECTION_HEADER)*(numSections-1));
//fprintf(stderr, "RTLIB: PE section header address = %lx\n", curSecn);
//fprintf(stderr, "curSecn.chars = %lx %s[%d]\n",curSecn.Characteristics, __FILE__,__LINE__);
if ((sizeof(void*) + 16) > curSecn.SizeOfRawData) {
fprintf(stderr, "ERROR IN RTLIB: getStaticTrapMap %s[%d]\n", __FILE__,__LINE__);
goto done; // last section is uninitialized, doesn't have trap table
}
//fprintf(stderr, "RTLIB %s[%d]\n", __FILE__,__LINE__);
//fprintf(stderr, "RTLIB mi.ab =%lx cs.va =%lx cs.srd=%lx %s[%d]\n", memInfo.AllocationBase, curSecn.VirtualAddress, curSecn.SizeOfRawData, __FILE__,__LINE__);
str = (char*)((long)memInfo.AllocationBase
+ curSecn.VirtualAddress
+ curSecn.SizeOfRawData
- 16);
if (0 != strncmp("DYNINST_REWRITE", str, 15)) {
fprintf(stderr, "ERROR IN RTLIB: getStaticTrapMap found bad string [%s] at %lx %s[%d]\n",
str, str, __FILE__,__LINE__);
goto done; // doesn't have DYNINST_REWRITE label
}
// get trap-table header
header = (struct trap_mapping_header*)
( (unsigned long)memInfo.AllocationBase + *((unsigned long*)(str - sizeof(void*))) );
done:
if (header) {
rtdebug_printf( "RTLIB: found trap map header at %lx: [%lx %lx]\n",
(unsigned long) header, header->low_entry, header->high_entry);
} else {
rtdebug_printf( "ERROR: didn't find trap table\n");
}
return header;
}
示例6: VirtualQuery
/*
* PrintStackdump
* Prints the content of the stack into the logging buffer
*/
void ExceptionTracer::PrintStackdump()
{
// We need the ESP of the exception context to execute a stack dump, make sure we have access to it
if ((context.ContextFlags & CONTEXT_CONTROL) == 0)
return;
static const auto align = sizeof_word; // Stack aligment
static const auto max_words_in_line_magic = stackdump_words_per_line + 10;
MEMORY_BASIC_INFORMATION mbi;
#if !_M_X64
uintptr_t base, bottom, top = (uintptr_t)context.Esp;
#else
uintptr_t base, bottom, top = (uintptr_t)context.Rsp;
#endif
auto words_in_line = max_words_in_line_magic;
// Finds the bottom of the stack from it's base pointer
// Note: mbi will get overriden on this function
auto GetStackBottom = [&mbi](uintptr_t base)
{
VirtualQuery((void*)base, &mbi, sizeof(mbi)); // Find uncommited region of the stack
VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi)); // Find guard page
VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi)); // Find commited region of the stack
auto last = (uintptr_t)mbi.BaseAddress;
return (base + (last - base) + mbi.RegionSize); // base + distanceToLastRegion + lastRegionSize
};
// Prints an CPU word at the specified stack address
auto PrintWord = [this, &words_in_line](uintptr_t addr)
{
if (words_in_line++ >= stackdump_words_per_line)
{
// Print new line only if it's not the first time we enter here (i.e. words_in_line has magical value)
if (words_in_line != max_words_in_line_magic + 1) NewLine();
words_in_line = 1;
Print("0x%p: ", addr);
}
Print(" %p", *(uint32_t*)addr);
};
Print("Stack dump:");
EnterScope();
{
// Makes sure the pointer at top (ESP) is valid and readable memory
if (VirtualQuery((void*)(top), &mbi, sizeof(mbi))
&& (mbi.State & MEM_COMMIT)
&& (mbi.Protect & (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_READWRITE | PAGE_READONLY)) != 0)
{
base = (uintptr_t)mbi.AllocationBase; // Base of the stack (uncommited)
bottom = GetStackBottom(base); // Bottom of the stack (commited)
// Align the stack top (esp) in a 4 bytes boundary
auto remainder = top % align;
uintptr_t current = remainder ? top + (align - remainder) : top;
// on x86 stack grows downward! (i.e. from bottom to base)
for (int n = 0; n < stackdump_max_words && current < bottom; ++n, current += align)
PrintWord(current);
NewLine();
Print("base: 0x%p top: 0x%p bottom: 0x%p", base, top, bottom);
NewLine();
}
}
LeaveScope();
}
示例7: AVMPI_getPrivateResidentPageCount
THIS WILL NOT WORK ON WINCE 6.0 AND ABOVE
#endif
#endif
#ifdef UNDER_CE
// The WinCE version of getPrivateResidentPageCount must do some specific things to get
// an accurate picture of private bytes due to how WinCE lays out memory for the process.
// see http://msdn.microsoft.com/en-us/library/bb331824.aspx for a desccription of how the memory is laid out.
// Note that we are running on Windows Mobile 6.0, but that is based on WinCE 5.0.
// Basically, first we walk the memory for the process slot, from 0x10000 to 0x2000000. Then we walk the memory
// in the large memory area (0x42000000 - 0x80000000), as this is where gcheap allocates memory from.
size_t AVMPI_getPrivateResidentPageCount()
{
void *addr = (void*)(0x00010000);
void *endAddr = (void*)(0x02000000);
size_t bytes=0;
MEMORY_BASIC_INFORMATION mib;
while(true)
{
size_t ret = VirtualQuery(addr, &mib, sizeof(MEMORY_BASIC_INFORMATION));
if(ret == 0)
break;
if((mib.State & MEM_COMMIT))
if ((DWORD)mib.BaseAddress + mib.RegionSize > (DWORD)endAddr)
bytes += (DWORD)endAddr - (DWORD)mib.BaseAddress;
else
bytes += mib.RegionSize;
addr = (void*) ((intptr_t)mib.BaseAddress + mib.RegionSize);
if (addr>=endAddr)
break;
}
MMgc::GCHeap* heap = MMgc::GCHeap::GetGCHeap();
// We need to also walk the shared memory regions to make sure we
// count the blocks we've allocated there
MMgc::GCHeap::Region* curRegion = heap->lastRegion;
if (curRegion)
addr = curRegion->baseAddr;
else
addr = NULL;
while (curRegion!=NULL)
{
addr = curRegion->baseAddr;
if (addr < (void*)0x42000000)
{
// Not in the shared regions
curRegion = curRegion->prev;
continue;
}
while(true)
{
size_t ret = VirtualQuery(addr, &mib, sizeof(MEMORY_BASIC_INFORMATION));
if(ret == 0)
break;
if((mib.State & MEM_COMMIT)) // && (mib.Type & MEM_PRIVATE))
{
if ((DWORD)mib.BaseAddress + mib.RegionSize > (DWORD)curRegion->reserveTop)
bytes += (DWORD)curRegion->reserveTop - (DWORD)mib.BaseAddress;
else
bytes += mib.RegionSize;
}
addr = (void*) ((intptr_t)mib.BaseAddress + mib.RegionSize);
if (addr>=curRegion->reserveTop)
break;
}
curRegion = curRegion->prev;
}
return bytes / VMPI_getVMPageSize();
}
示例8: VxDCall_VMM
//.........这里部分代码省略.........
{
LPVOID address;
BOOL ret;
DWORD psize = getpagesize();
ULONG page = (ULONG) stack32_pop( context );
ULONG npages = (ULONG) stack32_pop( context );
ULONG flags = (ULONG) stack32_pop( context );
TRACE("PageDecommit: page: %08lx, npages: %08lx, flags: %08lx partial stub\n",
page, npages, flags );
address = (LPVOID )( page * psize );
ret = VirtualFree ( address, ( npages * psize ), MEM_DECOMMIT );
TRACE("PageDecommit: Returning: %s\n", ret ? "TRUE" : "FALSE" );
return ret;
}
case 0x000d: /* PageModifyPermissions */
{
DWORD pg_old_perm;
DWORD pg_new_perm;
DWORD virt_old_perm;
DWORD virt_new_perm;
MEMORY_BASIC_INFORMATION mbi;
LPVOID address;
DWORD psize = getpagesize();
ULONG page = stack32_pop ( context );
ULONG npages = stack32_pop ( context );
ULONG permand = stack32_pop ( context );
ULONG permor = stack32_pop ( context );
TRACE("PageModifyPermissions %08lx %08lx %08lx %08lx partial stub\n",
page, npages, permand, permor );
address = (LPVOID )( page * psize );
VirtualQuery ( address, &mbi, sizeof ( MEMORY_BASIC_INFORMATION ));
virt_old_perm = mbi.Protect;
switch ( virt_old_perm & mbi.Protect ) {
case PAGE_READONLY:
case PAGE_EXECUTE:
case PAGE_EXECUTE_READ:
pg_old_perm = PC_USER;
break;
case PAGE_READWRITE:
case PAGE_WRITECOPY:
case PAGE_EXECUTE_READWRITE:
case PAGE_EXECUTE_WRITECOPY:
pg_old_perm = PC_USER | PC_WRITEABLE;
break;
case PAGE_NOACCESS:
default:
pg_old_perm = 0;
break;
}
pg_new_perm = pg_old_perm;
pg_new_perm &= permand & ~PC_STATIC;
pg_new_perm |= permor & ~PC_STATIC;
virt_new_perm = ( virt_old_perm ) & ~0xff;
if ( pg_new_perm & PC_USER )
{
if ( pg_new_perm & PC_WRITEABLE )
virt_new_perm |= PAGE_EXECUTE_READWRITE;
else
virt_new_perm |= PAGE_EXECUTE_READ;
}
示例9: _tWinMain
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, PTSTR, int) {
TCHAR szAppName[] = TEXT("MEM_RESET tester");
TCHAR szTestData[] = TEXT("Some text data");
// Commit a page of storage and modify its contents.
PTSTR pszData = (PTSTR) VirtualAlloc(NULL, 1024,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
_tcscpy_s(pszData, 1024, szTestData);
if (MessageBox(NULL, TEXT("Do you want to access this data later?"),
szAppName, MB_YESNO) == IDNO) {
// We want this page of storage to remain in our process but the
// contents aren't important to us anymore.
// Tell the system that the data is not modified.
// Note: Because MEM_RESET destroys data, VirtualAlloc rounds
// the base address and size parameters to their safest range.
// Here is an example:
// VirtualAlloc(pvData, 5000, MEM_RESET, PAGE_READWRITE)
// resets 0 pages on CPUs where the page size is greater than 4 KB
// and resets 1 page on CPUs with a 4 KB page. So that our call to
// VirtualAlloc to reset memory below always succeeds, VirtualQuery
// is called first to get the exact region size.
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(pszData, &mbi, sizeof(mbi));
VirtualAlloc(pszData, mbi.RegionSize, MEM_RESET, PAGE_READWRITE);
}
// Commit as much storage as there is physical RAM.
MEMORYSTATUS mst;
GlobalMemoryStatus(&mst);
PVOID pvDummy = VirtualAlloc(NULL, mst.dwTotalPhys,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
// Touch all the pages in the dummy region so that any
// modified pages in RAM are written to the paging file.
if (pvDummy != NULL)
ZeroMemory(pvDummy, mst.dwTotalPhys);
// Compare our data page with what we originally wrote there.
if (_tcscmp(pszData, szTestData) == 0) {
// The data in the page matches what we originally put there.
// ZeroMemory forced our page to be written to the paging file.
MessageBox(NULL, TEXT("Modified data page was saved."),
szAppName, MB_OK);
} else {
// The data in the page does NOT match what we originally put there
// ZeroMemory didn't cause our page to be written to the paging file
MessageBox(NULL, TEXT("Modified data page was NOT saved."),
szAppName, MB_OK);
}
// Don't forget to release part of the address space.
// Note that it is not mandatory here since the application is exiting.
if (pvDummy != NULL)
VirtualFree(pvDummy, 0, MEM_RELEASE);
VirtualFree(pszData, 0, MEM_RELEASE);
return(0);
}
示例10: RedirectIAT
bool RedirectIAT( SDLLHook* DLLHook, PIMAGE_IMPORT_DESCRIPTOR pImportDesc, PVOID pBaseLoadAddr )
{
PIMAGE_THUNK_DATA pIAT; // Ptr to import address table
PIMAGE_THUNK_DATA pINT; // Ptr to import names table
PIMAGE_THUNK_DATA pIteratingIAT;
// Figure out which OS platform we're on
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx( &osvi );
// If no import names table, we can't redirect this, so bail
if ( pImportDesc->OriginalFirstThunk == 0 )
return false;
pIAT = MakePtr( PIMAGE_THUNK_DATA, pBaseLoadAddr, pImportDesc->FirstThunk );
pINT = MakePtr( PIMAGE_THUNK_DATA, pBaseLoadAddr, pImportDesc->OriginalFirstThunk );
// Count how many entries there are in this IAT. Array is 0 terminated
pIteratingIAT = pIAT;
unsigned cFuncs = 0;
while ( pIteratingIAT->u1.Function )
{
cFuncs++;
pIteratingIAT++;
}
if ( cFuncs == 0 ) // If no imported functions, we're done!
return false;
// These next few lines ensure that we'll be able to modify the IAT,
// which is often in a read-only section in the EXE.
DWORD flOldProtect, flNewProtect, flDontCare;
MEMORY_BASIC_INFORMATION mbi;
// Get the current protection attributes
VirtualQuery( pIAT, &mbi, sizeof(mbi) );
// remove ReadOnly and ExecuteRead attributes, add on ReadWrite flag
flNewProtect = mbi.Protect;
flNewProtect &= ~(PAGE_READONLY | PAGE_EXECUTE_READ);
flNewProtect |= (PAGE_READWRITE);
if ( !VirtualProtect( pIAT, sizeof(PVOID) * cFuncs,
flNewProtect, &flOldProtect) )
{
return false;
}
// If the Default hook is enabled, build an array of redirection stubs in the processes memory.
DLPD_IAT_STUB * pStubs = 0;
if ( DLLHook->UseDefault )
{
// Allocate memory for the redirection stubs. Make one extra stub at the
// end to be a sentinel
pStubs = new DLPD_IAT_STUB[ cFuncs + 1];
if ( !pStubs )
return false;
}
// Scan through the IAT, completing the stubs and redirecting the IAT
// entries to point to the stubs
pIteratingIAT = pIAT;
while ( pIteratingIAT->u1.Function )
{
void* HookFn = 0; // Set to either the SFunctionHook or pStubs.
if ( !IMAGE_SNAP_BY_ORDINAL( pINT->u1.Ordinal ) ) // import by name
{
PIMAGE_IMPORT_BY_NAME pImportName = MakePtr( PIMAGE_IMPORT_BY_NAME, pBaseLoadAddr, pINT->u1.AddressOfData );
// Iterate through the hook functions, searching for this import.
SFunctionHook* FHook = DLLHook->Functions;
while ( FHook->Name )
{
if ( lstrcmpi( FHook->Name, (char*)pImportName->Name ) == 0 )
{
OutputDebugString( "Hooked function: " );
OutputDebugString( (char*)pImportName->Name );
OutputDebugString( "\n" );
// Save the old function in the SFunctionHook structure and get the new one.
FHook->OrigFn = (void*)pIteratingIAT->u1.Function;
HookFn = (PIMAGE_IMPORT_BY_NAME)FHook->HookFn;
break;
}
FHook++;
}
// If the default function is enabled, store the name for the user.
if ( DLLHook->UseDefault )
pStubs->pszNameOrOrdinal = (DWORD)&pImportName->Name;
}
else
{
// If the default function is enabled, store the ordinal for the user.
if ( DLLHook->UseDefault )
pStubs->pszNameOrOrdinal = pINT->u1.Ordinal;
//.........这里部分代码省略.........
示例11: switch
//.........这里部分代码省略.........
break;
}
case PSTATE_GAMEDEFS_SIGNATURES_SIG:
{
if (TempSig.library[0] == '\0')
{
strncopy(TempSig.library, "server", sizeof(TempSig.library));
}
void *addressInBase = nullptr;
if (strcmp(TempSig.library, "server") == 0)
{
addressInBase = reinterpret_cast<void*>(MDLL_Spawn);
}
else if (strcmp(TempSig.library, "engine") == 0)
{
addressInBase = reinterpret_cast<void*>(gpGlobals);
}
void *finalAddress = nullptr;
if (!addressInBase)
{
AMXXLOG_Error("Unrecognized library \"%s\" (gameconf \"%s\")", TempSig.library, m_CurrentPath);
}
else if (TempSig.signature[0])
{
if (TempSig.signature[0] == '@')
{
#if defined PLATFORM_WINDOWS
MEMORY_BASIC_INFORMATION mem;
if (VirtualQuery(addressInBase, &mem, sizeof(mem)))
{
finalAddress = g_MemUtils.ResolveSymbol(mem.AllocationBase, &TempSig.signature[1]);
}
else
{
AMXXLOG_Error("Unable to find library \"%s\" in memory (gameconf \"%s\")", TempSig.library, m_File);
}
#elif defined PLATFORM_POSIX
Dl_info info;
if (dladdr(addressInBase, &info) != 0)
{
void *handle = dlopen(info.dli_fname, RTLD_NOW);
if (handle)
{
finalAddress = g_MemUtils.ResolveSymbol(handle, &TempSig.signature[1]);
dlclose(handle);
}
else
{
AMXXLOG_Error("Unable to load library \"%s\" (gameconf \"%s\")", TempSig.library, m_File);
}
}
else
{
AMXXLOG_Error("Unable to find library \"%s\" in memory (gameconf \"%s\")", TempSig.library, m_File);
}
#endif
}
示例12: sampgdk_get_plugin_handle
SAMPGDK_EXPORT void *SAMPGDK_CALL sampgdk_get_plugin_handle(void *symbol) {
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(symbol, &mbi, sizeof(mbi));
return (void*)mbi.AllocationBase;
}
示例13: RecordExceptionInfo
// Entry point into the main exception handling routine. This routine is put into an except()
// statment at the beginning of a thread and is called anytime that there is a program exception
// The data is stored in a file called ErrorLog.txt in the data directory.
//
// data: pointer to the exception data
// Message: Any message that should be printed out in the error log file
//
// returns:
//
int __cdecl RecordExceptionInfo(PEXCEPTION_POINTERS data, const char *Message)
{
static bool BeenHere = false;
// Going recursive! That must mean this routine crashed!
if (BeenHere) {
return EXCEPTION_CONTINUE_SEARCH;
}
BeenHere = true;
char ModuleName[MAX_PATH];
char FileName[MAX_PATH] = "Unknown";
// Create a filename to record the error information to.
// Storing it in the executable directory works well.
if (GetModuleFileName(0, ModuleName, sizeof(ModuleName)) <= 0) {
ModuleName[0] = 0;
}
char *FilePart = GetFilePart(ModuleName);
// Extract the file name portion and remove it's file extension. We'll
// use that name shortly.
lstrcpy(FileName, FilePart);
char *lastperiod = strrchr(FileName, '.');
if (lastperiod) {
lastperiod[0] = 0;
}
// Replace the executable filename with our error log file name.
lstrcpy(FilePart, "errorlog.txt");
HANDLE LogFile = CreateFile(ModuleName, GENERIC_WRITE, 0, 0,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if (LogFile == INVALID_HANDLE_VALUE) {
OutputDebugString("Error creating exception report");
return EXCEPTION_CONTINUE_SEARCH;
}
// Append to the error log.
SetFilePointer(LogFile, 0, 0, FILE_END);
// Print out some blank lines to separate this error log from any previous ones.
hprintf(LogFile, "\r\n\r\n\r\n\r\n");
PEXCEPTION_RECORD Exception = data->ExceptionRecord;
PCONTEXT Context = data->ContextRecord;
char CrashModulePathName[MAX_PATH];
char *CrashModuleFileName = "Unknown";
MEMORY_BASIC_INFORMATION MemInfo;
// VirtualQuery can be used to get the allocation base associated with a
// code address, which is the same as the ModuleHandle. This can be used
// to get the filename of the module that the crash happened in.
if (VirtualQuery((void*)Context->Eip, &MemInfo, sizeof(MemInfo)) && GetModuleFileName((HINSTANCE)MemInfo.AllocationBase, CrashModulePathName, sizeof(CrashModulePathName)) > 0) {
CrashModuleFileName = GetFilePart(CrashModulePathName);
}
// Print out the beginning of the error log in a Win95 error window
// compatible format.
hprintf(LogFile, "%s caused %s in module %s at %04x:%08x.\r\n",
FileName, GetExceptionDescription(Exception->ExceptionCode),
CrashModuleFileName, Context->SegCs, Context->Eip);
hprintf(LogFile, "Exception handler called in %s.\r\n", Message);
RecordSystemInformation(LogFile);
// If the exception was an access violation, print out some additional
// information, to the error log and the debugger.
if (Exception->ExceptionCode == STATUS_ACCESS_VIOLATION && Exception->NumberParameters >= 2) {
char DebugMessage[1000];
const char* readwrite = "Read from";
if (Exception->ExceptionInformation[0]) {
readwrite = "Write to";
}
wsprintf(DebugMessage, "%s location %08x caused an access violation.\r\n", readwrite, Exception->ExceptionInformation[1]);
#ifdef _DEBUG
// The VisualC++ debugger doesn't actually tell you whether a read
// or a write caused the access violation, nor does it tell what
// address was being read or written. So I fixed that.
OutputDebugString("Exception handler: ");
OutputDebugString(DebugMessage);
#endif
hprintf(LogFile, "%s", DebugMessage);
}
// Print out the register values in a Win95 error window compatible format.
hprintf(LogFile, "\r\n");
hprintf(LogFile, "Registers:\r\n");
hprintf(LogFile, "EAX=%08x CS=%04x EIP=%08x EFLGS=%08x\r\n",
Context->Eax, Context->SegCs, Context->Eip, Context->EFlags);
hprintf(LogFile, "EBX=%08x SS=%04x ESP=%08x EBP=%08x\r\n",
Context->Ebx, Context->SegSs, Context->Esp, Context->Ebp);
//.........这里部分代码省略.........
示例14: VirtualQuery
bool CDetour::Detour(BYTE *&jmp, BYTE *&orig, const BYTE *&det, int iPatchType, int len)
{
DWORD dwBack = 0;
int i = 0;
BYTE *pPatchBuf = NULL;
// Allocate space for the jump
jmp = (BYTE*)malloc(len+5);
// Force page protection flags to read|write
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery( ( void* )orig, &mbi, sizeof( mbi ) );
VirtualProtect( mbi.BaseAddress, mbi.RegionSize, PAGE_READWRITE, &mbi.Protect );
// Copy the overwritten opcodes at the original to the malloced space
memcpy(jmp, orig, len);
// Increment to the end of the opcodes at the malloced space
jmp += len;
// Place a jump back to the original at this point
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = (DWORD)(orig+len - jmp) - 5;
// Generate a random opcode
int iTmpRnd = (rand() * 0xFF) + rand();
BYTE bTmpRnd = (BYTE)iTmpRnd;
// Place a jump at the original to the detour function
pPatchBuf = new BYTE[len];
// Pad out the bytes with NOPs so we don't have ends of intructions
memset(pPatchBuf, 0x90, len);
// Write the opcodes to the buffer according to patch type
switch(iPatchType)
{
case DETOUR_TYPE_JMP:
pPatchBuf[0] = '\xE9';
*(DWORD*)&pPatchBuf[1] = (DWORD)(det - orig) - 5;
break;
case DETOUR_TYPE_PUSH_RET:
pPatchBuf[0] = '\x68';
*(DWORD*)&pPatchBuf[1] = (DWORD)det;
pPatchBuf[5] = '\xC3';
break;
case DETOUR_TYPE_NOP_JMP:
pPatchBuf[0] = '\x90';
pPatchBuf[1] = '\xE9';
*(DWORD*)&pPatchBuf[2] = (DWORD)(det - orig) - 6;
break;
case DETOUR_TYPE_NOP_NOP_JMP:
pPatchBuf[0] = '\x90';
pPatchBuf[1] = '\x90';
pPatchBuf[2] = '\xE9';
*(DWORD*)&pPatchBuf[3] = (DWORD)(det - orig) - 7;
break;
case DETOUR_TYPE_STC_JC:
pPatchBuf[0] = '\xF9';
pPatchBuf[1] = '\x0F';
pPatchBuf[2] = '\x82';
*(DWORD*)&pPatchBuf[3] = (DWORD)(det - orig) - 7;
break;
case DETOUR_TYPE_CLC_JNC:
pPatchBuf[0] = '\xF8';
pPatchBuf[1] = '\x0F';
pPatchBuf[2] = '\x83';
*(DWORD*)&pPatchBuf[3] = (DWORD)(det - orig) - 7;
break;
case DETOUR_TYPE_OBS_ADD:
pPatchBuf[0] = '\xB8'; //mov eax
*(DWORD*)&pPatchBuf[1] = iTmpRnd;
pPatchBuf[5] = '\x05'; //add eax
*(int*)&pPatchBuf[6] = (DWORD)det - iTmpRnd;
pPatchBuf[10] = '\xFF'; //jmp eax
pPatchBuf[11] = '\xE0';
break;
case DETOUR_TYPE_OBS_XOR:
pPatchBuf[0] = '\x33'; //xor eax, eax
pPatchBuf[1] = '\xC0';
pPatchBuf[2] = '\x2D'; //sub eax
*(int*)&pPatchBuf[3] = (int)iTmpRnd;
pPatchBuf[7] = '\x35'; //xor eax
*(DWORD*)&pPatchBuf[8] = (DWORD)det ^ (-iTmpRnd);
pPatchBuf[12] = '\xFF'; //jmp eax
pPatchBuf[13] = '\xE0';
break;
case DETOUR_TYPE_OBS_STACKADD:
pPatchBuf[0] = '\x68'; //push
*(DWORD*)&pPatchBuf[1] = (DWORD)iTmpRnd;
pPatchBuf[5] = '\x81'; //xor dword ptr [esp]
pPatchBuf[6] = '\x34';
//.........这里部分代码省略.........
示例15: AVMPI_getThreadStackBase
uintptr_t AVMPI_getThreadStackBase()
{
MEMORY_BASIC_INFORMATION __mib;
VirtualQuery(&__mib, &__mib, sizeof(MEMORY_BASIC_INFORMATION));
return (uintptr_t)__mib.BaseAddress + __mib.RegionSize;
}