language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
C++
x64dbg-development/src/dbg/main.cpp
/** @file main.cpp @brief Implements the main class. */ #include "debugger.h" extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if(fdwReason == DLL_PROCESS_ATTACH) { hInst = hinstDLL; // Get program directory strcpy_s(szUserDir, StringUtils::Utf16ToUtf8(BridgeUserDirectory()).c_str()); { wchar_t wszDir[deflen] = L""; if(GetModuleFileNameW(hInst, wszDir, deflen)) { strcpy_s(szProgramDir, StringUtils::Utf16ToUtf8(wszDir).c_str()); int len = (int)strlen(szProgramDir); while(szProgramDir[len] != '\\') len--; szProgramDir[len] = 0; } } // https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-disablethreadlibrarycalls DisableThreadLibraryCalls(hinstDLL); } return TRUE; }
C++
x64dbg-development/src/dbg/memory.cpp
/** @file memory.cpp @brief Implements the memory class. */ #include "memory.h" #include "debugger.h" #include "patches.h" #include "threading.h" #include "thread.h" #include "module.h" #include "taskthread.h" #include "value.h" #define PAGE_SHIFT (12) //#define PAGE_SIZE (4096) #define PAGE_ALIGN(Va) ((ULONG_PTR)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1))) #define BYTES_TO_PAGES(Size) (((Size) >> PAGE_SHIFT) + (((Size) & (PAGE_SIZE - 1)) != 0)) #define ROUND_TO_PAGES(Size) (((ULONG_PTR)(Size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)) static ULONG fallbackCookie = 0; std::map<Range, MEMPAGE, RangeCompare> memoryPages; bool bListAllPages = false; bool bQueryWorkingSet = false; static std::vector<MEMPAGE> QueryMemPages() { // First gather all possible pages in the memory range std::vector<MEMPAGE> pages; pages.reserve(200); //TODO: provide a better estimate SIZE_T numBytes = 0; duint pageStart = 0; duint allocationBase = 0; do { if(!DbgIsDebugging()) return {}; // Query memory attributes MEMORY_BASIC_INFORMATION mbi; memset(&mbi, 0, sizeof(mbi)); numBytes = VirtualQueryEx(fdProcessInfo->hProcess, (LPVOID)pageStart, &mbi, sizeof(mbi)); // Only allow pages that are committed/reserved (exclude free memory) if(mbi.State != MEM_FREE) { auto bReserved = mbi.State == MEM_RESERVE; //check if the current page is reserved. auto bPrevReserved = pages.size() ? pages.back().mbi.State == MEM_RESERVE : false; //back if the previous page was reserved (meaning this one won't be so it has to be added to the map) // Only list allocation bases, unless if forced to list all if(bListAllPages || bReserved || bPrevReserved || allocationBase != duint(mbi.AllocationBase)) { // Set the new allocation base page allocationBase = duint(mbi.AllocationBase); MEMPAGE curPage; memset(&curPage, 0, sizeof(MEMPAGE)); memcpy(&curPage.mbi, &mbi, sizeof(mbi)); if(bReserved) { if(duint(curPage.mbi.BaseAddress) != allocationBase) sprintf_s(curPage.info, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Reserved (%p)")), allocationBase); else strcpy_s(curPage.info, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Reserved"))); } else if(!ModNameFromAddr(pageStart, curPage.info, true)) { // Module lookup failed; check if it's a file mapping wchar_t szMappedName[sizeof(curPage.info)] = L""; if((mbi.Type == MEM_MAPPED) && (GetMappedFileNameW(fdProcessInfo->hProcess, mbi.AllocationBase, szMappedName, MAX_MODULE_SIZE) != 0)) { auto bFileNameOnly = false; //TODO: setting for this auto fileStart = wcsrchr(szMappedName, L'\\'); if(bFileNameOnly && fileStart) strcpy_s(curPage.info, StringUtils::Utf16ToUtf8(fileStart + 1).c_str()); else strcpy_s(curPage.info, StringUtils::Utf16ToUtf8(szMappedName).c_str()); } } pages.push_back(curPage); } else { // Otherwise append the page to the last created entry if(pages.size()) //make sure to not dereference an invalid pointer pages.back().mbi.RegionSize += mbi.RegionSize; } } // Calculate the next page start duint newAddress = duint(mbi.BaseAddress) + mbi.RegionSize; if(newAddress <= pageStart) break; pageStart = newAddress; } while(numBytes); return pages; } static void ProcessFileSections(std::vector<MEMPAGE> & pageVector) { if(pageVector.empty()) return; const auto pagecount = (int)pageVector.size(); // NOTE: this iteration is backwards for(int i = pagecount - 1; i > -1; i--) { if(!DbgIsDebugging()) return; auto & currentPage = pageVector.at(i); // Nothing to do for reserved or free pages if(currentPage.mbi.State == MEM_RESERVE || currentPage.mbi.State == MEM_FREE) continue; auto pageBase = duint(currentPage.mbi.BaseAddress); auto pageSize = currentPage.mbi.RegionSize; // Retrieve module info duint modBase = 0; std::vector<MODSECTIONINFO> sections; duint sectionAlignment = 0; duint modSize = 0; duint sizeOfImage = 0; { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(pageBase); // Nothing to do for non-modules if(!modInfo) continue; modBase = modInfo->base; modSize = modInfo->size; sections = modInfo->sections; if(modInfo->headers) { sectionAlignment = modInfo->headers->OptionalHeader.SectionAlignment; sizeOfImage = ROUND_TO_PAGES(modInfo->headers->OptionalHeader.SizeOfImage); } else { // This appears to happen under unknown circumstances // https://github.com/x64dbg/x64dbg/issues/2945 // https://github.com/x64dbg/x64dbg/issues/2931 sectionAlignment = 0x1000; sizeOfImage = modSize; // Spam the user with errors to hopefully get more information std::string summary; summary = StringUtils::sprintf("The module at %p (%s%s) triggers a weird bug, please report an issue\n", modBase, modInfo->name, modInfo->extension); GuiAddLogMessage(summary.c_str()); } } // Nothing to do if the module doesn't have sections if(sections.empty()) continue; // It looks like a section alignment of 0x10000 becomes PAGE_SIZE in reality // The rest of the space is mapped as RESERVED sectionAlignment = min(sectionAlignment, PAGE_SIZE); auto sectionAlign = [sectionAlignment](duint value) { return (value + (sectionAlignment - 1)) & ~(sectionAlignment - 1); }; // Align the sections for(size_t j = 0; j < sections.size(); j++) { auto & section = sections[j]; section.addr = sectionAlign(section.addr); section.size = (section.size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); // Extend the last section to SizeOfImage under the right circumstances if(j + 1 == sections.size() && sectionAlignment < PAGE_SIZE) { auto totalSize = section.addr + section.size; totalSize -= modBase; if(sizeOfImage > totalSize) section.size += sizeOfImage - totalSize; } } // Section view if(!bListAllPages) { std::vector<MEMPAGE> newPages; newPages.reserve(sections.size() + 1); // Insert a page for the header if this is the header page if(pageBase == modBase) { MEMPAGE headerPage = {}; VirtualQueryEx(fdProcessInfo->hProcess, (LPCVOID)modBase, &headerPage.mbi, sizeof(MEMORY_BASIC_INFORMATION)); headerPage.mbi.RegionSize = min(sections.front().addr - modBase, pageSize); strcpy_s(headerPage.info, currentPage.info); newPages.push_back(headerPage); } // Insert pages for the sections for(const auto & section : sections) { // Only insert the sections that are within the current page if(section.addr >= pageBase && section.addr + section.size <= pageBase + currentPage.mbi.RegionSize) { MEMPAGE sectionPage = {}; VirtualQueryEx(fdProcessInfo->hProcess, (LPCVOID)section.addr, &sectionPage.mbi, sizeof(MEMORY_BASIC_INFORMATION)); sectionPage.mbi.BaseAddress = (PVOID)section.addr; sectionPage.mbi.RegionSize = section.size; sprintf_s(sectionPage.info, " \"%s\"", section.name); newPages.push_back(sectionPage); } } // Make sure the total size matches the new fake pages size_t totalSize = 0; for(const auto & page : newPages) totalSize += page.mbi.RegionSize; // Replace the single module page with the sections // newPages should never be empty, but try to avoid data loss if it is if(!newPages.empty() && totalSize == pageSize) { pageVector.erase(pageVector.begin() + i); // remove the SizeOfImage page pageVector.insert(pageVector.begin() + i, newPages.begin(), newPages.end()); } else { // Report an error to make it easier to debug auto summary = StringUtils::sprintf("Error replacing page: %p[%p] (%s)\n", pageBase, pageSize, currentPage.info); summary += "Sections:\n"; for(const auto & section : sections) summary += StringUtils::sprintf(" \"%s\": %p[%p]\n", section.name, section.addr, section.size); summary += "New pages:\n"; for(const auto & page : newPages) summary += StringUtils::sprintf(" \"%s\": %p[%p]\n", page.info, page.mbi.BaseAddress, page.mbi.RegionSize); summary += "Please report an issue!\n"; GuiAddLogMessage(summary.c_str()); strncat_s(currentPage.info, " (error, see log)", _TRUNCATE); } } // List all pages else { size_t infoOffset = 0; // Display module name in first region (useful if PE header and first section have same protection) if(pageBase == modBase) infoOffset = strlen(currentPage.info); for(size_t j = 0; j < sections.size() && infoOffset + 1 < _countof(currentPage.info); j++) { const auto & currentSection = sections.at(j); duint sectionStart = currentSection.addr; duint sectionEnd = sectionStart + currentSection.size; // Check if the section and page overlap if(pageBase < sectionEnd && pageBase + pageSize > sectionStart) { if(infoOffset) infoOffset += _snprintf_s(currentPage.info + infoOffset, sizeof(currentPage.info) - infoOffset, _TRUNCATE, ","); infoOffset += _snprintf_s(currentPage.info + infoOffset, sizeof(currentPage.info) - infoOffset, _TRUNCATE, " \"%s\"", currentSection.name); } } } } } #define MAX_HEAPS 1000 static void ProcessSystemPages(std::vector<MEMPAGE> & pageVector) { THREADLIST threadList; ThreadGetList(&threadList); auto pebBase = (duint)GetPEBLocation(fdProcessInfo->hProcess); std::vector<duint> stackAddrs; for(int i = 0; i < threadList.count; i++) { DWORD threadId = threadList.list[i].BasicInfo.ThreadId; // Read TEB::Tib to get stack information NT_TIB tib; if(!ThreadGetTib(threadList.list[i].BasicInfo.ThreadLocalBase, &tib)) tib.StackLimit = nullptr; // The stack will be a specific range only, not always the base address stackAddrs.push_back((duint)tib.StackLimit); } ULONG NumberOfHeaps = 0; MemRead(pebBase + offsetof(PEB, NumberOfHeaps), &NumberOfHeaps, sizeof(NumberOfHeaps)); duint ProcessHeapsPtr = 0; MemRead(pebBase + offsetof(PEB, ProcessHeaps), &ProcessHeapsPtr, sizeof(ProcessHeapsPtr)); duint ProcessHeaps[MAX_HEAPS] = {}; auto HeapCount = min(_countof(ProcessHeaps), NumberOfHeaps); MemRead(ProcessHeapsPtr, ProcessHeaps, sizeof(duint) * HeapCount); std::unordered_map<duint, uint32_t> processHeapIds; for(uint32_t i = 0; i < HeapCount; i++) processHeapIds.emplace(ProcessHeaps[i], i); for(auto & page : pageVector) { const duint pageBase = (duint)page.mbi.BaseAddress; const duint pageSize = (duint)page.mbi.RegionSize; auto inRange = [pageBase, pageSize](duint addr) { return addr >= pageBase && addr < pageBase + pageSize; }; auto appendInfo = [&page](const char* str) { if(*page.info) { strncat_s(page.info, ", ", _TRUNCATE); } strncat_s(page.info, str, _TRUNCATE); }; // Check for windows specific data if(inRange(0x7FFE0000)) { appendInfo("KUSER_SHARED_DATA"); continue; } // Mark PEB if(inRange(pebBase)) { appendInfo("PEB"); } // Check in threads char temp[256] = ""; for(int i = 0; i < threadList.count; i++) { DWORD threadId = threadList.list[i].BasicInfo.ThreadId; auto tidStr = formatpidtid(threadId); // Mark TEB // // TebBase: Points to 32/64 TEB // TebBaseWow64: Points to 64 TEB in a 32bit process duint tebBase = threadList.list[i].BasicInfo.ThreadLocalBase; duint tebBaseWow64 = tebBase - (2 * PAGE_SIZE); if(inRange(tebBase)) { sprintf_s(temp, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "TEB (%s)")), tidStr.c_str()); appendInfo(temp); } if(inRange(tebBaseWow64)) { #ifndef _WIN64 sprintf_s(temp, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "WoW64 TEB (%s)")), tidStr.c_str()); appendInfo(temp); #endif //_WIN64 } // The stack will be a specific range only, not always the base address duint stackAddr = stackAddrs[i]; if(inRange(stackAddr)) { sprintf_s(temp, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Stack (%s)")), tidStr.c_str()); appendInfo(temp); } } auto heapItr = processHeapIds.find(pageBase); if(heapItr != processHeapIds.end()) { sprintf_s(temp, "Heap (ID %u)", heapItr->second); appendInfo(temp); } } // Only free thread data if it was allocated if(threadList.list) BridgeFree(threadList.list); } void MemUpdateMap() { // First gather all possible pages in the memory range std::vector<MEMPAGE> pageVector = QueryMemPages(); // Process file sections ProcessFileSections(pageVector); // Get a list of threads for information about Kernel/PEB/TEB/Stack ranges ProcessSystemPages(pageVector); // Convert the vector to a map EXCLUSIVE_ACQUIRE(LockMemoryPages); memoryPages.clear(); for(const auto & page : pageVector) { duint start = (duint)page.mbi.BaseAddress; duint size = (duint)page.mbi.RegionSize; memoryPages.insert(std::make_pair(std::make_pair(start, start + size - 1), page)); } } static DWORD WINAPI memUpdateMap() { if(DbgIsDebugging()) { MemUpdateMap(); GuiUpdateMemoryView(); } return 0; } void MemUpdateMapAsync() { static TaskThread_<decltype(&memUpdateMap)> memUpdateMapTask(&memUpdateMap, 1000); memUpdateMapTask.WakeUp(); } duint MemFindBaseAddr(duint Address, duint* Size, bool Refresh, bool FindReserved) { // Update the memory map if needed if(Refresh) MemUpdateMap(); SHARED_ACQUIRE(LockMemoryPages); // Search for the memory page address auto found = memoryPages.find(std::make_pair(Address, Address)); if(found == memoryPages.end()) return 0; if(!FindReserved && found->second.mbi.State == MEM_RESERVE) //check if the current page is reserved. return 0; // Return the allocation region size when requested if(Size) *Size = found->second.mbi.RegionSize; return found->first.first; } //http://www.triplefault.io/2017/08/detecting-debuggers-by-abusing-bad.html //TODO: name this function properly static bool IgnoreThisRead(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead) { typedef BOOL(WINAPI * QUERYWORKINGSETEX)(HANDLE, PVOID, DWORD); static auto fnQueryWorkingSetEx = QUERYWORKINGSETEX(GetProcAddress(GetModuleHandleW(L"psapi.dll"), "QueryWorkingSetEx")); if(!bQueryWorkingSet || !fnQueryWorkingSetEx) return false; PSAPI_WORKING_SET_EX_INFORMATION wsi; wsi.VirtualAddress = (PVOID)PAGE_ALIGN(lpBaseAddress); if(fnQueryWorkingSetEx(hProcess, &wsi, sizeof(wsi)) && !wsi.VirtualAttributes.Valid) { MEMORY_BASIC_INFORMATION mbi; if(VirtualQueryEx(hProcess, wsi.VirtualAddress, &mbi, sizeof(mbi)) && mbi.State == MEM_COMMIT/* && mbi.Type == MEM_PRIVATE*/) { memset(lpBuffer, 0, nSize); if(lpNumberOfBytesRead) *lpNumberOfBytesRead = nSize; return true; } } return false; } bool MemoryReadSafePage(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead) { #if 0 //TODO: remove when proven stable, this function checks if reads are always within page boundaries auto base = duint(lpBaseAddress); if(nSize > PAGE_SIZE - (base & (PAGE_SIZE - 1))) __debugbreak(); #endif if(IgnoreThisRead(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead)) return true; return MemoryReadSafe(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); } bool MemRead(duint BaseAddress, void* Buffer, duint Size, duint* NumberOfBytesRead, bool cache) { if(!MemIsCanonicalAddress(BaseAddress) || !DbgIsDebugging()) return false; if(cache && !MemIsValidReadPtr(BaseAddress, true)) return false; if(!Buffer || !Size) return false; duint bytesReadTemp = 0; if(!NumberOfBytesRead) NumberOfBytesRead = &bytesReadTemp; duint offset = 0; duint requestedSize = Size; duint sizeLeftInFirstPage = PAGE_SIZE - (BaseAddress & (PAGE_SIZE - 1)); duint readSize = min(sizeLeftInFirstPage, requestedSize); while(readSize) { SIZE_T bytesRead = 0; auto readSuccess = MemoryReadSafePage(fdProcessInfo->hProcess, (PVOID)(BaseAddress + offset), (PBYTE)Buffer + offset, readSize, &bytesRead); *NumberOfBytesRead += bytesRead; if(!readSuccess) break; offset += readSize; requestedSize -= readSize; readSize = min(PAGE_SIZE, requestedSize); if(readSize && (BaseAddress + offset) % PAGE_SIZE) __debugbreak(); //TODO: remove when proven stable, this checks if (BaseAddress + offset) is aligned to PAGE_SIZE after the first call } auto success = *NumberOfBytesRead == Size; SetLastError(success ? ERROR_SUCCESS : ERROR_PARTIAL_COPY); return success; } bool MemReadUnsafePage(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead) { //TODO: remove when proven stable, this function checks if reads are always within page boundaries auto base = duint(lpBaseAddress); if(nSize > PAGE_SIZE - (base & (PAGE_SIZE - 1))) __debugbreak(); if(IgnoreThisRead(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead)) return true; return !!ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); } bool MemReadUnsafe(duint BaseAddress, void* Buffer, duint Size, duint* NumberOfBytesRead) { if(!MemIsCanonicalAddress(BaseAddress) || BaseAddress < PAGE_SIZE || !DbgIsDebugging()) return false; if(!Buffer || !Size) return false; duint bytesReadTemp = 0; if(!NumberOfBytesRead) NumberOfBytesRead = &bytesReadTemp; duint offset = 0; duint requestedSize = Size; duint sizeLeftInFirstPage = PAGE_SIZE - (BaseAddress & (PAGE_SIZE - 1)); duint readSize = min(sizeLeftInFirstPage, requestedSize); while(readSize) { SIZE_T bytesRead = 0; auto readSuccess = MemReadUnsafePage(fdProcessInfo->hProcess, (PVOID)(BaseAddress + offset), (PBYTE)Buffer + offset, readSize, &bytesRead); *NumberOfBytesRead += bytesRead; if(!readSuccess) break; offset += readSize; requestedSize -= readSize; readSize = min(PAGE_SIZE, requestedSize); if(readSize && (BaseAddress + offset) % PAGE_SIZE) __debugbreak(); //TODO: remove when proven stable, this checks if (BaseAddress + offset) is aligned to PAGE_SIZE after the first call } auto success = *NumberOfBytesRead == Size; SetLastError(success ? ERROR_SUCCESS : ERROR_PARTIAL_COPY); return success; } static bool MemoryWriteSafePage(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten) { //TODO: remove when proven stable, this function checks if writes are always within page boundaries auto base = duint(lpBaseAddress); if(nSize > PAGE_SIZE - (base & (PAGE_SIZE - 1))) __debugbreak(); return MemoryWriteSafe(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten); } bool MemWrite(duint BaseAddress, const void* Buffer, duint Size, duint* NumberOfBytesWritten) { if(!MemIsCanonicalAddress(BaseAddress)) return false; if(!Buffer || !Size) return false; SIZE_T bytesWrittenTemp = 0; if(!NumberOfBytesWritten) NumberOfBytesWritten = &bytesWrittenTemp; duint offset = 0; duint requestedSize = Size; duint sizeLeftInFirstPage = PAGE_SIZE - (BaseAddress & (PAGE_SIZE - 1)); duint writeSize = min(sizeLeftInFirstPage, requestedSize); while(writeSize) { SIZE_T bytesWritten = 0; auto writeSuccess = MemoryWriteSafePage(fdProcessInfo->hProcess, (PVOID)(BaseAddress + offset), (PBYTE)Buffer + offset, writeSize, &bytesWritten); *NumberOfBytesWritten += bytesWritten; if(!writeSuccess) break; offset += writeSize; requestedSize -= writeSize; writeSize = min(PAGE_SIZE, requestedSize); if(writeSize && (BaseAddress + offset) % PAGE_SIZE) __debugbreak(); //TODO: remove when proven stable, this checks if (BaseAddress + offset) is aligned to PAGE_SIZE after the first call } auto success = *NumberOfBytesWritten == Size; SetLastError(success ? ERROR_SUCCESS : ERROR_PARTIAL_COPY); return success; } bool MemPatch(duint BaseAddress, const void* Buffer, duint Size, duint* NumberOfBytesWritten) { // Buffer and size must be valid if(!Buffer || Size <= 0) return false; // Allocate the memory Memory<unsigned char*> oldData(Size, "mempatch:oldData"); if(!MemRead(BaseAddress, oldData(), Size)) { // If no memory can be read, no memory can be written. Fail out // of this function. return false; } // Are we able to write on this page? if(MemWrite(BaseAddress, Buffer, Size, NumberOfBytesWritten)) { for(duint i = 0; i < Size; i++) PatchSet(BaseAddress + i, oldData()[i], ((const unsigned char*)Buffer)[i]); // Done return true; } // Unable to write memory return false; } bool MemIsValidReadPtr(duint Address, bool cache) { if(cache) return MemFindBaseAddr(Address, nullptr) != 0; unsigned char ch; return MemRead(Address, &ch, sizeof(ch)); } bool MemIsValidReadPtrUnsafe(duint Address, bool cache) { if(cache) return MemFindBaseAddr(Address, nullptr) != 0; unsigned char ch; return MemReadUnsafe(Address, &ch, sizeof(ch)); } bool MemIsCanonicalAddress(duint Address) { #ifndef _WIN64 // 32-bit mode only supports 4GB max, so limits are // not an issue return true; #else // The most-significant 16 bits must be all 1 or all 0. // (64 - 16) = 48bit linear address range. // // 0xFFFF800000000000 = Significant 16 bits set // 0x0000800000000000 = 48th bit set return (((Address & 0xFFFF800000000000) + 0x800000000000) & ~0x800000000000) == 0; #endif //_WIN64 } bool MemIsCodePage(duint Address, bool Refresh) { MEMPAGE pageInfo; if(!MemGetPageInfo(Address, &pageInfo, Refresh)) return false; return (pageInfo.mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0; } duint MemAllocRemote(duint Address, duint Size, DWORD Type, DWORD Protect) { return (duint)VirtualAllocEx(fdProcessInfo->hProcess, (LPVOID)Address, Size, Type, Protect); } bool MemFreeRemote(duint Address) { return !!VirtualFreeEx(fdProcessInfo->hProcess, (LPVOID)Address, 0, MEM_RELEASE); } bool MemGetPageInfo(duint Address, MEMPAGE* PageInfo, bool Refresh) { // Update the memory map if needed if(Refresh) MemUpdateMap(); SHARED_ACQUIRE(LockMemoryPages); // Search for the memory page address auto found = memoryPages.find(std::make_pair(Address, Address)); if(found == memoryPages.end()) return false; // Return the data when possible if(PageInfo) *PageInfo = found->second; return true; } bool MemSetPageRights(duint Address, const char* Rights) { DWORD protect; if(!MemPageRightsFromString(&protect, Rights)) return false; return MemSetProtect(Address, protect, PAGE_SIZE); } bool MemGetPageRights(duint Address, char* Rights) { unsigned int protect = 0; if(!MemGetProtect(Address, true, false, &protect)) return false; return MemPageRightsToString(protect, Rights); } bool MemPageRightsToString(DWORD Protect, char* Rights) { if(!Protect) //reserved pages don't have a protection (https://goo.gl/Izkk0c) { *Rights = '\0'; return true; } switch(Protect & 0xFF) { case PAGE_NOACCESS: strcpy_s(Rights, RIGHTS_STRING_SIZE, "----"); break; case PAGE_READONLY: strcpy_s(Rights, RIGHTS_STRING_SIZE, "-R--"); break; case PAGE_READWRITE: strcpy_s(Rights, RIGHTS_STRING_SIZE, "-RW-"); break; case PAGE_WRITECOPY: strcpy_s(Rights, RIGHTS_STRING_SIZE, "-RWC"); break; case PAGE_EXECUTE: strcpy_s(Rights, RIGHTS_STRING_SIZE, "E---"); break; case PAGE_EXECUTE_READ: strcpy_s(Rights, RIGHTS_STRING_SIZE, "ER--"); break; case PAGE_EXECUTE_READWRITE: strcpy_s(Rights, RIGHTS_STRING_SIZE, "ERW-"); break; case PAGE_EXECUTE_WRITECOPY: strcpy_s(Rights, RIGHTS_STRING_SIZE, "ERWC"); break; default: memset(Rights, 0, RIGHTS_STRING_SIZE); break; } strcat_s(Rights, RIGHTS_STRING_SIZE, ((Protect & PAGE_GUARD) == PAGE_GUARD) ? "G" : "-"); // Rights[5] = ((Protect & PAGE_NOCACHE) == PAGE_NOCACHE) ? '' : '-'; // Rights[6] = ((Protect & PAGE_WRITECOMBINE) == PAGE_GUARD) ? '' : '-'; return true; } bool MemPageRightsFromString(DWORD* Protect, const char* Rights) { ASSERT_TRUE(strlen(Rights) >= 2); *Protect = 0; // Check for the PAGE_GUARD flag if(Rights[0] == 'G' || Rights[0] == 'g') { *Protect |= PAGE_GUARD; Rights++; } if(_strcmpi(Rights, "Execute") == 0) *Protect |= PAGE_EXECUTE; else if(_strcmpi(Rights, "ExecuteRead") == 0) *Protect |= PAGE_EXECUTE_READ; else if(_strcmpi(Rights, "ExecuteReadWrite") == 0) *Protect |= PAGE_EXECUTE_READWRITE; else if(_strcmpi(Rights, "ExecuteWriteCopy") == 0) *Protect |= PAGE_EXECUTE_WRITECOPY; else if(_strcmpi(Rights, "NoAccess") == 0) *Protect |= PAGE_NOACCESS; else if(_strcmpi(Rights, "ReadOnly") == 0) *Protect |= PAGE_READONLY; else if(_strcmpi(Rights, "ReadWrite") == 0) *Protect |= PAGE_READWRITE; else if(_strcmpi(Rights, "WriteCopy") == 0) *Protect |= PAGE_WRITECOPY; return (*Protect != 0); } bool MemFindInPage(const SimplePage & page, duint startoffset, const std::vector<PatternByte> & pattern, std::vector<duint> & results, duint maxresults) { if(startoffset >= page.size || results.size() >= maxresults) return false; //TODO: memory read limit Memory<unsigned char*> data(page.size); if(!MemRead(page.address, data(), data.size())) return false; duint maxFind = maxresults; duint foundCount = results.size(); duint i = 0; duint findSize = data.size() - startoffset; while(foundCount < maxFind) { duint foundoffset = patternfind(data() + startoffset + i, findSize - i, pattern); if(foundoffset == -1) break; i += foundoffset + 1; duint result = page.address + startoffset + i - 1; results.push_back(result); foundCount++; } return true; } bool MemFindInMap(const std::vector<SimplePage> & pages, const std::vector<PatternByte> & pattern, std::vector<duint> & results, duint maxresults, bool progress) { duint count = 0; duint total = pages.size(); for(const auto page : pages) { if(!MemFindInPage(page, 0, pattern, results, maxresults)) continue; if(progress) GuiReferenceSetProgress(int(floor((float(count) / float(total)) * 100.0f))); if(results.size() >= maxresults) break; count++; } if(progress) { GuiReferenceSetProgress(100); GuiReferenceReloadData(); } return true; } template<class T> static T ror(T x, unsigned int moves) { return (x >> moves) | (x << (sizeof(T) * 8 - moves)); } template<class T> static T rol(T x, unsigned int moves) { return (x << moves) | (x >> (sizeof(T) * 8 - moves)); } bool MemDecodePointer(duint* Pointer, bool vistaPlus) { // Decode a pointer that has been encoded with a special "process cookie" // http://doxygen.reactos.org/dd/dc6/lib_2rtl_2process_8c_ad52c0f8f48ce65475a02a5c334b3e959.html // Verify if(!Pointer) return false; // Query the kernel for XOR key ULONG cookie; if(!NT_SUCCESS(NtQueryInformationProcess(fdProcessInfo->hProcess, ProcessCookie, &cookie, sizeof(ULONG), nullptr))) { if(!fallbackCookie) return false; cookie = fallbackCookie; } // Pointer adjustment (Windows Vista+) if(vistaPlus) #ifdef _WIN64 * Pointer = ror(*Pointer, (0x40 - (cookie & 0x3F)) & 0xFF); #else * Pointer = ror(*Pointer, (0x20 - (cookie & 0x1F)) & 0xFF); #endif //_WIN64 // XOR pointer with key * Pointer ^= cookie; return true; } void MemInitRemoteProcessCookie(ULONG cookie) { // Clear previous session's cookie fallbackCookie = cookie; // Allow a non-zero cookie to ignore the brute force if(fallbackCookie) return; // Windows XP/Vista/7 are unable to obtain remote process cookies using NtQueryInformationProcess // Guess the cookie by brute-forcing all possible hashes and validate it using known encodings duint RtlpUnhandledExceptionFilter = 0; duint UnhandledExceptionFilter = 0; duint SingleHandler = 0; duint DefaultHandler = 0; auto RtlpUnhandledExceptionFilterSymbol = ArchValue("_RtlpUnhandledExceptionFilter", "RtlpUnhandledExceptionFilter"); auto UnhandledExceptionFilterSymbol = ArchValue("_UnhandledExceptionFilter@4", "UnhandledExceptionFilter"); auto SingleHandlerSymbol = ArchValue("_SingleHandler", "SingleHandler"); auto DefaultHandlerSymbol = ArchValue("_DefaultHandler@4", "DefaultHandler"); if(!valfromstring(RtlpUnhandledExceptionFilterSymbol, &RtlpUnhandledExceptionFilter) || !valfromstring(UnhandledExceptionFilterSymbol, &UnhandledExceptionFilter) || !valfromstring(SingleHandlerSymbol, &SingleHandler) || !valfromstring(DefaultHandlerSymbol, &DefaultHandler)) return; // Pointer encodings known at System Breakpoint. These may be invalid if attaching to a process. // *ntdll.RtlpUnhandledExceptionFilter = EncodePointer(kernel32.UnhandledExceptionFilter) duint encodedUnhandledExceptionFilter = 0; if(!MemRead(RtlpUnhandledExceptionFilter, &encodedUnhandledExceptionFilter, sizeof(encodedUnhandledExceptionFilter))) return; // *kernel32.SingleHandler = EncodePointer(kernel32.DefaultHandler) duint encodedDefaultHandler = 0; if(!MemRead(SingleHandler, &encodedDefaultHandler, sizeof(encodedDefaultHandler))) return; auto isValidEncoding = [](ULONG CookieGuess, duint EncodedValue, duint DecodedValue) { return DecodedValue == (ror(EncodedValue, 0x40 - (CookieGuess & 0x3F)) ^ CookieGuess); }; cookie = 0; for(int i = 64; i > 0; i--) { const ULONG guess = ULONG(ror(encodedDefaultHandler, i) ^ DefaultHandler); if(isValidEncoding(guess, encodedUnhandledExceptionFilter, UnhandledExceptionFilter) && isValidEncoding(guess, encodedDefaultHandler, DefaultHandler)) { // cookie collision, we're unable to determine which cookie is correct if(cookie && guess != cookie) return; cookie = guess; } } fallbackCookie = cookie; } //Workaround for modules that have holes between sections, it keeps parts it couldn't read the same as the input bool MemReadDumb(duint BaseAddress, void* Buffer, duint Size) { if(!MemIsCanonicalAddress(BaseAddress) || !Buffer || !Size) return false; duint offset = 0; duint requestedSize = Size; duint sizeLeftInFirstPage = PAGE_SIZE - (BaseAddress & (PAGE_SIZE - 1)); duint readSize = min(sizeLeftInFirstPage, requestedSize); bool success = true; while(readSize) { SIZE_T bytesRead = 0; if(!MemoryReadSafePage(fdProcessInfo->hProcess, (PVOID)(BaseAddress + offset), (PBYTE)Buffer + offset, readSize, &bytesRead)) success = false; offset += readSize; requestedSize -= readSize; readSize = min(PAGE_SIZE, requestedSize); } return success; } bool MemGetProtect(duint Address, bool Reserved, bool Cache, unsigned int* Protect) { if(!Protect) return false; // Align address to page base Address = PAGE_ALIGN(Address); if(Cache) { SHARED_ACQUIRE(LockMemoryPages); auto found = memoryPages.find({ Address, Address }); if(found == memoryPages.end()) return false; if(!Reserved && found->second.mbi.State == MEM_RESERVE) //check if the current page is reserved. return false; *Protect = found->second.mbi.Protect; } else { MEMORY_BASIC_INFORMATION mbi; memset(&mbi, 0, sizeof(MEMORY_BASIC_INFORMATION)); if(!VirtualQueryEx(fdProcessInfo->hProcess, (void*)Address, &mbi, sizeof(mbi))) return false; *Protect = mbi.Protect; } return true; } static void MemSplitRange(duint Address, duint Size) { Size = PAGE_ALIGN(Size); auto found = memoryPages.find({ Address, Address }); if(found == memoryPages.end()) return; auto & range = found->first; if(range.second > (Address + Size)) { // Requires split. MEMPAGE firstPage = found->second; firstPage.mbi.RegionSize = Size; Range firstRange{ Address, Address + Size }; MEMPAGE secondPage = found->second; secondPage.mbi.RegionSize = (range.second - (Address + Size)); Range secondRange{ Address + Size, range.second }; memoryPages.erase(found); memoryPages.emplace(firstRange, firstPage); memoryPages.emplace(secondRange, secondPage); } } bool MemSetProtect(duint Address, unsigned int Protect, duint Size) { // Align address to page base Address = PAGE_ALIGN(Address); DWORD oldProtect; if(VirtualProtectEx(fdProcessInfo->hProcess, (void*)Address, Size, Protect, &oldProtect) == FALSE) return false; // Update cache. SHARED_ACQUIRE(LockMemoryPages); // When the protection changes we can't treat this as a single page anymore. if(bListAllPages) { // But we only need to split if the view requests it. MemSplitRange(Address, Size); } // Update protection info. auto found = memoryPages.find({ Address, Address }); while(found != memoryPages.end()) { if(found->first.second > (Address + Size)) break; found->second.mbi.Protect = Protect; found++; } return true; }
C/C++
x64dbg-development/src/dbg/memory.h
#ifndef _MEMORY_H #define _MEMORY_H #include "_global.h" #include "patternfind.h" struct SimplePage; void MemUpdateMap(); void MemUpdateMapAsync(); duint MemFindBaseAddr(duint Address, duint* Size = nullptr, bool Refresh = false, bool FindReserved = false); bool MemoryReadSafePage(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead); bool MemRead(duint BaseAddress, void* Buffer, duint Size, duint* NumberOfBytesRead = nullptr, bool cache = false); bool MemReadUnsafePage(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead); bool MemReadUnsafe(duint BaseAddress, void* Buffer, duint Size, duint* NumberOfBytesRead = nullptr); bool MemWrite(duint BaseAddress, const void* Buffer, duint Size, duint* NumberOfBytesWritten = nullptr); bool MemPatch(duint BaseAddress, const void* Buffer, duint Size, duint* NumberOfBytesWritten = nullptr); bool MemIsValidReadPtr(duint Address, bool cache = false); bool MemIsValidReadPtrUnsafe(duint Address, bool cache = false); bool MemIsCanonicalAddress(duint Address); bool MemIsCodePage(duint Address, bool Refresh); duint MemAllocRemote(duint Address, duint Size, DWORD Type = MEM_RESERVE | MEM_COMMIT, DWORD Protect = PAGE_EXECUTE_READWRITE); bool MemFreeRemote(duint Address); bool MemGetPageInfo(duint Address, MEMPAGE* PageInfo, bool Refresh = false); bool MemSetPageRights(duint Address, const char* Rights); bool MemGetPageRights(duint Address, char* Rights); bool MemPageRightsToString(DWORD Protect, char* Rights); bool MemPageRightsFromString(DWORD* Protect, const char* Rights); bool MemFindInPage(const SimplePage & page, duint startoffset, const std::vector<PatternByte> & pattern, std::vector<duint> & results, duint maxresults); bool MemFindInMap(const std::vector<SimplePage> & pages, const std::vector<PatternByte> & pattern, std::vector<duint> & results, duint maxresults, bool progress = true); bool MemDecodePointer(duint* Pointer, bool vistaPlus); void MemInitRemoteProcessCookie(ULONG cookie); bool MemReadDumb(duint BaseAddress, void* Buffer, duint Size); bool MemGetProtect(duint Address, bool Reserved, bool Cache, unsigned int* Protect); bool MemSetProtect(duint Address, unsigned int Protection, duint Size); #include "addrinfo.h" extern std::map<Range, MEMPAGE, RangeCompare> memoryPages; extern bool bListAllPages; extern bool bQueryWorkingSet; extern DWORD memMapThreadCounter; struct SimplePage { duint address; duint size; SimplePage(duint address, duint size) { this->address = address; this->size = size; } }; #endif // _MEMORY_H
C++
x64dbg-development/src/dbg/mnemonichelp.cpp
#include "mnemonichelp.h" #include "threading.h" #include <atomic> #include "jansson/jansson_x64dbg.h" #include "debugger.h" #include "filehelper.h" static std::unordered_map<String, String> MnemonicMap; static std::unordered_map<String, String> MnemonicBriefMap; static std::atomic<bool> isMnemonicLoaded(false); static bool loadFromText(); static inline void loadMnemonicHelp() { if(isMnemonicLoaded.load()) return; else // Load mnemonic help database loadFromText(); } static bool loadFromText() { EXCLUSIVE_ACQUIRE(LockMnemonicHelp); //Protect the following code in a critical section if(isMnemonicLoaded.load()) return true; isMnemonicLoaded.store(true); //Don't retry failed load(and spam log). String json; if(!FileHelper::ReadAllText(StringUtils::sprintf("%s\\..\\mnemdb.json", szProgramDir), json)) { dputs(QT_TRANSLATE_NOOP("DBG", "Failed to read mnemonic help database...")); return false; } MnemonicMap.clear(); auto root = json_loads(json.c_str(), 0, 0); if(root) { // Get a handle to the root object -> x86-64 subtree auto jsonData = json_object_get(root, "x86-64"); // Check if there was something to load if(jsonData) { size_t i; JSON value; json_array_foreach(jsonData, i, value) { auto mnem = json_string_value(json_object_get(value, "mnem")); auto description = json_string_value(json_object_get(value, "description")); if(mnem && description) MnemonicMap.emplace(StringUtils::ToLower(mnem), StringUtils::Trim(description)); } } // Get a handle to the root object -> x86-64-brief subtree auto jsonDataBrief = json_object_get(root, "x86-64-brief"); // Check if there was something to load if(jsonDataBrief) { size_t i; JSON value; json_array_foreach(jsonDataBrief, i, value) { auto mnem = json_string_value(json_object_get(value, "mnem")); auto description = json_string_value(json_object_get(value, "description")); if(mnem && description) MnemonicBriefMap.emplace(mnem, StringUtils::Trim(description)); } } // Free root json_decref(root); } else { dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load mnemonic help database...")); return false; } dputs(QT_TRANSLATE_NOOP("DBG", "Mnemonic help database loaded!")); return true; } String MnemonicHelp::getUniversalMnemonic(const String & mnem) { auto mnemLower = StringUtils::ToLower(mnem); auto startsWith = [&](const char* n) { return StringUtils::StartsWith(mnemLower, n); }; if(mnemLower == "jmp") return mnemLower; if(mnemLower == "loop") //LOOP return mnemLower; if(startsWith("int")) //INT n return "int n"; if(startsWith("cmov")) //CMOVcc return "cmovcc"; if(startsWith("fcmov")) //FCMOVcc return "fcmovcc"; if(startsWith("j")) //Jcc return "jcc"; if(startsWith("loop")) //LOOPcc return "loopcc"; if(startsWith("set")) //SETcc return "setcc"; return mnemLower; } String MnemonicHelp::getDescription(const char* mnem, int depth) { if(mnem == nullptr) return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Invalid mnemonic!")); if(depth == 10) return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Too many redirections...")); loadMnemonicHelp(); SHARED_ACQUIRE(LockMnemonicHelp); auto mnemuni = getUniversalMnemonic(mnem); auto found = MnemonicMap.find(mnemuni); if(found == MnemonicMap.end()) { if(mnemuni[0] == 'v') //v/vm { found = MnemonicMap.find(mnemuni.c_str() + 1); if(found == MnemonicMap.end()) return ""; } else return ""; } const auto & description = found->second; if(StringUtils::StartsWith(description, "-R:")) //redirect return getDescription(description.c_str() + 3, depth + 1); return description; } String MnemonicHelp::getBriefDescription(const char* mnem) { if(mnem == nullptr) return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Invalid mnemonic!")); loadMnemonicHelp(); SHARED_ACQUIRE(LockMnemonicHelp); auto mnemLower = StringUtils::ToLower(mnem); if(mnemLower == "???") return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "invalid instruction")); auto found = MnemonicBriefMap.find(mnemLower); if(found == MnemonicBriefMap.end()) { if(mnemLower[0] == 'v') //v/vm { found = MnemonicBriefMap.find(mnemLower.c_str() + 1); if(found != MnemonicBriefMap.end()) { if(mnemLower.length() > 1 && mnemLower[1] == 'm') //vm return "vm " + found->second; return "vector " + found->second; } } return ""; } return found->second; }
C/C++
x64dbg-development/src/dbg/mnemonichelp.h
#pragma once #include "_global.h" class MnemonicHelp { public: static String getUniversalMnemonic(const String & mnem); static String getDescription(const char* mnem, int depth = 0); static String getBriefDescription(const char* mnem); };
C++
x64dbg-development/src/dbg/module.cpp
#include "module.h" #include "TitanEngine/TitanEngine.h" #include "ntdll/ntdll.h" #include "threading.h" #include "symbolinfo.h" #include "murmurhash.h" #include "symbolsourcedia.h" #include "memory.h" #include "label.h" #include <algorithm> #include <shlwapi.h> #include "console.h" #include "debugger.h" #include "value.h" #include <memory> #include "LLVMDemangle/LLVMDemangle.h" std::map<Range, std::unique_ptr<MODINFO>, RangeCompare> modinfo; std::unordered_map<duint, std::string> hashNameMap; // RtlImageNtHeaderEx is much better than the non-Ex version due to stricter validation, but isn't available on XP x86. // This is essentially a fallback replacement that does the same thing static NTSTATUS ImageNtHeaders(duint base, duint size, PIMAGE_NT_HEADERS* outHeaders) { PIMAGE_NT_HEADERS ntHeaders; __try { if(base == 0 || outHeaders == nullptr) return STATUS_INVALID_PARAMETER; if(size < sizeof(IMAGE_DOS_HEADER)) return STATUS_INVALID_IMAGE_FORMAT; const PIMAGE_DOS_HEADER dosHeaders = (PIMAGE_DOS_HEADER)base; if(dosHeaders->e_magic != IMAGE_DOS_SIGNATURE) return STATUS_INVALID_IMAGE_FORMAT; const ULONG e_lfanew = dosHeaders->e_lfanew; const ULONG sizeOfPeSignature = sizeof('PE00'); if(e_lfanew >= size || e_lfanew >= (ULONG_MAX - sizeOfPeSignature - sizeof(IMAGE_FILE_HEADER)) || (e_lfanew + sizeOfPeSignature + sizeof(IMAGE_FILE_HEADER)) >= size) return STATUS_INVALID_IMAGE_FORMAT; ntHeaders = (PIMAGE_NT_HEADERS)((PCHAR)base + e_lfanew); // RtlImageNtHeaderEx verifies that the range does not cross the UM <-> KM boundary here, // but it would cost a syscall to query this address as it varies between OS versions // TODO: or do we already have this info somewhere? if(!MemIsCanonicalAddress((duint)ntHeaders + sizeof(IMAGE_NT_HEADERS))) return STATUS_INVALID_IMAGE_FORMAT; if(ntHeaders->Signature != IMAGE_NT_SIGNATURE) return STATUS_INVALID_IMAGE_FORMAT; } __except(EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } *outHeaders = ntHeaders; return STATUS_SUCCESS; } // Use only with SEC_COMMIT mappings, not SEC_IMAGE! (in that case, just do VA = base + rva...) ULONG64 ModRvaToOffset(ULONG64 base, PIMAGE_NT_HEADERS ntHeaders, ULONG64 rva) { PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(ntHeaders); for(WORD i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i) { if(rva >= section->VirtualAddress && rva < section->VirtualAddress + section->SizeOfRawData) { ASSERT_TRUE(rva != 0); // Following garbage in is garbage out, RVA 0 should always yield VA 0 return base + (rva - section->VirtualAddress) + section->PointerToRawData; } section++; } return 0; } static void ReadExportDirectory(MODINFO & Info, ULONG_PTR FileMapVA) { // Get the export directory and its size ULONG exportDirSize; auto exportDir = (PIMAGE_EXPORT_DIRECTORY)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_EXPORT, &exportDirSize); if(exportDirSize == 0 || exportDir == nullptr || (ULONG_PTR)exportDir + exportDirSize > FileMapVA + Info.loadedSize || // Check if exportDir fits into the mapped area (ULONG_PTR)exportDir + exportDirSize < (ULONG_PTR)exportDir // Check for ULONG_PTR wraparound (e.g. when exportDirSize == 0xfffff000) || exportDir->NumberOfFunctions == 0) return; DWORD64 totalFunctionSize = exportDir->NumberOfFunctions * sizeof(ULONG_PTR); if(totalFunctionSize / exportDir->NumberOfFunctions != sizeof(ULONG_PTR) || // Check for overflow totalFunctionSize > Info.loadedSize) // Check for impossible number of exports return; auto rva2offset = [&Info](ULONG64 rva) { return Info.isVirtual ? rva : ModRvaToOffset(0, Info.headers, rva); }; auto addressOfFunctionsOffset = rva2offset(exportDir->AddressOfFunctions); if(!addressOfFunctionsOffset) return; auto addressOfFunctions = PDWORD(addressOfFunctionsOffset + FileMapVA); auto addressOfNamesOffset = rva2offset(exportDir->AddressOfNames); auto addressOfNames = PDWORD(addressOfNamesOffset ? addressOfNamesOffset + FileMapVA : 0); auto addressOfNameOrdinalsOffset = rva2offset(exportDir->AddressOfNameOrdinals); auto addressOfNameOrdinals = PWORD(addressOfNameOrdinalsOffset ? addressOfNameOrdinalsOffset + FileMapVA : 0); // Do not reserve memory based on untrusted input //Info.exports.reserve(exportDir->NumberOfFunctions); Info.exportOrdinalBase = exportDir->Base; // TODO: 'invalid address' below means an RVA that is obviously invalid, like being greater than SizeOfImage. // In that case rva2offset will return a VA of 0 and we can ignore it. However the ntdll loader (and this code) // will still crash on corrupt or malicious inputs that are seemingly valid. Find out how common this is // (i.e. does it warrant wrapping everything in try/except?) and whether there are better solutions. // Note that we're loading this file because the debuggee did; that makes it at least somewhat plausible that we will also survive for(DWORD i = 0; i < exportDir->NumberOfFunctions; i++) { // Check if addressOfFunctions[i] is valid ULONG_PTR target = (ULONG_PTR)addressOfFunctions + i * sizeof(DWORD); if(target > FileMapVA + Info.loadedSize || target < (ULONG_PTR)addressOfFunctions) { continue; } // It is possible the AddressOfFunctions contain zero RVAs. GetProcAddress for these ordinals returns zero. // "The reason for it is to assign a particular ordinal to a function." - NTCore if(!addressOfFunctions[i]) continue; Info.exports.emplace_back(); auto & entry = Info.exports.back(); entry.ordinal = i + exportDir->Base; entry.rva = addressOfFunctions[i]; const auto entryVa = Info.isVirtual ? entry.rva : ModRvaToOffset(FileMapVA, Info.headers, entry.rva); entry.forwarded = entryVa >= (ULONG64)exportDir && entryVa < (ULONG64)exportDir + exportDirSize; if(entry.forwarded) { auto forwardNameOffset = rva2offset(entry.rva); if(forwardNameOffset) // Silent ignore (1) by ntdll loader: invalid forward names or addresses of forward names entry.forwardName = String((const char*)(forwardNameOffset + FileMapVA)); } } for(DWORD i = 0; i < exportDir->NumberOfNames; i++) { // Check if addressOfNameOrdinals[i] is valid ULONG_PTR target = (ULONG_PTR)addressOfNameOrdinals + i * sizeof(WORD); if(target > FileMapVA + Info.loadedSize || target < (ULONG_PTR)addressOfNameOrdinals) { continue; } DWORD index = addressOfNameOrdinals[i]; if(index < exportDir->NumberOfFunctions) // Silent ignore (2) by ntdll loader: bogus AddressOfNameOrdinals indices { // Check if addressOfNames[i] is valid target = (ULONG_PTR)addressOfNames + i * sizeof(DWORD); if(target > FileMapVA + Info.loadedSize || target < (ULONG_PTR)addressOfNames) { continue; } auto nameOffset = rva2offset(addressOfNames[i]); if(nameOffset) // Silent ignore (3) by ntdll loader: invalid names or addresses of names { // Info.exports has excluded some invalid exports, so addressOfNameOrdinals[i] is not equal to // the index of Info.exports. We need to iterate over Info.exports. for(size_t j = 0; j < Info.exports.size(); j++) { if(index + exportDir->Base == Info.exports[j].ordinal) { Info.exports[j].name = String((const char*)(nameOffset + FileMapVA)); break; } } } } } // give some kind of name to ordinal functions for(size_t i = 0; i < Info.exports.size(); i++) { if(Info.exports[i].name.empty()) Info.exports[i].name = "Ordinal#" + std::to_string(Info.exports[i].ordinal); } // prepare sorted vectors Info.exportsByName.resize(Info.exports.size()); Info.exportsByRva.resize(Info.exports.size()); for(size_t i = 0; i < Info.exports.size(); i++) { Info.exportsByName[i].index = i; Info.exportsByName[i].name = Info.exports[i].name.c_str(); //NOTE: DO NOT MODIFY name is any way! Info.exportsByRva[i] = i; } std::sort(Info.exportsByName.begin(), Info.exportsByName.end()); std::sort(Info.exportsByRva.begin(), Info.exportsByRva.end(), [&Info](size_t a, size_t b) { return Info.exports.at(a).rva < Info.exports.at(b).rva; }); // undecorate names for(auto & x : Info.exports) { if(!x.name.empty()) { auto demangled = LLVMDemangle(x.name.c_str()); if(demangled && x.name.compare(demangled) != 0) x.undecoratedName = demangled; LLVMDemangleFree(demangled); } } } static void ReadImportDirectory(MODINFO & Info, ULONG_PTR FileMapVA) { // Get the import directory and its size ULONG importDirSize; auto importDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_IMPORT, &importDirSize); if(importDirSize == 0 || importDescriptor == nullptr || (ULONG_PTR)importDescriptor + importDirSize > FileMapVA + Info.loadedSize || // Check if importDescriptor fits into the mapped area (ULONG_PTR)importDescriptor + importDirSize < (ULONG_PTR)importDescriptor) // Check for ULONG_PTR wraparound (e.g. when importDirSize == 0xfffff000) return; const ULONG64 ordinalFlag = IMAGE64(Info.headers) ? IMAGE_ORDINAL_FLAG64 : IMAGE_ORDINAL_FLAG32; auto rva2offset = [&Info](ULONG64 rva) { return Info.isVirtual ? rva : ModRvaToOffset(0, Info.headers, rva); }; for(size_t moduleIndex = 0; importDescriptor->Name != 0; ++importDescriptor, ++moduleIndex) { auto moduleNameOffset = rva2offset(importDescriptor->Name); if(!moduleNameOffset) // If the module name VA is invalid, the loader crashes with an access violation. Try to avoid this break; // Prefer OFTs over FTs. If they differ, the FT is a bounded import and has a 0% chance of being correct due to ASLR auto thunkOffset = rva2offset(importDescriptor->OriginalFirstThunk != 0 ? importDescriptor->OriginalFirstThunk : importDescriptor->FirstThunk); // If there is no FT, the loader ignores the descriptor and moves on to the next DLL instead of crashing. Wise move if(importDescriptor->FirstThunk == 0) continue; Info.importModules.emplace_back((const char*)(moduleNameOffset + FileMapVA)); unsigned char* thunkData = (unsigned char*)FileMapVA + thunkOffset; for(auto iatRva = importDescriptor->FirstThunk; THUNK_VAL(Info.headers, thunkData, u1.AddressOfData) != 0; thunkData += IMAGE64(Info.headers) ? sizeof(IMAGE_THUNK_DATA64) : sizeof(IMAGE_THUNK_DATA32), iatRva += IMAGE64(Info.headers) ? sizeof(ULONG64) : sizeof(DWORD)) { // Get AddressOfData, check whether the ordinal flag was set, and then strip it because the RVA is not valid with it set ULONG64 addressOfDataValue = THUNK_VAL(Info.headers, thunkData, u1.AddressOfData); const bool ordinalFlagSet = (addressOfDataValue & ordinalFlag) == ordinalFlag; // NB: both variables are ULONG64 to force this test to be 64 bit addressOfDataValue &= ~ordinalFlag; auto addressOfDataOffset = rva2offset(addressOfDataValue); if(!addressOfDataOffset && !ordinalFlagSet) // Invalid entries are ignored. Of course the app will crash if it ever calls the function, but whose fault is that? continue; Info.imports.emplace_back(); auto & entry = Info.imports.back(); entry.iatRva = iatRva; entry.moduleIndex = moduleIndex; auto importByName = PIMAGE_IMPORT_BY_NAME(addressOfDataOffset + FileMapVA); if(!ordinalFlagSet && importByName->Name[0] != '\0') { // Import by name entry.name = String((const char*)importByName->Name); entry.ordinal = -1; } else { // Import by ordinal entry.ordinal = THUNK_VAL(Info.headers, thunkData, u1.Ordinal) & 0xffff; char buf[18]; sprintf_s(buf, "Ordinal#%u", (ULONG)entry.ordinal); entry.name = String((const char*)buf); } } } // prepare sorted vectors Info.importsByRva.resize(Info.imports.size()); for(size_t i = 0; i < Info.imports.size(); i++) Info.importsByRva[i] = i; std::sort(Info.importsByRva.begin(), Info.importsByRva.end(), [&Info](size_t a, size_t b) { return Info.imports[a].iatRva < Info.imports[b].iatRva; }); // undecorate names for(auto & i : Info.imports) { if(!i.name.empty()) { auto demangled = LLVMDemangle(i.name.c_str()); if(demangled && i.name.compare(demangled) != 0) i.undecoratedName = demangled; LLVMDemangleFree(demangled); } } } static void ReadTlsCallbacks(MODINFO & Info, ULONG_PTR FileMapVA) { // Clear TLS callbacks Info.tlsCallbacks.clear(); // Get the TLS directory ULONG tlsDirSize; auto tlsDir = (PIMAGE_TLS_DIRECTORY)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_TLS, &tlsDirSize); if(tlsDir == nullptr /*|| tlsDirSize == 0*/ || // The loader completely ignores the directory size. Setting it to 0 is an anti-debug trick (ULONG_PTR)tlsDir + tlsDirSize > FileMapVA + Info.loadedSize || // Check if tlsDir fits into the mapped area (ULONG_PTR)tlsDir + tlsDirSize < (ULONG_PTR)tlsDir) // Check for ULONG_PTR wraparound (e.g. when tlsDirSize == 0xfffff000) return; ULONG64 addressOfCallbacks = IMAGE64(Info.headers) ? ((PIMAGE_TLS_DIRECTORY64)tlsDir)->AddressOfCallBacks : (ULONG64)((PIMAGE_TLS_DIRECTORY32)tlsDir)->AddressOfCallBacks; if(!addressOfCallbacks) return; auto imageBase = HEADER_FIELD(Info.headers, ImageBase); auto rva = tlsDir->AddressOfCallBacks - imageBase; auto tlsArrayOffset = Info.isVirtual ? rva : ModRvaToOffset(0, Info.headers, rva); if(!tlsArrayOffset) return; // TODO: proper bounds checking auto tlsArray = PULONG_PTR(tlsArrayOffset + FileMapVA); while(*tlsArray) Info.tlsCallbacks.push_back(duint(*tlsArray++ - imageBase + Info.base)); } #ifndef IMAGE_REL_BASED_RESERVED #define IMAGE_REL_BASED_RESERVED 6 #endif // IMAGE_REL_BASED_RESERVED #ifndef IMAGE_REL_BASED_MACHINE_SPECIFIC_7 #define IMAGE_REL_BASED_MACHINE_SPECIFIC_7 7 #endif // IMAGE_REL_BASED_MACHINE_SPECIFIC_7 static void ReadBaseRelocationTable(MODINFO & Info, ULONG_PTR FileMapVA) { // Clear relocations Info.relocations.clear(); // Ignore files with relocation info stripped if((Info.headers->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) == IMAGE_FILE_RELOCS_STRIPPED) return; // Get address and size of base relocation table ULONG totalBytes; auto baseRelocBlock = (PIMAGE_BASE_RELOCATION)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_BASERELOC, &totalBytes); if(baseRelocBlock == nullptr || totalBytes == 0 || (ULONG_PTR)baseRelocBlock + totalBytes > FileMapVA + Info.loadedSize || // Check if baseRelocBlock fits into the mapped area (ULONG_PTR)baseRelocBlock + totalBytes < (ULONG_PTR)baseRelocBlock) // Check for ULONG_PTR wraparound (e.g. when totalBytes == 0xfffff000) return; // Until we reach the end of the relocation table while(totalBytes > 0) { ULONG blockSize = baseRelocBlock->SizeOfBlock; if(blockSize == 0 || blockSize > totalBytes) // The loader allows incorrect relocation dir sizes/block counts, but it won't relocate the image { dprintf(QT_TRANSLATE_NOOP("DBG", "Invalid relocation block for module %s%s!\n"), Info.name, Info.extension); return; } // Process the relocation block totalBytes -= blockSize; blockSize = (blockSize - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); PUSHORT nextOffset = (PUSHORT)((PCHAR)baseRelocBlock + sizeof(IMAGE_BASE_RELOCATION)); while(blockSize--) { const auto type = (UCHAR)((*nextOffset) >> 12); const auto offset = (USHORT)(*nextOffset & 0xfff); if(baseRelocBlock->VirtualAddress + offset > FileMapVA + HEADER_FIELD(Info.headers, SizeOfImage)) { dprintf(QT_TRANSLATE_NOOP("DBG", "Invalid relocation entry for module %s%s!\n"), Info.name, Info.extension); return; } switch(type) { case IMAGE_REL_BASED_HIGHLOW: Info.relocations.push_back(MODRELOCATIONINFO{ baseRelocBlock->VirtualAddress + offset, type, sizeof(ULONG) }); break; case IMAGE_REL_BASED_DIR64: Info.relocations.push_back(MODRELOCATIONINFO{ baseRelocBlock->VirtualAddress + offset, type, sizeof(ULONG64) }); break; case IMAGE_REL_BASED_HIGH: case IMAGE_REL_BASED_LOW: case IMAGE_REL_BASED_HIGHADJ: Info.relocations.push_back(MODRELOCATIONINFO{ baseRelocBlock->VirtualAddress + offset, type, sizeof(USHORT) }); break; case IMAGE_REL_BASED_ABSOLUTE: case IMAGE_REL_BASED_RESERVED: // IMAGE_REL_BASED_SECTION; ignored by loader case IMAGE_REL_BASED_MACHINE_SPECIFIC_7: // IMAGE_REL_BASED_REL32; ignored by loader break; default: dprintf(QT_TRANSLATE_NOOP("DBG", "Illegal relocation type 0x%02X for module %s%s!\n"), type, Info.name, Info.extension); return; } ++nextOffset; } baseRelocBlock = (PIMAGE_BASE_RELOCATION)nextOffset; } std::sort(Info.relocations.begin(), Info.relocations.end(), [](MODRELOCATIONINFO const & a, MODRELOCATIONINFO const & b) { return a.rva < b.rva; }); } //Useful information: http://www.debuginfo.com/articles/debuginfomatch.html static void ReadDebugDirectory(MODINFO & Info, ULONG_PTR FileMapVA) { // Get the debug directory and its size ULONG debugDirSize; auto debugDir = (PIMAGE_DEBUG_DIRECTORY)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_DEBUG, &debugDirSize); if(debugDirSize == 0 || debugDir == nullptr || (ULONG_PTR)debugDir + debugDirSize > FileMapVA + Info.loadedSize || /* Check if debugDir fits into the mapped area */ (ULONG_PTR)debugDir + debugDirSize < (ULONG_PTR)debugDir) /* Check for ULONG_PTR wraparound (e.g. when debugDirSize == 0xfffff000) */ { return; } struct CV_HEADER { DWORD Signature; DWORD Offset; }; struct CV_INFO_PDB20 { CV_HEADER CvHeader; //CvHeader.Signature = "NB10" DWORD Signature; DWORD Age; BYTE PdbFileName[1]; }; struct CV_INFO_PDB70 { DWORD CvSignature; //"RSDS" GUID Signature; DWORD Age; BYTE PdbFileName[1]; }; const auto supported = [&Info, FileMapVA](PIMAGE_DEBUG_DIRECTORY entry) { // Check for valid RVA ULONG_PTR offset = 0; if(entry->AddressOfRawData) offset = Info.isVirtual ? entry->AddressOfRawData : (ULONG_PTR)ModRvaToOffset(0, Info.headers, entry->AddressOfRawData); else if(entry->PointerToRawData) offset = entry->PointerToRawData; if(!offset) return false; // Check size is sane and end of data lies within the image if(entry->SizeOfData < sizeof(CV_INFO_PDB20) /*smallest supported type*/ || entry->AddressOfRawData + entry->SizeOfData > HEADER_FIELD(Info.headers, SizeOfImage)) return false; // Choose from one of our many supported types such as codeview if(entry->Type == IMAGE_DEBUG_TYPE_CODEVIEW) // TODO: support other types (DBG)? { // Get the CV signature and do a final size check if it is valid auto signature = *(DWORD*)(FileMapVA + offset); if(signature == '01BN') return entry->SizeOfData >= sizeof(CV_INFO_PDB20) && entry->SizeOfData < sizeof(CV_INFO_PDB20) + DOS_MAX_PATH_LENGTH; else if(signature == 'SDSR') return entry->SizeOfData >= sizeof(CV_INFO_PDB70) && entry->SizeOfData < sizeof(CV_INFO_PDB70) + DOS_MAX_PATH_LENGTH; else { dprintf(QT_TRANSLATE_NOOP("DBG", "Unknown CodeView signature %08X for module %s%s...\n"), signature, Info.name, Info.extension); return false; } } return false; }; // Iterate over entries until we find a CV one or the end of the directory PIMAGE_DEBUG_DIRECTORY entry = debugDir; while(debugDirSize >= sizeof(IMAGE_DEBUG_DIRECTORY)) { if(supported(entry)) break; const auto typeName = [](DWORD type) { switch(type) { case IMAGE_DEBUG_TYPE_UNKNOWN: return "IMAGE_DEBUG_TYPE_UNKNOWN"; case IMAGE_DEBUG_TYPE_COFF: return "IMAGE_DEBUG_TYPE_COFF"; case IMAGE_DEBUG_TYPE_CODEVIEW: return "IMAGE_DEBUG_TYPE_CODEVIEW"; case IMAGE_DEBUG_TYPE_FPO: return "IMAGE_DEBUG_TYPE_FPO"; case IMAGE_DEBUG_TYPE_MISC: return "IMAGE_DEBUG_TYPE_MISC"; case IMAGE_DEBUG_TYPE_EXCEPTION: return "IMAGE_DEBUG_TYPE_EXCEPTION"; case IMAGE_DEBUG_TYPE_FIXUP: return "IMAGE_DEBUG_TYPE_FIXUP"; case IMAGE_DEBUG_TYPE_OMAP_TO_SRC: return "IMAGE_DEBUG_TYPE_OMAP_TO_SRC"; case IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: return "IMAGE_DEBUG_TYPE_OMAP_FROM_SRC"; case IMAGE_DEBUG_TYPE_BORLAND: return "IMAGE_DEBUG_TYPE_BORLAND"; case IMAGE_DEBUG_TYPE_RESERVED10: return "IMAGE_DEBUG_TYPE_RESERVED10"; case IMAGE_DEBUG_TYPE_CLSID: return "IMAGE_DEBUG_TYPE_CLSID"; // The following types aren't defined in older Windows SDKs, so just count up from here so we can still return the names for them case(IMAGE_DEBUG_TYPE_CLSID + 1): return "IMAGE_DEBUG_TYPE_VC_FEATURE"; // How to kill: /NOVCFEATURE linker switch case(IMAGE_DEBUG_TYPE_CLSID + 2): return "IMAGE_DEBUG_TYPE_POGO"; // How to kill: /NOCOFFGRPINFO linker switch case(IMAGE_DEBUG_TYPE_CLSID + 3): return "IMAGE_DEBUG_TYPE_ILTCG"; case(IMAGE_DEBUG_TYPE_CLSID + 4): return "IMAGE_DEBUG_TYPE_MPX"; case(IMAGE_DEBUG_TYPE_CLSID + 5): return "IMAGE_DEBUG_TYPE_REPRO"; default: return "unknown"; } }(entry->Type); /*dprintf("IMAGE_DEBUG_DIRECTORY:\nCharacteristics: %08X\nTimeDateStamp: %08X\nMajorVersion: %04X\nMinorVersion: %04X\nType: %s\nSizeOfData: %08X\nAddressOfRawData: %08X\nPointerToRawData: %08X\n", debugDir->Characteristics, debugDir->TimeDateStamp, debugDir->MajorVersion, debugDir->MinorVersion, typeName, debugDir->SizeOfData, debugDir->AddressOfRawData, debugDir->PointerToRawData);*/ dprintf(QT_TRANSLATE_NOOP("DBG", "Skipping unsupported debug type %s in module %s%s...\n"), typeName, Info.name, Info.extension); entry++; debugDirSize -= sizeof(IMAGE_DEBUG_DIRECTORY); } if(!supported(entry)) { dprintf(QT_TRANSLATE_NOOP("DBG", "Did not find any supported debug types in module %s%s!\n"), Info.name, Info.extension); return; } // At this point we know the entry is a valid CV one ULONG_PTR offset = 0; if(entry->AddressOfRawData) offset = Info.isVirtual ? entry->AddressOfRawData : (ULONG_PTR)ModRvaToOffset(0, Info.headers, entry->AddressOfRawData); else if(entry->PointerToRawData) offset = entry->PointerToRawData; auto cvData = (unsigned char*)(FileMapVA + offset); auto signature = *(DWORD*)cvData; if(signature == '01BN') { auto cv = (CV_INFO_PDB20*)cvData; Info.pdbSignature = StringUtils::sprintf("%X%X", cv->Signature, cv->Age); Info.pdbFile = String((const char*)cv->PdbFileName, entry->SizeOfData - FIELD_OFFSET(CV_INFO_PDB20, PdbFileName)); Info.pdbValidation.signature = cv->Signature; Info.pdbValidation.age = cv->Age; } else if(signature == 'SDSR') { auto cv = (CV_INFO_PDB70*)cvData; Info.pdbSignature = StringUtils::sprintf("%08X%04X%04X%s%X", cv->Signature.Data1, cv->Signature.Data2, cv->Signature.Data3, StringUtils::ToHex(cv->Signature.Data4, 8).c_str(), cv->Age); Info.pdbFile = String((const char*)cv->PdbFileName, entry->SizeOfData - FIELD_OFFSET(CV_INFO_PDB70, PdbFileName)); memcpy(&Info.pdbValidation.guid, &cv->Signature, sizeof(GUID)); Info.pdbValidation.signature = 0; Info.pdbValidation.age = cv->Age; } //dprintf("%s%s pdbSignature: %s, pdbFile: \"%s\"\n", Info.name, Info.extension, Info.pdbSignature.c_str(), Info.pdbFile.c_str()); if(!Info.pdbFile.empty()) { // Get the directory/filename from the debug directory PDB path String dir, file; auto lastIdx = Info.pdbFile.rfind('\\'); if(lastIdx == String::npos) file = Info.pdbFile; else { dir = Info.pdbFile.substr(0, lastIdx - 1); file = Info.pdbFile.substr(lastIdx + 1); } // TODO: this order is exactly the wrong way around :P // It should be: symbol cache (by far the most likely location, also why it exists) -> PDB path in PE -> program directory. // (this is also the search order used by WinDbg/symchk/dumpbin and anything that uses symsrv) // WinDbg even tries HTTP servers before the path in the PE, but that might be taking it a bit too far // Symbol cache auto cachePath = String(szSymbolCachePath); if(cachePath.back() != '\\') cachePath += '\\'; cachePath += StringUtils::sprintf("%s\\%s\\%s", file.c_str(), Info.pdbSignature.c_str(), file.c_str()); Info.pdbPaths.push_back(cachePath); // Debug directory full path const bool bAllowUncPathsInDebugDirectory = false; // TODO: create setting for this if(!dir.empty() && (bAllowUncPathsInDebugDirectory || !PathIsUNCW(StringUtils::Utf8ToUtf16(Info.pdbFile).c_str()))) Info.pdbPaths.push_back(Info.pdbFile); // Program directory (debug directory PDB name) char pdbPath[MAX_PATH]; strcpy_s(pdbPath, Info.path); auto lastBack = strrchr(pdbPath, '\\'); if(lastBack) { lastBack[1] = '\0'; strncat_s(pdbPath, file.c_str(), _TRUNCATE); Info.pdbPaths.push_back(pdbPath); } // Program directory (file name PDB name) strcpy_s(pdbPath, Info.path); lastBack = strrchr(pdbPath, '\\'); if(lastBack) { lastBack[1] = '\0'; strncat_s(pdbPath, Info.name, _TRUNCATE); strncat_s(pdbPath, ".pdb", _TRUNCATE); Info.pdbPaths.push_back(pdbPath); } } } #ifdef _WIN64 static void ReadExceptionDirectory(MODINFO & Info, ULONG_PTR FileMapVA) { // Clear runtime functions Info.runtimeFunctions.clear(); // Get address and size of exception directory ULONG totalBytes; auto baseRuntimeFunctions = (PRUNTIME_FUNCTION)RtlImageDirectoryEntryToData((PVOID)FileMapVA, Info.isVirtual, IMAGE_DIRECTORY_ENTRY_EXCEPTION, &totalBytes); if(baseRuntimeFunctions == nullptr || totalBytes == 0 || (ULONG_PTR)baseRuntimeFunctions + totalBytes > FileMapVA + Info.loadedSize || // Check if baseRuntimeFunctions fits into the mapped area (ULONG_PTR)baseRuntimeFunctions + totalBytes < (ULONG_PTR)baseRuntimeFunctions) // Check for ULONG_PTR wraparound (e.g. when totalBytes == 0xfffff000) return; Info.runtimeFunctions.resize(totalBytes / sizeof(RUNTIME_FUNCTION)); for(size_t i = 0; i < Info.runtimeFunctions.size(); i++) Info.runtimeFunctions[i] = baseRuntimeFunctions[i]; std::stable_sort(Info.runtimeFunctions.begin(), Info.runtimeFunctions.end(), [](const RUNTIME_FUNCTION & a, const RUNTIME_FUNCTION & b) { return std::tie(a.BeginAddress, a.EndAddress) < std::tie(b.BeginAddress, b.EndAddress); }); } #endif // _WIN64 static bool GetUnsafeModuleInfoImpl(MODINFO & Info, ULONG_PTR FileMapVA, void(*func)(MODINFO &, ULONG_PTR), const char* name) { __try { func(Info, FileMapVA); } __except(EXCEPTION_EXECUTE_HANDLER) { dprintf(QT_TRANSLATE_NOOP("DBG", "Exception while getting module info (%s), please report...\n"), name); return false; } return true; } void GetModuleInfo(MODINFO & Info, ULONG_PTR FileMapVA) { // Get the PE headers if(!NT_SUCCESS(ImageNtHeaders(FileMapVA, Info.loadedSize, &Info.headers))) { dprintf(QT_TRANSLATE_NOOP("DBG", "Module %s%s: invalid PE file!\n"), Info.name, Info.extension); return; } // Get the entry point duint moduleOEP = HEADER_FIELD(Info.headers, AddressOfEntryPoint); // Fix a problem where the OEP is set to zero (non-existent). // OEP can't start at the PE header/offset 0 -- except if module is an EXE. Info.entry = moduleOEP + Info.base; Info.headerImageBase = (duint)HEADER_FIELD(Info.headers, ImageBase); if(!moduleOEP) { // If this wasn't an exe, invalidate the entry point if((Info.headers->FileHeader.Characteristics & IMAGE_FILE_DLL) == IMAGE_FILE_DLL) Info.entry = 0; } // Setup the pseudo entry point symbol Info.entrySymbol.name = "OptionalHeader.AddressOfEntryPoint"; Info.entrySymbol.forwarded = false; Info.entrySymbol.ordinal = 0; Info.entrySymbol.rva = (DWORD)moduleOEP; // Enumerate all PE sections WORD sectionCount = Info.headers->FileHeader.NumberOfSections; Info.sections.clear(); Info.sections.reserve(sectionCount); PIMAGE_SECTION_HEADER ntSection = IMAGE_FIRST_SECTION(Info.headers); for(WORD i = 0; i < sectionCount; i++) { MODSECTIONINFO curSection; memset(&curSection, 0, sizeof(MODSECTIONINFO)); curSection.addr = ntSection->VirtualAddress + Info.base; curSection.size = ntSection->Misc.VirtualSize; if(!curSection.size) curSection.size = ntSection->SizeOfRawData; // Null-terminate section name char sectionName[IMAGE_SIZEOF_SHORT_NAME + 1]; strncpy_s(sectionName, (const char*)ntSection->Name, IMAGE_SIZEOF_SHORT_NAME); // Escape section name when needed strcpy_s(curSection.name, StringUtils::Escape(sectionName).c_str()); // Add entry to the vector Info.sections.push_back(curSection); ntSection++; } #define GetUnsafeModuleInfo(func) GetUnsafeModuleInfoImpl(Info, FileMapVA, func, #func) if(!GetUnsafeModuleInfo(ReadExportDirectory)) { Info.exports.clear(); Info.exportOrdinalBase = 0; Info.exportsByName.clear(); Info.exportsByRva.clear(); } if(!GetUnsafeModuleInfo(ReadImportDirectory)) { Info.importModules.clear(); Info.imports.clear(); Info.importsByRva.clear(); } GetUnsafeModuleInfo(ReadTlsCallbacks); GetUnsafeModuleInfo(ReadBaseRelocationTable); GetUnsafeModuleInfo(ReadDebugDirectory); #ifdef _WIN64 GetUnsafeModuleInfo(ReadExceptionDirectory); #endif // _WIN64 #undef GetUnsafeModuleInfo } bool ModLoad(duint Base, duint Size, const char* FullPath, bool loadSymbols) { // Handle a new module being loaded if(!Base || !Size || !FullPath) return false; auto infoPtr = std::make_unique<MODINFO>(); auto & info = *infoPtr; // Copy the module path in the struct strcpy_s(info.path, FullPath); // Break the module path into a directory and file name char file[MAX_MODULE_SIZE]; { char dir[MAX_PATH]; memset(dir, 0, sizeof(dir)); // Dir <- lowercase(file path) strcpy_s(dir, FullPath); _strlwr_s(dir); // Find the last instance of a path delimiter (slash) char* fileStart = strrchr(dir, '\\'); if(fileStart) { strncpy_s(file, fileStart + 1, _TRUNCATE); fileStart[0] = '\0'; } else strncpy_s(file, FullPath, _TRUNCATE); } // Calculate module hash from full file name info.hash = ModHashFromName(file); // Copy the extension into the module struct { char* extensionPos = strrchr(file, '.'); if(extensionPos) { strcpy_s(info.extension, extensionPos); extensionPos[0] = '\0'; } } // Copy information to struct strcpy_s(info.name, file); info.base = Base; info.size = Size; info.fileHandle = nullptr; info.loadedSize = 0; info.fileMap = nullptr; info.fileMapVA = 0; // Determine whether the module is located in system wchar_t szWindowsDir[MAX_PATH]; GetWindowsDirectoryW(szWindowsDir, _countof(szWindowsDir)); String Utf8Sysdir = StringUtils::Utf16ToUtf8(szWindowsDir); Utf8Sysdir.append("\\"); if(_memicmp(Utf8Sysdir.c_str(), FullPath, Utf8Sysdir.size()) == 0) { info.party = mod_system; } else { info.party = mod_user; } // Load module data info.isVirtual = strstr(FullPath, "virtual:\\") == FullPath; if(!info.isVirtual) { auto wszFullPath = StringUtils::Utf8ToUtf16(FullPath); // Load the physical module from disk if(StaticFileLoadW(wszFullPath.c_str(), UE_ACCESS_READ, false, &info.fileHandle, &info.loadedSize, &info.fileMap, &info.fileMapVA)) { GetModuleInfo(info, info.fileMapVA); Size = GetPE32DataFromMappedFile(info.fileMapVA, 0, UE_SIZEOFIMAGE); info.size = Size; } else { info.fileHandle = nullptr; info.loadedSize = 0; info.fileMap = nullptr; info.fileMapVA = 0; } } else { // This was a virtual module -> read it remotely info.mappedData.realloc(Size); MemRead(Base, info.mappedData(), info.mappedData.size()); // Get information from the local buffer // TODO: this does not properly work for file offset -> rva conversions (since virtual modules are SEC_IMAGE) info.loadedSize = (DWORD)Size; GetModuleInfo(info, (ULONG_PTR)info.mappedData()); } info.symbols = &EmptySymbolSource; // empty symbol source per default if(loadSymbols) { for(const auto & pdbPath : info.pdbPaths) { if(info.loadSymbols(pdbPath, bForceLoadSymbols)) break; } } // Add module to list EXCLUSIVE_ACQUIRE(LockModules); modinfo.insert(std::make_pair(Range(Base, Base + Size - 1), std::move(infoPtr))); EXCLUSIVE_RELEASE(); // Put labels for virtual module exports if(info.isVirtual) { if(info.entry >= Base && info.entry < Base + Size) LabelSet(info.entry, "EntryPoint", false, true); apienumexports(Base, [](duint base, const char* mod, const char* name, duint addr) { LabelSet(addr, name, false, true); }); } SymUpdateModuleList(); return true; } bool ModUnload(duint Base) { EXCLUSIVE_ACQUIRE(LockModules); // Find the iterator index const auto found = modinfo.find(Range(Base, Base)); if(found == modinfo.end()) return false; // Remove it from the list modinfo.erase(found); EXCLUSIVE_RELEASE(); // Update symbols SymUpdateModuleList(); return true; } void ModClear(bool updateGui) { { // Clean up all the modules EXCLUSIVE_ACQUIRE(LockModules); modinfo.clear(); } { // Clean up the reverse hash map EXCLUSIVE_ACQUIRE(LockModuleHashes); hashNameMap.clear(); } // Tell the symbol updater if(updateGui) GuiSymbolUpdateModuleList(0, nullptr); } MODINFO* ModInfoFromAddr(duint Address) { // // NOTE: THIS DOES _NOT_ USE LOCKS // auto found = modinfo.find(Range(Address, Address)); // Was the module found with this address? if(found == modinfo.end()) return nullptr; return found->second.get(); } bool ModNameFromAddr(duint Address, char* Name, bool Extension) { ASSERT_NONNULL(Name); SHARED_ACQUIRE(LockModules); // Get a pointer to module information auto module = ModInfoFromAddr(Address); if(!module) { Name[0] = '\0'; return false; } // Copy initial module name strcpy_s(Name, MAX_MODULE_SIZE, module->name); if(Extension) strcat_s(Name, MAX_MODULE_SIZE, module->extension); return true; } duint ModBaseFromAddr(duint Address) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return 0; return module->base; } duint ModHashFromAddr(duint Address) { // Returns a unique hash from a virtual address SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return Address; return module->hash + (Address - module->base); } duint ModContentHashFromAddr(duint Address) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return 0; if(module->fileMapVA != 0 && module->loadedSize > 0) return murmurhash((void*)module->fileMapVA, module->loadedSize); else return 0; } duint ModHashFromName(const char* Module) { // return MODINFO.hash (based on the name) ASSERT_NONNULL(Module); auto len = int(strlen(Module)); if(!len) return 0; auto hash = murmurhash(Module, len); //update the hash cache SHARED_ACQUIRE(LockModuleHashes); auto hashInCache = hashNameMap.find(hash) != hashNameMap.end(); SHARED_RELEASE(); if(!hashInCache) { EXCLUSIVE_ACQUIRE(LockModuleHashes); hashNameMap[hash] = Module; } return hash; } duint ModBaseFromName(const char* Module) { ASSERT_NONNULL(Module); auto len = int(strlen(Module)); if(!len) return 0; ASSERT_TRUE(len < MAX_MODULE_SIZE); SHARED_ACQUIRE(LockModules); //TODO: refactor this to query from a map duint candidate = 0; for(const auto & i : modinfo) { const auto & currentModule = i.second; char currentModuleName[MAX_MODULE_SIZE]; strcpy_s(currentModuleName, currentModule->name); strcat_s(currentModuleName, currentModule->extension); // Compare with extension (perfect match) if(!_stricmp(currentModuleName, Module)) return currentModule->base; // Compare without extension, possible candidate (thanks to chessgod101 for finding this) if(!candidate && !_stricmp(currentModule->name, Module)) candidate = currentModule->base; } return candidate; } duint ModSizeFromAddr(duint Address) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return 0; return module->size; } std::string ModNameFromHash(duint Hash) { SHARED_ACQUIRE(LockModuleHashes); auto found = hashNameMap.find(Hash); if(found == hashNameMap.end()) return std::string(); return found->second; } bool ModSectionsFromAddr(duint Address, std::vector<MODSECTIONINFO>* Sections) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return false; // Copy vector <-> vector *Sections = module->sections; return true; } duint ModEntryFromAddr(duint Address) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return 0; return module->entry; } int ModPathFromAddr(duint Address, char* Path, int Size) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module) return 0; strcpy_s(Path, Size, module->path); return (int)strlen(Path); } int ModPathFromName(const char* Module, char* Path, int Size) { return ModPathFromAddr(ModBaseFromName(Module), Path, Size); } void ModEnum(const std::function<void(const MODINFO &)> & cbEnum) { SHARED_ACQUIRE(LockModules); for(const auto & mod : modinfo) cbEnum(*mod.second); } MODULEPARTY ModGetParty(duint Address) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); // If the module is not found, it is an user module if(!module) return mod_user; return module->party; } void ModSetParty(duint Address, MODULEPARTY Party) { EXCLUSIVE_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); // If the module is not found, it is an user module if(!module) return; module->party = Party; } bool ModRelocationsFromAddr(duint Address, std::vector<MODRELOCATIONINFO> & Relocations) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module || module->relocations.empty()) return false; Relocations = module->relocations; return true; } bool ModRelocationAtAddr(duint Address, MODRELOCATIONINFO* Relocation) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module || module->relocations.empty()) return false; DWORD rva = (DWORD)(Address - module->base); // We assume there are no overlapping relocations auto ub = std::upper_bound(module->relocations.cbegin(), module->relocations.cend(), rva, [](DWORD a, MODRELOCATIONINFO const & b) { return a < b.rva; }); if(ub != module->relocations.begin() && (--ub)->Contains(rva)) { if(Relocation) *Relocation = *ub; return true; } return false; } bool ModRelocationsInRange(duint Address, duint Size, std::vector<MODRELOCATIONINFO> & Relocations) { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(Address); if(!module || module->relocations.empty()) return false; DWORD rva = (DWORD)(Address - module->base); // We assume there are no overlapping relocations auto ub = std::upper_bound(module->relocations.cbegin(), module->relocations.cend(), rva, [](DWORD a, MODRELOCATIONINFO const & b) { return a < b.rva; }); if(ub != module->relocations.begin()) ub--; Relocations.clear(); while(ub != module->relocations.end() && ub->rva < rva + Size) { if(ub->rva >= rva) Relocations.push_back(*ub); ub++; } return !Relocations.empty(); } #if _WIN64 const RUNTIME_FUNCTION* MODINFO::findRuntimeFunction(DWORD rva) const { const auto found = std::lower_bound(runtimeFunctions.cbegin(), runtimeFunctions.cend(), rva, [](const RUNTIME_FUNCTION & a, const DWORD & rva) { return a.EndAddress <= rva; }); if(found != runtimeFunctions.cend() && rva >= found->BeginAddress) return &*found; return nullptr; } #endif bool MODINFO::loadSymbols(const String & pdbPath, bool forceLoad) { unloadSymbols(); // Try DIA if(symbols == &EmptySymbolSource && SymbolSourceDIA::isLibraryAvailable()) { // TODO: do something with searchPaths std::string modname = name; modname += extension; DiaValidationData_t validationData; memcpy(&validationData.guid, &pdbValidation.guid, sizeof(GUID)); validationData.signature = pdbValidation.signature; validationData.age = pdbValidation.age; SymbolSourceDIA* symSource = new SymbolSourceDIA(); if(!FileExists(pdbPath.c_str())) { GuiSymbolLogAdd(StringUtils::sprintf("[DIA] Skipping non-existent PDB: %s\n", pdbPath.c_str()).c_str()); } else if(symSource->loadPDB(pdbPath, modname, base, size, forceLoad ? nullptr : &validationData)) { symSource->resizeSymbolBitmap(size); symbols = symSource; std::string msg; if(symSource->isLoading()) msg = StringUtils::sprintf("[DIA] Loading PDB (async): %s\n", pdbPath.c_str()); else msg = StringUtils::sprintf("[DIA] Loaded PDB: %s\n", pdbPath.c_str()); GuiSymbolLogAdd(msg.c_str()); return true; } else { // TODO: more detailled error codes? GuiSymbolLogAdd(StringUtils::sprintf("[DIA] Failed to load PDB: %s\n", pdbPath.c_str()).c_str()); } delete symSource; } if(symbols == &EmptySymbolSource && true) // TODO: try loading from other sources? { } if(!symbols->isOpen()) { std::string msg = StringUtils::sprintf("No symbols loaded for: %s%s\n", name, extension); GuiSymbolLogAdd(msg.c_str()); return false; } return true; } void MODINFO::unloadSymbols() { if(symbols != nullptr && symbols != &EmptySymbolSource) { delete symbols; symbols = &EmptySymbolSource; } } void MODINFO::unmapFile() { // Unload the mapped file from memory if(fileMapVA) StaticFileUnloadW(StringUtils::Utf8ToUtf16(path).c_str(), false, fileHandle, loadedSize, fileMap, fileMapVA); } const MODEXPORT* MODINFO::findExport(duint rva) const { if(exports.size()) { auto found = std::lower_bound(exportsByRva.begin(), exportsByRva.end(), rva, [this](size_t index, duint rva) { return exports.at(index).rva < rva; }); found = found != exportsByRva.end() && rva >= exports.at(*found).rva ? found : exportsByRva.end(); if(found != exportsByRva.end()) return &exports[*found]; } return nullptr; } const MODIMPORT* MODINFO::findImport(duint rva) const { if(imports.size()) { auto found = std::lower_bound(importsByRva.begin(), importsByRva.end(), rva, [this](size_t index, duint rva) { return imports.at(index).iatRva < rva; }); found = found != importsByRva.end() && rva >= imports.at(*found).iatRva ? found : importsByRva.end(); if(found != importsByRva.end()) return &imports[*found]; } return nullptr; } static bool resolveApiSetForward(const String & originatingDll, String & forwardDll, String & forwardExport) { wchar_t szApiSetDllPath[MAX_PATH] = L""; if(!GetSystemDirectoryW(szApiSetDllPath, _countof(szApiSetDllPath))) return {}; wcsncat_s(szApiSetDllPath, L"\\downlevel\\", _TRUNCATE); wcsncat_s(szApiSetDllPath, StringUtils::Utf8ToUtf16(forwardDll).c_str(), _TRUNCATE); wcsncat_s(szApiSetDllPath, L".dll", _TRUNCATE); auto ticks = GetTickCount(); // Load the physical module from disk MODINFO info = {}; if(!StaticFileLoadW(szApiSetDllPath, UE_ACCESS_READ, false, &info.fileHandle, &info.loadedSize, &info.fileMap, &info.fileMapVA)) return false; GetModuleInfo(info, info.fileMapVA); NameIndex found; if(!NameIndex::findByName(info.exportsByName, forwardExport, found, true)) return false; const auto & foundExport = info.exports[found.index]; if(!foundExport.forwarded) { dputs("assertion failure, api set not forwarded"); return false; } const auto & forwardName = foundExport.forwardName; auto dotIdx = forwardName.find('.'); if(dotIdx == String::npos) return false; forwardDll = forwardName.substr(0, dotIdx); forwardExport = forwardName.substr(dotIdx + 1); // Some DLLs have extra mappings: https://www.geoffchappell.com/studies/windows/win32/apisetschema/history/sets61.htm // This is a heuristic to resolve correctly without having to implement proper APISetMap support if(forwardDll == originatingDll) { // The only supported exceptional mapping is kernel32 -> kernelbase if(_stricmp(forwardDll.c_str(), "kernel32") != 0) return false; forwardDll = "kernelbase"; } return !forwardExport.empty(); } duint MODINFO::getProcAddress(const String & exportName, int maxForwardDepth) const { NameIndex found; if(!NameIndex::findByName(exportsByName, exportName, found, false)) return 0; const auto exportInfo = &exports[found.index]; if(maxForwardDepth > 0 && exportInfo->forwarded) { const auto & forwardName = exportInfo->forwardName; auto dotIdx = forwardName.find('.'); if(dotIdx == String::npos) return 0; auto forwardExport = forwardName.substr(dotIdx + 1); if(forwardExport.empty()) return 0; auto forwardDll = forwardName.substr(0, dotIdx); auto forwardBase = ModBaseFromName(forwardDll.c_str()); if(forwardBase == 0 && _strnicmp(forwardDll.c_str(), "api-", 4) == 0 || _strnicmp(forwardDll.c_str(), "ext-", 4) == 0) { if(!resolveApiSetForward(name, forwardDll, forwardExport)) return 0; forwardBase = ModBaseFromName(forwardDll.c_str()); } auto forwardModule = ModInfoFromAddr(forwardBase); if(forwardModule == nullptr) return 0; if(forwardExport[0] == '#') { duint ordinal = 0; if(!convertNumber(forwardExport.c_str() + 1, ordinal, 0) || ordinal > 0xFFFF) return 0; auto exportIndex = ordinal - forwardModule->exportOrdinalBase; if(exportIndex >= forwardModule->exports.size()) return 0; return forwardModule->base + forwardModule->exports[exportIndex].rva; } return forwardModule->getProcAddress(forwardExport, maxForwardDepth - 1); } return base + exportInfo->rva; } void MODIMPORT::convertToGuiSymbol(duint base, SYMBOLINFO* info) const { info->addr = base + iatRva; info->type = sym_import; info->decoratedSymbol = (char*)name.c_str(); info->undecoratedSymbol = (char*)undecoratedName.c_str(); info->freeDecorated = info->freeUndecorated = false; info->ordinal = 0; } void MODEXPORT::convertToGuiSymbol(duint base, SYMBOLINFO* info) const { info->addr = base + rva; info->type = sym_export; info->decoratedSymbol = (char*)name.c_str(); info->undecoratedSymbol = (char*)undecoratedName.c_str(); info->freeDecorated = info->freeUndecorated = false; info->ordinal = ordinal; }
C/C++
x64dbg-development/src/dbg/module.h
#ifndef _MODULE_H #define _MODULE_H #include "_global.h" #include <functional> #include "symbolsourcebase.h" // Macros to safely access IMAGE_NT_HEADERS fields since the compile-time typedef of this struct may not match the actual file bitness. // Never access OptionalHeader.xx values directly unless they have the same size and offset on 32 and 64 bit. IMAGE_FILE_HEADER fields are safe to use #define IMAGE32(NtHeaders) ((NtHeaders) != nullptr && (NtHeaders)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) #define IMAGE64(NtHeaders) ((NtHeaders) != nullptr && (NtHeaders)->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) #define HEADER_FIELD(NtHeaders, Field) (IMAGE64(NtHeaders) \ ? ((PIMAGE_NT_HEADERS64)(NtHeaders))->OptionalHeader.Field : (IMAGE32(NtHeaders) \ ? ((PIMAGE_NT_HEADERS32)(NtHeaders))->OptionalHeader.Field \ : 0)) #define THUNK_VAL(NtHeaders, Ptr, Val) (IMAGE64(NtHeaders) \ ? ((PIMAGE_THUNK_DATA64)(Ptr))->Val : (IMAGE32(NtHeaders) \ ? ((PIMAGE_THUNK_DATA32)(Ptr))->Val \ : 0)) struct MODSECTIONINFO { duint addr; // Virtual address duint size; // Virtual size char name[MAX_SECTION_SIZE * 5]; // Escaped section name }; struct MODRELOCATIONINFO { DWORD rva; // Virtual address BYTE type; // Relocation type (IMAGE_REL_BASED_*) WORD size; bool Contains(duint Address) const { return Address >= rva && Address < rva + size; } }; struct PdbValidationData { GUID guid; DWORD signature = 0; DWORD age = 0; PdbValidationData() { memset(&guid, 0, sizeof(guid)); } }; struct MODEXPORT : SymbolInfoGui { DWORD ordinal = 0; DWORD rva = 0; bool forwarded = false; String forwardName; String name; String undecoratedName; virtual void convertToGuiSymbol(duint base, SYMBOLINFO* info) const override; }; struct MODIMPORT : SymbolInfoGui { size_t moduleIndex = 0; //index in MODINFO.importModules DWORD iatRva = 0; duint ordinal = -1; //equal to -1 if imported by name String name; String undecoratedName; virtual void convertToGuiSymbol(duint base, SYMBOLINFO* info) const override; }; struct MODINFO { duint base = 0; // Module base duint size = 0; // Module size duint hash = 0; // Full module name hash duint entry = 0; // Entry point duint headerImageBase = 0; // ImageBase field in OptionalHeader char name[MAX_MODULE_SIZE]; // Module name (without extension) char extension[MAX_MODULE_SIZE]; // File extension (including the dot) char path[MAX_PATH]; // File path (in UTF8) PIMAGE_NT_HEADERS headers = nullptr; // Image headers. Always use HEADER_FIELD() to access OptionalHeader values std::vector<MODSECTIONINFO> sections; std::vector<MODRELOCATIONINFO> relocations; std::vector<duint> tlsCallbacks; #if _WIN64 std::vector<RUNTIME_FUNCTION> runtimeFunctions; //sorted by (begin, end) const RUNTIME_FUNCTION* findRuntimeFunction(DWORD rva) const; #endif // _WIN64 MODEXPORT entrySymbol; std::vector<MODEXPORT> exports; DWORD exportOrdinalBase = 0; //ordinal - 'exportOrdinalBase' = index in 'exports' std::vector<NameIndex> exportsByName; //index in 'exports', sorted by export name std::vector<size_t> exportsByRva; //index in 'exports', sorted by rva std::vector<String> importModules; std::vector<MODIMPORT> imports; std::vector<size_t> importsByRva; //index in 'imports', sorted by rva SymbolSourceBase* symbols = nullptr; String pdbSignature; String pdbFile; PdbValidationData pdbValidation; std::vector<String> pdbPaths; // Possible PDB paths (tried in order) HANDLE fileHandle = nullptr; DWORD loadedSize = 0; HANDLE fileMap = nullptr; ULONG_PTR fileMapVA = 0; MODULEPARTY party; // Party. Currently used value: 0: User, 1: System bool isVirtual = false; Memory<unsigned char*> mappedData; MODINFO() { memset(name, 0, sizeof(name)); memset(extension, 0, sizeof(extension)); memset(path, 0, sizeof(path)); } ~MODINFO() { unmapFile(); unloadSymbols(); GuiInvalidateSymbolSource(base); } bool loadSymbols(const String & pdbPath, bool forceLoad); void unloadSymbols(); void unmapFile(); const MODEXPORT* findExport(duint rva) const; const MODIMPORT* findImport(duint iatRva) const; duint getProcAddress(const String & name, int maxForwardDepth = 10) const; }; ULONG64 ModRvaToOffset(ULONG64 base, PIMAGE_NT_HEADERS ntHeaders, ULONG64 rva); bool ModLoad(duint Base, duint Size, const char* FullPath, bool loadSymbols = true); bool ModUnload(duint Base); void ModClear(bool updateGui = true); MODINFO* ModInfoFromAddr(duint Address); bool ModNameFromAddr(duint Address, char* Name, bool Extension); duint ModBaseFromAddr(duint Address); // Get a unique hash for an address in the module. // IMPORTANT: If you want to get a hash for the module base, pass the base duint ModHashFromAddr(duint Address); duint ModHashFromName(const char* Module); duint ModContentHashFromAddr(duint Address); duint ModBaseFromName(const char* Module); duint ModSizeFromAddr(duint Address); std::string ModNameFromHash(duint Hash); bool ModSectionsFromAddr(duint Address, std::vector<MODSECTIONINFO>* Sections); duint ModEntryFromAddr(duint Address); int ModPathFromAddr(duint Address, char* Path, int Size); int ModPathFromName(const char* Module, char* Path, int Size); /// <summary> /// Enumerate all loaded modules with a function. /// A shared lock on the modules is held until this function returns. /// </summary> /// <param name="cbEnum">Enumeration function.</param> void ModEnum(const std::function<void(const MODINFO &)> & cbEnum); MODULEPARTY ModGetParty(duint Address); void ModSetParty(duint Address, MODULEPARTY Party); bool ModRelocationsFromAddr(duint Address, std::vector<MODRELOCATIONINFO> & Relocations); bool ModRelocationAtAddr(duint Address, MODRELOCATIONINFO* Relocation); bool ModRelocationsInRange(duint Address, duint Size, std::vector<MODRELOCATIONINFO> & Relocations); #endif // _MODULE_H
C++
x64dbg-development/src/dbg/msgqueue.cpp
#include "msgqueue.h" // Allocate a message stack MESSAGE_STACK* MsgAllocStack() { return new MESSAGE_STACK(); } // Free a message stack void MsgFreeStack(MESSAGE_STACK* Stack) { ASSERT_NONNULL(Stack); // Update termination variable Stack->Destroy = true; // Notify each thread for(int i = 0; i < Stack->WaitingCalls + 1; i++) //TODO: found crash here on exit { MESSAGE newMessage; Stack->msgs.enqueue(newMessage); } // Delete allocated structure //delete Stack; } // Add a message to the stack bool MsgSend(MESSAGE_STACK* Stack, int Msg, duint Param1, duint Param2) { if(Stack->Destroy) return false; MESSAGE newMessage; newMessage.msg = Msg; newMessage.param1 = Param1; newMessage.param2 = Param2; // Asynchronous send asend(Stack->msgs, newMessage); return true; } // Get a message from the stack (will return false when there are no messages) bool MsgGet(MESSAGE_STACK* Stack, MESSAGE* Msg) { if(Stack->Destroy) return false; // Don't increment the wait count because this does not wait return try_receive(Stack->msgs, *Msg); } // Wait for a message on the specified stack void MsgWait(MESSAGE_STACK* Stack, MESSAGE* Msg) { if(Stack->Destroy) return; // Increment/decrement wait count InterlockedIncrement((volatile long*)&Stack->WaitingCalls); *Msg = Stack->msgs.dequeue(); InterlockedDecrement((volatile long*)&Stack->WaitingCalls); }
C/C++
x64dbg-development/src/dbg/msgqueue.h
#ifndef _MSGQUEUE_H #define _MSGQUEUE_H #include "_global.h" #include <agents.h> #define MAX_MESSAGES 256 // Message structure struct MESSAGE { int msg = -1; duint param1 = 0; duint param2 = 0; }; // Message stack structure class MESSAGE_STACK { public: Concurrency::unbounded_buffer<MESSAGE> msgs; int WaitingCalls = 0; // Number of threads waiting bool Destroy = false; // Destroy stack as soon as possible }; // Function definitions MESSAGE_STACK* MsgAllocStack(); void MsgFreeStack(MESSAGE_STACK* Stack); bool MsgSend(MESSAGE_STACK* Stack, int Msg, duint Param1, duint Param2); bool MsgGet(MESSAGE_STACK* Stack, MESSAGE* Msg); void MsgWait(MESSAGE_STACK* Stack, MESSAGE* Msg); #endif // _MSGQUEUE_H
C++
x64dbg-development/src/dbg/murmurhash.cpp
//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. // Note - The x86 and x64 versions do _not_ produce the same results, as the // algorithms are optimized for their respective platforms. You can still // compile and run any of them on any platform, but your performance with the // non-native version will be less than optimal. #include "murmurhash.h" //----------------------------------------------------------------------------- // Platform-specific functions and macros // Microsoft Visual Studio #if defined(_MSC_VER) /** @def FORCE_INLINE @brief A macro that defines force inline. */ #define FORCE_INLINE __forceinline #include <stdlib.h> /** @def ROTL32(x,y) _rotl(x,y) @brief A macro that defines rotl 32. @param x The void to process. @param y The void to process. */ #define ROTL32(x,y) _rotl(x,y) /** @def ROTL64(x,y) _rotl64(x,y) @brief A macro that defines rotl 64. @param x The void to process. @param y The void to process. */ #define ROTL64(x,y) _rotl64(x,y) /** @def BIG_CONSTANT(x) (x) @brief A macro that defines big constant. @param x The void to process. */ #define BIG_CONSTANT(x) (x) // Other compilers #else // defined(_MSC_VER) /** @brief The force inline. */ #define FORCE_INLINE inline __attribute__((always_inline)) inline uint32_t rotl32(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } inline uint64_t rotl64(uint64_t x, int8_t r) { return (x << r) | (x >> (64 - r)); } /** @def ROTL32(x,y) rotl32(x,y) @brief A macro that defines rotl 32. @param x The void to process. @param y The void to process. */ #define ROTL32(x,y) rotl32(x,y) /** @def ROTL64(x,y) rotl64(x,y) @brief A macro that defines rotl 64. @param x The void to process. @param y The void to process. */ #define ROTL64(x,y) rotl64(x,y) /** @def BIG_CONSTANT(x) (x##LLU) @brief A macro that defines big constant. @param x The void to process. */ #define BIG_CONSTANT(x) (x##LLU) #endif // !defined(_MSC_VER) /** @fn FORCE_INLINE uint32_t getblock32(const uint32_t* p, int i) @brief ----------------------------------------------------------------------------- Block read - if your platform needs to do endian-swapping or can only handle aligned reads, do the conversion here. @param p The const uint32_t* to process. @param i Zero-based index of the. @return An uint32_t. */ FORCE_INLINE uint32_t getblock32(const uint32_t* p, int i) { return p[i]; } /** @fn FORCE_INLINE uint64_t getblock64(const uint64_t* p, int i) @brief Getblock 64. @param p The const uint64_t* to process. @param i Zero-based index of the. @return An uint64_t. */ FORCE_INLINE uint64_t getblock64(const uint64_t* p, int i) { return p[i]; } /** @fn FORCE_INLINE uint32_t fmix32(uint32_t h) @brief ----------------------------------------------------------------------------- Finalization mix - force all bits of a hash block to avalanche. @param h The uint32_t to process. @return An uint32_t. */ FORCE_INLINE uint32_t fmix32(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } //---------- /** @fn FORCE_INLINE uint64_t fmix64(uint64_t k) @brief Fmix 64. @param k The uint64_t to process. @return An uint64_t. */ FORCE_INLINE uint64_t fmix64(uint64_t k) { k ^= k >> 33; k *= BIG_CONSTANT(0xff51afd7ed558ccd); k ^= k >> 33; k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); k ^= k >> 33; return k; } //----------------------------------------------------------------------------- /** @fn void MurmurHash3_x86_32(const void* key, int len, uint32_t seed, void* out) @brief Murmur hash 3 x coordinate 86 32. @param key The key. @param len The length. @param seed The seed. @param [in,out] out If non-null, the out. */ void MurmurHash3_x86_32(const void* key, int len, uint32_t seed, void* out) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 4; uint32_t h1 = seed; const uint32_t c1 = 0xcc9e2d51; const uint32_t c2 = 0x1b873593; //---------- // body const uint32_t* blocks = (const uint32_t*)(data + nblocks * 4); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock32(blocks, i); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 13); h1 = h1 * 5 + 0xe6546b64; } //---------- // tail const uint8_t* tail = (const uint8_t*)(data + nblocks * 4); uint32_t k1 = 0; switch(len & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h1 = fmix32(h1); *(uint32_t*)out = h1; } //----------------------------------------------------------------------------- /** @fn void MurmurHash3_x86_128(const void* key, const int len, uint32_t seed, void* out) @brief Murmur hash 3 x coordinate 86 128. @param key The key. @param len The length. @param seed The seed. @param [in,out] out If non-null, the out. */ void MurmurHash3_x86_128(const void* key, const int len, uint32_t seed, void* out) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 16; uint32_t h1 = seed; uint32_t h2 = seed; uint32_t h3 = seed; uint32_t h4 = seed; const uint32_t c1 = 0x239b961b; const uint32_t c2 = 0xab0e9789; const uint32_t c3 = 0x38b34ae5; const uint32_t c4 = 0xa1e38b93; //---------- // body const uint32_t* blocks = (const uint32_t*)(data + nblocks * 16); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock32(blocks, i * 4 + 0); uint32_t k2 = getblock32(blocks, i * 4 + 1); uint32_t k3 = getblock32(blocks, i * 4 + 2); uint32_t k4 = getblock32(blocks, i * 4 + 3); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 19); h1 += h2; h1 = h1 * 5 + 0x561ccd1b; k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; h2 = ROTL32(h2, 17); h2 += h3; h2 = h2 * 5 + 0x0bcaa747; k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; h3 = ROTL32(h3, 15); h3 += h4; h3 = h3 * 5 + 0x96cd1c35; k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; h4 = ROTL32(h4, 13); h4 += h1; h4 = h4 * 5 + 0x32ac3b17; } //---------- // tail const uint8_t* tail = (const uint8_t*)(data + nblocks * 16); uint32_t k1 = 0; uint32_t k2 = 0; uint32_t k3 = 0; uint32_t k4 = 0; switch(len & 15) { case 15: k4 ^= tail[14] << 16; case 14: k4 ^= tail[13] << 8; case 13: k4 ^= tail[12] << 0; k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; case 12: k3 ^= tail[11] << 24; case 11: k3 ^= tail[10] << 16; case 10: k3 ^= tail[ 9] << 8; case 9: k3 ^= tail[ 8] << 0; k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; case 8: k2 ^= tail[ 7] << 24; case 7: k2 ^= tail[ 6] << 16; case 6: k2 ^= tail[ 5] << 8; case 5: k2 ^= tail[ 4] << 0; k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; case 4: k1 ^= tail[ 3] << 24; case 3: k1 ^= tail[ 2] << 16; case 2: k1 ^= tail[ 1] << 8; case 1: k1 ^= tail[ 0] << 0; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; h1 = fmix32(h1); h2 = fmix32(h2); h3 = fmix32(h3); h4 = fmix32(h4); h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; ((uint32_t*)out)[0] = h1; ((uint32_t*)out)[1] = h2; ((uint32_t*)out)[2] = h3; ((uint32_t*)out)[3] = h4; } //----------------------------------------------------------------------------- /** @fn void MurmurHash3_x64_128(const void* key, const int len, const uint32_t seed, void* out) @brief Murmur hash 3 x coordinate 64 128. @param key The key. @param len The length. @param seed The seed. @param [in,out] out If non-null, the out. */ void MurmurHash3_x64_128(const void* key, const int len, const uint32_t seed, void* out) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 16; uint64_t h1 = seed; uint64_t h2 = seed; const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5); const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f); //---------- // body const uint64_t* blocks = (const uint64_t*)(data); for(int i = 0; i < nblocks; i++) { uint64_t k1 = getblock64(blocks, i * 2 + 0); uint64_t k2 = getblock64(blocks, i * 2 + 1); k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; h1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; h2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } //---------- // tail const uint8_t* tail = (const uint8_t*)(data + nblocks * 16); uint64_t k1 = 0; uint64_t k2 = 0; switch(len & 15) { case 15: k2 ^= ((uint64_t)tail[14]) << 48; case 14: k2 ^= ((uint64_t)tail[13]) << 40; case 13: k2 ^= ((uint64_t)tail[12]) << 32; case 12: k2 ^= ((uint64_t)tail[11]) << 24; case 11: k2 ^= ((uint64_t)tail[10]) << 16; case 10: k2 ^= ((uint64_t)tail[ 9]) << 8; case 9: k2 ^= ((uint64_t)tail[ 8]) << 0; k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; case 8: k1 ^= ((uint64_t)tail[ 7]) << 56; case 7: k1 ^= ((uint64_t)tail[ 6]) << 48; case 6: k1 ^= ((uint64_t)tail[ 5]) << 40; case 5: k1 ^= ((uint64_t)tail[ 4]) << 32; case 4: k1 ^= ((uint64_t)tail[ 3]) << 24; case 3: k1 ^= ((uint64_t)tail[ 2]) << 16; case 2: k1 ^= ((uint64_t)tail[ 1]) << 8; case 1: k1 ^= ((uint64_t)tail[ 0]) << 0; k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; ((uint64_t*)out)[0] = h1; ((uint64_t*)out)[1] = h2; } //-----------------------------------------------------------------------------
C/C++
x64dbg-development/src/dbg/murmurhash.h
//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. #ifndef _MURMURHASH3_H_ #define _MURMURHASH3_H_ //----------------------------------------------------------------------------- // Platform-specific functions and macros // Microsoft Visual Studio #if defined(_MSC_VER) && (_MSC_VER < 1600) typedef unsigned char uint8_t; typedef unsigned int uint32_t; typedef unsigned __int64 uint64_t; // Other compilers #else // defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) //----------------------------------------------------------------------------- void MurmurHash3_x86_32(const void* key, int len, uint32_t seed, void* out); void MurmurHash3_x86_128(const void* key, int len, uint32_t seed, void* out); void MurmurHash3_x64_128(const void* key, int len, uint32_t seed, void* out); //----------------------------------------------------------------------------- #ifdef _WIN64 static inline unsigned long long murmurhash(const void* data, int len) { unsigned long long hash[2]; MurmurHash3_x64_128(data, len, 0x1337, hash); #else //x86 static inline unsigned long murmurhash(const void* data, int len) { unsigned int hash[1]; MurmurHash3_x86_32(data, len, 0x1337, hash); #endif //_WIN64 return hash[0]; } #endif // _MURMURHASH3_H_
C++
x64dbg-development/src/dbg/patches.cpp
/** @file patches.cpp @brief Implements the patches class. */ #include "patches.h" #include "memory.h" #include "debugger.h" #include "threading.h" #include "module.h" static std::unordered_map<duint, PATCHINFO> patches; static std::unordered_map<DWORD, size_t> lastEnumSize; bool PatchSet(duint Address, unsigned char OldByte, unsigned char NewByte) { if(!DbgIsDebugging()) return false; // Address must be valid if(!MemIsValidReadPtr(Address)) return false; // Don't patch anything if the new and old values are the same if(OldByte == NewByte) return true; PATCHINFO newPatch; newPatch.addr = Address - ModBaseFromAddr(Address); newPatch.oldbyte = OldByte; newPatch.newbyte = NewByte; ModNameFromAddr(Address, newPatch.mod, true); // Generate a key for this address const duint key = ModHashFromAddr(Address); EXCLUSIVE_ACQUIRE(LockPatches); // Find any patch with this specific address auto found = patches.find(key); if(found != patches.end()) { if(found->second.oldbyte == NewByte) { // The patch was undone here patches.erase(found); return true; } // Keep the original byte from the previous patch newPatch.oldbyte = found->second.oldbyte; found->second = newPatch; } else { // The entry was never found, insert it patches.insert(std::make_pair(key, newPatch)); } return true; } bool PatchGet(duint Address, PATCHINFO* Patch) { if(!DbgIsDebugging()) return false; SHARED_ACQUIRE(LockPatches); // Find this specific address in the list auto found = patches.find(ModHashFromAddr(Address)); if(found == patches.end()) return false; // Did the user request an output buffer? if(Patch) { *Patch = found->second; Patch->addr += ModBaseFromAddr(Address); } // Return true because the patch was found return true; } bool PatchDelete(duint Address, bool Restore) { if(!DbgIsDebugging()) return false; EXCLUSIVE_ACQUIRE(LockPatches); // Do a list lookup with hash auto found = patches.find(ModHashFromAddr(Address)); if(found == patches.end()) return false; // Restore the original byte at this address if(Restore) MemWrite((found->second.addr + ModBaseFromAddr(Address)), &found->second.oldbyte, sizeof(char)); // Finally remove it from the list patches.erase(found); return true; } void PatchDelRange(duint Start, duint End, bool Restore) { if(!DbgIsDebugging()) return; // Are all bookmarks going to be deleted? // 0x00000000 - 0xFFFFFFFF if(Start == 0 && End == ~0) { EXCLUSIVE_ACQUIRE(LockPatches); patches.clear(); } else { // Make sure 'Start' and 'End' reference the same module duint moduleBase = ModBaseFromAddr(Start); if(moduleBase != ModBaseFromAddr(End)) return; // VA to RVA in module Start -= moduleBase; End -= moduleBase; EXCLUSIVE_ACQUIRE(LockPatches); for(auto itr = patches.begin(); itr != patches.end();) { const auto & currentPatch = itr->second; // [Start, End) if(currentPatch.addr >= Start && currentPatch.addr < End) { // Restore the original byte if necessary if(Restore) MemWrite((currentPatch.addr + moduleBase), &currentPatch.oldbyte, sizeof(char)); itr = patches.erase(itr); } else ++itr; } } } bool PatchEnum(PATCHINFO* List, size_t* Size) { /*if(!DbgIsDebugging()) return false;*/ ASSERT_FALSE(!List && !Size); SHARED_ACQUIRE(LockPatches); // Did the user request the size? if(Size) { *Size = patches.size() * sizeof(PATCHINFO); lastEnumSize[GetCurrentThreadId()] = patches.size(); if(!List) return true; } // Copy each vector entry to a C-style array auto limit = patches.size(); { auto lastSizeItr = lastEnumSize.find(GetCurrentThreadId()); if(lastSizeItr != lastEnumSize.end()) { limit = lastSizeItr->second; lastEnumSize.erase(lastSizeItr); } } for(auto itr = patches.cbegin(); itr != patches.cend() && limit != 0; ++itr, --limit, ++List) { *List = itr->second; List->addr += ModBaseFromName(itr->second.mod); } return true; } int PatchFile(const PATCHINFO* List, int Count, const char* FileName, char* Error) { // // This function returns an int based on the number // of patches applied. -1 indicates a failure. // if(Count <= 0) { // Notify the user of the error if(Error) strcpy_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "No patches to apply"))); return -1; } // Get a copy of the first module name in the array char moduleName[MAX_MODULE_SIZE]; strcpy_s(moduleName, List[0].mod); // Check if all patches are in the same module for(int i = 0; i < Count; i++) { if(_stricmp(List[i].mod, moduleName)) { if(Error) sprintf_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Not all patches are in module %s")), moduleName); return -1; } } // See if the module was loaded duint moduleBase = ModBaseFromName(moduleName); if(!moduleBase) { if(Error) sprintf_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Failed to get base of module %s")), moduleName); return -1; } //get the origin module path char modPath[MAX_PATH] = ""; if(!ModPathFromAddr(moduleBase, modPath, MAX_PATH)) { if(Error) sprintf_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Failed to get module path of module %s")), moduleName); return -1; } // Create file copy at destination path with attributes WString srcPath = StringUtils::Utf8ToUtf16(modPath); WString dstPath = StringUtils::Utf8ToUtf16(FileName); if(!CopyFileW(srcPath.c_str(), dstPath.c_str(), false)) { if(Error) strcpy_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Failed to make a copy of the original file (patch target is in use?)"))); return -1; } // Strip the READONLY flag from file so we can load it DWORD fileAttrs = GetFileAttributesW(dstPath.c_str()); if(fileAttrs == INVALID_FILE_ATTRIBUTES) { if(Error) strcpy_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Unable to obtain attributes for copied file"))); return -1; } SetFileAttributesW(dstPath.c_str(), fileAttrs & ~FILE_ATTRIBUTE_READONLY); // Try loading (will fail if SetFileAttributesW fails) HANDLE fileHandle; DWORD loadedSize; HANDLE fileMap; ULONG_PTR fileMapVa; if(!StaticFileLoadW(dstPath.c_str(), UE_ACCESS_ALL, false, &fileHandle, &loadedSize, &fileMap, &fileMapVa)) { if(Error) strcpy_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "StaticFileLoad failed"))); return -1; } // Begin iterating all patches, applying them to a file int patchCount = 0; for(int i = 0; i < Count; i++) { // Convert the virtual address to an offset within disk file data unsigned char* ptr = (unsigned char*)ConvertVAtoFileOffsetEx(fileMapVa, loadedSize, moduleBase, List[i].addr, false, true); // Skip patches that do not have a raw address if(!ptr) continue; *ptr = List[i].newbyte; patchCount++; } // Unload the file from memory and commit changes to disk if(!StaticFileUnloadW(dstPath.c_str(), true, fileHandle, loadedSize, fileMap, fileMapVa)) { if(Error) strcpy_s(Error, MAX_ERROR_SIZE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "StaticFileUnload failed"))); return -1; } // Zero the error message and return count if(Error) memset(Error, 0, MAX_ERROR_SIZE * sizeof(char)); return patchCount; } void PatchClear(const char* Module) { EXCLUSIVE_ACQUIRE(LockPatches); // Was a module specified? if(!Module || Module[0] == '\0') { // No specific entries to delete, so remove all of them patches.clear(); } else { // Otherwise iterate over each patch and check the owner // module for the address for(auto itr = patches.begin(); itr != patches.end();) { if(!_stricmp(itr->second.mod, Module)) itr = patches.erase(itr); else ++itr; } } }
C/C++
x64dbg-development/src/dbg/patches.h
#ifndef _PATCHES_H #define _PATCHES_H #include "_global.h" //casted to bridgemain.h:DBGPATCHINFO in _dbgfunctions.cpp struct PATCHINFO { char mod[MAX_MODULE_SIZE]; duint addr; unsigned char oldbyte; unsigned char newbyte; }; bool PatchSet(duint Address, unsigned char OldByte, unsigned char NewByte); bool PatchGet(duint Address, PATCHINFO* Patch); bool PatchDelete(duint Address, bool Restore); void PatchDelRange(duint Start, duint End, bool Restore); bool PatchEnum(PATCHINFO* List, size_t* Size); int PatchFile(const PATCHINFO* List, int Count, const char* FileName, char* Error); void PatchClear(const char* Module = nullptr); #endif // _PATCHES_H
C++
x64dbg-development/src/dbg/patternfind.cpp
#include "patternfind.h" #include <vector> #include <algorithm> using namespace std; static inline bool isHex(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } static inline string formathexpattern(const string & patterntext) { string result; int len = (int)patterntext.length(); for(int i = 0; i < len; i++) if(patterntext[i] == '?' || isHex(patterntext[i])) result += patterntext[i]; return result; } static inline int hexchtoint(char ch) { if(ch >= '0' && ch <= '9') return ch - '0'; else if(ch >= 'A' && ch <= 'F') return ch - 'A' + 10; else if(ch >= 'a' && ch <= 'f') return ch - 'a' + 10; return -1; } bool patterntransform(const string & patterntext, vector<PatternByte> & pattern) { pattern.clear(); //reject patterns with unsupported charcters for(char ch : patterntext) if(ch != '?' && ch != ' ' && !isHex(ch)) return false; string formattext = formathexpattern(patterntext); int len = (int)formattext.length(); if(!len) return false; if(len % 2) //not a multiple of 2 { formattext += '?'; len++; } PatternByte newByte = {}; for(int i = 0, j = 0; i < len; i++) { if(formattext[i] == '?') //wildcard { newByte.nibble[j].wildcard = true; //match anything } else //hex { newByte.nibble[j].wildcard = false; newByte.nibble[j].data = hexchtoint(formattext[i]) & 0xF; } j++; if(j == 2) //two nibbles = one byte { j = 0; pattern.push_back(newByte); } } //reject wildcard only patterns bool allWildcard = std::all_of(pattern.begin(), pattern.end(), [](const PatternByte & patternByte) { return patternByte.nibble[0].wildcard & patternByte.nibble[1].wildcard; }); if(allWildcard) return false; return true; } static inline bool patternmatchbyte(unsigned char byte, const PatternByte & pbyte) { int matched = 0; unsigned char n1 = (byte >> 4) & 0xF; if(pbyte.nibble[0].wildcard) matched++; else if(pbyte.nibble[0].data == n1) matched++; unsigned char n2 = byte & 0xF; if(pbyte.nibble[1].wildcard) matched++; else if(pbyte.nibble[1].data == n2) matched++; return (matched == 2); } size_t patternfind(const unsigned char* data, size_t datasize, const char* pattern, int* patternsize) { string patterntext(pattern); vector<PatternByte> searchpattern; if(!patterntransform(patterntext, searchpattern)) return -1; return patternfind(data, datasize, searchpattern); } size_t patternfind(const unsigned char* data, size_t datasize, unsigned char* pattern, size_t patternsize) { if(patternsize > datasize) patternsize = datasize; for(size_t i = 0, pos = 0; i < datasize; i++) { if(data[i] == pattern[pos]) { pos++; if(pos == patternsize) return i - patternsize + 1; } else if(pos > 0) { i -= pos; pos = 0; //reset current pattern position } } return -1; } static inline void patternwritebyte(unsigned char* byte, const PatternByte & pbyte) { unsigned char n1 = (*byte >> 4) & 0xF; unsigned char n2 = *byte & 0xF; if(!pbyte.nibble[0].wildcard) n1 = pbyte.nibble[0].data; if(!pbyte.nibble[1].wildcard) n2 = pbyte.nibble[1].data; *byte = ((n1 << 4) & 0xF0) | (n2 & 0xF); } void patternwrite(unsigned char* data, size_t datasize, const char* pattern) { vector<PatternByte> writepattern; string patterntext(pattern); if(!patterntransform(patterntext, writepattern)) return; size_t writepatternsize = writepattern.size(); if(writepatternsize > datasize) writepatternsize = datasize; for(size_t i = 0; i < writepatternsize; i++) patternwritebyte(&data[i], writepattern.at(i)); } bool patternsnr(unsigned char* data, size_t datasize, const char* searchpattern, const char* replacepattern) { size_t found = patternfind(data, datasize, searchpattern); if(found == -1) return false; patternwrite(data + found, datasize - found, replacepattern); return true; } size_t patternfind(const unsigned char* data, size_t datasize, const std::vector<PatternByte> & pattern) { size_t searchpatternsize = pattern.size(); for(size_t i = 0, pos = 0; i < datasize; i++) //search for the pattern { if(patternmatchbyte(data[i], pattern.at(pos))) //check if our pattern matches the current byte { pos++; if(pos == searchpatternsize) //everything matched return i - searchpatternsize + 1; } else if(pos > 0) //fix by Computer_Angel { i -= pos; pos = 0; //reset current pattern position } } return -1; }
C/C++
x64dbg-development/src/dbg/patternfind.h
#ifndef _PATTERNFIND_H #define _PATTERNFIND_H #include <vector> #include <string> struct PatternByte { struct PatternNibble { unsigned char data; bool wildcard; } nibble[2]; }; //returns: offset to data when found, -1 when not found size_t patternfind( const unsigned char* data, //data size_t datasize, //size of data const char* pattern, //pattern to search int* patternsize = 0 //outputs the number of bytes the pattern is ); //returns: offset to data when found, -1 when not found size_t patternfind( const unsigned char* data, //data size_t datasize, //size of data unsigned char* pattern, //bytes to search size_t patternsize //size of bytes to search ); //returns: nothing void patternwrite( unsigned char* data, //data size_t datasize, //size of data const char* pattern //pattern to write ); //returns: true on success, false on failure bool patternsnr( unsigned char* data, //data size_t datasize, //size of data const char* searchpattern, //pattern to search const char* replacepattern //pattern to write ); //returns: true on success, false on failure bool patterntransform(const std::string & patterntext, //pattern string std::vector<PatternByte> & pattern //pattern to feed to patternfind ); //returns: offset to data when found, -1 when not found size_t patternfind( const unsigned char* data, //data size_t datasize, //size of data const std::vector<PatternByte> & pattern //pattern to search ); #endif // _PATTERNFIND_H
C++
x64dbg-development/src/dbg/pdbdiafile.cpp
#include "_global.h" #include <comutil.h> #include <windows.h> #include <thread> #include <atomic> #include <mutex> #include <algorithm> #include "msdia/dia2.h" #include "msdia/cvConst.h" #include "msdia/diacreate.h" #include "pdbdiafile.h" #include "stringutils.h" #include "console.h" #include "LLVMDemangle/LLVMDemangle.h" //Taken from: https://msdn.microsoft.com/en-us/library/ms752876(v=vs.85).aspx class FileStream : public IStream { FileStream(HANDLE hFile) { AddRef(); _hFile = hFile; } ~FileStream() { if(_hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(_hFile); } } public: HRESULT static OpenFile(LPCWSTR pName, IStream** ppStream, bool fWrite) { HANDLE hFile = ::CreateFileW(pName, fWrite ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ, NULL, fWrite ? CREATE_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); *ppStream = new FileStream(hFile); if(*ppStream == NULL) CloseHandle(hFile); return S_OK; } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** ppvObject) { if(iid == __uuidof(IUnknown) || iid == __uuidof(IStream) || iid == __uuidof(ISequentialStream)) { *ppvObject = static_cast<IStream*>(this); AddRef(); return S_OK; } else return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return (ULONG)InterlockedIncrement(&_refcount); } virtual ULONG STDMETHODCALLTYPE Release(void) { ULONG res = (ULONG)InterlockedDecrement(&_refcount); if(res == 0) delete this; return res; } // ISequentialStream Interface public: virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) { BOOL rc = ReadFile(_hFile, pv, cb, pcbRead, NULL); return (rc) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) { BOOL rc = WriteFile(_hFile, pv, cb, pcbWritten, NULL); return rc ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } // IStream Interface public: virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*, ULARGE_INTEGER*) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Commit(DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Revert(void) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Clone(IStream**) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin, ULARGE_INTEGER* lpNewFilePointer) { DWORD dwMoveMethod; switch(dwOrigin) { case STREAM_SEEK_SET: dwMoveMethod = FILE_BEGIN; break; case STREAM_SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case STREAM_SEEK_END: dwMoveMethod = FILE_END; break; default: return STG_E_INVALIDFUNCTION; break; } if(SetFilePointerEx(_hFile, liDistanceToMove, (PLARGE_INTEGER)lpNewFilePointer, dwMoveMethod) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) { if(GetFileSizeEx(_hFile, (PLARGE_INTEGER)&pStatstg->cbSize) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } private: HANDLE _hFile; LONG _refcount = 0; }; template<typename T> class ScopedDiaType { private: T* _sym; public: ScopedDiaType() : _sym(nullptr) {} ScopedDiaType(T* sym) : _sym(sym) {} ~ScopedDiaType() { if(_sym != nullptr) _sym->Release(); } T** ref() { return &_sym; } T** operator&() { return ref(); } T* operator->() { return _sym; } operator T* () { return _sym; } void Attach(T* sym) { _sym = sym; } }; template<typename T> using CComPtr = ScopedDiaType<T>; PDBDiaFile::PDBDiaFile() : m_stream(nullptr), m_dataSource(nullptr), m_session(nullptr) { } PDBDiaFile::~PDBDiaFile() { if(isOpen()) close(); } bool PDBDiaFile::initLibrary() { return SUCCEEDED(CoInitialize(nullptr)); } bool PDBDiaFile::shutdownLibrary() { CoUninitialize(); return true; } bool PDBDiaFile::open(const char* file, uint64_t loadAddress, DiaValidationData_t* validationData) { return open(StringUtils::Utf8ToUtf16(file).c_str(), loadAddress, validationData); } bool PDBDiaFile::open(const wchar_t* file, uint64_t loadAddress, DiaValidationData_t* validationData) { if(!initLibrary()) return false; if(isOpen()) { #if 1 // Enable for validation purpose. __debugbreak(); #endif return false; } HRESULT hr = REGDB_E_CLASSNOTREG; hr = NoRegCoCreate(L"msdia140.dll", __uuidof(DiaSource), __uuidof(IDiaDataSource), (LPVOID*)&m_dataSource); if(testError(hr) || m_dataSource == nullptr) { hr = CoCreateInstance(__uuidof(DiaSource), NULL, CLSCTX_INPROC_SERVER, __uuidof(IDiaDataSource), (LPVOID*)&m_dataSource); } if(testError(hr) || m_dataSource == nullptr) { GuiSymbolLogAdd("Unable to initialize PDBDia Library.\n"); return false; } hr = FileStream::OpenFile(file, &m_stream, false); if(testError(hr)) { GuiSymbolLogAdd("Unable to open PDB file.\n"); return false; } /*std::vector<unsigned char> pdbData; if (!FileHelper::ReadAllData(StringUtils::Utf16ToUtf8(file), pdbData)) { GuiSymbolLogAdd("Unable to open PDB file.\n"); return false; } m_stream = SHCreateMemStream(pdbData.data(), pdbData.size());*/ if(validationData != nullptr) { hr = m_dataSource->loadDataFromIStream(m_stream); if(hr == E_PDB_FORMAT) { GuiSymbolLogAdd("PDB uses an obsolete format.\n"); return false; } } else { hr = m_dataSource->loadDataFromIStream(m_stream); } if(testError(hr)) { if(hr != E_PDB_NOT_FOUND) { GuiSymbolLogAdd(StringUtils::sprintf("Unable to open PDB file - %08X\n", hr).c_str()); } else { GuiSymbolLogAdd(StringUtils::sprintf("Unknown error - %08X\n", hr).c_str()); } return false; } hr = m_dataSource->openSession(&m_session); if(testError(hr) || m_session == nullptr) { GuiSymbolLogAdd(StringUtils::sprintf("Unable to create new PDBDia Session - %08X\n", hr).c_str()); return false; } if(validationData != nullptr) { IDiaSymbol* globalSym = nullptr; hr = m_session->get_globalScope(&globalSym); if(testError(hr)) { //?? } else { DWORD age = 0; hr = globalSym->get_age(&age); if(!testError(hr) && validationData->age != age) { globalSym->Release(); close(); GuiSymbolLogAdd(StringUtils::sprintf("Validation error: PDB age is not matching (expected: %u, actual: %u).\n", validationData->age, age).c_str()); return false; } if(validationData->signature != 0) { // PDB v2.0 ('NB10' ones) do not have a GUID and they use a signature and age DWORD signature = 0; hr = globalSym->get_signature(&signature); if(!testError(hr) && validationData->signature != signature) { globalSym->Release(); close(); GuiSymbolLogAdd(StringUtils::sprintf("Validation error: PDB signature is not matching (expected: %08X, actual: %08X).\n", signature, validationData->signature).c_str()); return false; } } else { // v7.0 PDBs should be checked using (age+guid) only GUID guid = { 0 }; hr = globalSym->get_guid(&guid); if(!testError(hr) && memcmp(&guid, &validationData->guid, sizeof(GUID)) != 0) { globalSym->Release(); close(); auto guidStr = [](const GUID & guid) -> String { // https://stackoverflow.com/a/22848342/1806760 char guid_string[37]; // 32 hex chars + 4 hyphens + null terminator sprintf_s(guid_string, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return guid_string; }; GuiSymbolLogAdd(StringUtils::sprintf("Validation error: PDB guid is not matching (expected: %s, actual: %s).\n", guidStr(validationData->guid).c_str(), guidStr(guid).c_str()).c_str()); return false; } } } globalSym->Release(); } if(loadAddress != 0) { m_session->put_loadAddress(loadAddress); } return true; } bool PDBDiaFile::isOpen() const { return m_session != nullptr || m_dataSource != nullptr || m_stream != nullptr; } bool PDBDiaFile::close() { if(m_session) { auto refcount = m_session->Release(); if(refcount != 0) dprintf("Memory leaks in IDiaSession (refcount: %u)\n", refcount); m_session = nullptr; } if(m_dataSource) { auto refcount = m_dataSource->Release(); if(refcount != 0) dprintf("Memory leaks in IDiaDataSource (refcount: %u)\n", refcount); m_dataSource = nullptr; } if(m_stream) { auto refcount = m_stream->Release(); if(refcount != 0) dprintf("Memory leaks in IStream (refcount: %u)\n", refcount); m_stream = nullptr; } return true; } bool PDBDiaFile::testError(HRESULT hr) { if(FAILED(hr)) { return true; } return false; } std::string PDBDiaFile::getSymbolNameString(IDiaSymbol* sym) { HRESULT hr; BSTR str = nullptr; std::string name; hr = sym->get_name(&str); if(hr != S_OK) return name; if(str != nullptr) { name = StringUtils::Utf16ToUtf8(str); } SysFreeString(str); return name; } std::string PDBDiaFile::getSymbolUndecoratedNameString(IDiaSymbol* sym) { HRESULT hr; BSTR str = nullptr; std::string name; std::string result; hr = sym->get_undecoratedName(&str); if(hr != S_OK) { return name; } if(str != nullptr) { name = StringUtils::Utf16ToUtf8(str); } result = name; SysFreeString(str); return result; } bool PDBDiaFile::enumerateLineNumbers(uint32_t rva, uint32_t size, std::vector<DiaLineInfo_t> & lines, std::map<DWORD, std::string> & files, const std::atomic<bool> & cancelled) { HRESULT hr; DWORD lineNumber = 0; DWORD relativeVirtualAddress = 0; DWORD lineNumberEnd = 0; CComPtr<IDiaEnumLineNumbers> lineNumbersEnum; hr = m_session->findLinesByRVA(rva, size, &lineNumbersEnum); if(!SUCCEEDED(hr)) return false; LONG lineCount = 0; hr = lineNumbersEnum->get_Count(&lineCount); if(!SUCCEEDED(hr)) return false; if(lineCount == 0) return true; lines.reserve(lines.size() + lineCount); const ULONG bucket = 10000; ULONG steps = lineCount / bucket + (lineCount % bucket != 0); for(ULONG step = 0; step < steps; step++) { ULONG begin = step * bucket; ULONG end = min((ULONG)lineCount, (step + 1) * bucket); if(cancelled) return false; std::vector<IDiaLineNumber*> lineNumbers; ULONG lineCountStep = end - begin; lineNumbers.resize(lineCountStep); ULONG fetched = 0; hr = lineNumbersEnum->Next((ULONG)lineNumbers.size(), lineNumbers.data(), &fetched); for(ULONG n = 0; n < fetched; n++) { if(cancelled) { for(ULONG m = n; m < fetched; m++) lineNumbers[m]->Release(); return false; } CComPtr<IDiaLineNumber> lineNumberInfo; lineNumberInfo.Attach(lineNumbers[n]); DWORD sourceFileId = 0; hr = lineNumberInfo->get_sourceFileId(&sourceFileId); if(!SUCCEEDED(hr)) continue; if(!files.count(sourceFileId)) { CComPtr<IDiaSourceFile> sourceFile; hr = lineNumberInfo->get_sourceFile(&sourceFile); if(!SUCCEEDED(hr)) continue; BSTR fileName = nullptr; hr = sourceFile->get_fileName(&fileName); if(!SUCCEEDED(hr)) continue; files.insert({ sourceFileId, StringUtils::Utf16ToUtf8(fileName) }); SysFreeString(fileName); } DiaLineInfo_t lineInfo; lineInfo.sourceFileId = sourceFileId; hr = lineNumberInfo->get_lineNumber(&lineInfo.lineNumber); if(!SUCCEEDED(hr)) continue; hr = lineNumberInfo->get_relativeVirtualAddress(&lineInfo.rva); if(!SUCCEEDED(hr)) continue; lines.push_back(lineInfo); } } return true; } uint32_t getSymbolId(IDiaSymbol* sym) { DWORD id; sym->get_symIndexId(&id); return id; } bool PDBDiaFile::enumerateLexicalHierarchy(const Query_t & query) { CComPtr<IDiaSymbol> globalScope; IDiaSymbol* symbol = nullptr; ULONG celt = 0; HRESULT hr; DiaSymbol_t symbolInfo; bool res = true; hr = m_session->get_globalScope(&globalScope); if(hr != S_OK) return false; InternalQueryContext_t context; context.callback = query.callback; context.collectSize = query.collectSize; context.collectUndecoratedNames = query.collectUndecoratedNames; uint32_t scopeId = getSymbolId(globalScope); context.visited.insert(scopeId); // Enumerate publics. { CComPtr<IDiaEnumSymbols> enumSymbols; hr = globalScope->findChildren(SymTagPublicSymbol, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); if(convertSymbolInfo(symbol, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } // Enumerate global functions. { CComPtr<IDiaEnumSymbols> enumSymbols; hr = globalScope->findChildren(SymTagFunction, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } // Enumerate global data. { CComPtr<IDiaEnumSymbols> enumSymbols; hr = globalScope->findChildren(SymTagData, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } // Enumerate compilands. { CComPtr<IDiaEnumSymbols> enumSymbols; hr = globalScope->findChildren(SymTagCompiland, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); if(!enumerateCompilandScope(sym, context)) { return false; } } } } return true; } bool PDBDiaFile::findSymbolRVA(uint64_t address, DiaSymbol_t & sym, DiaSymbolType symType /*= DiaSymbolType::ANY*/) { if(m_session == nullptr || m_dataSource == nullptr) return false; IDiaEnumSymbols* enumSymbols = nullptr; IDiaSymbol* symbol = nullptr; ULONG celt = 0; HRESULT hr; enum SymTagEnum tag = SymTagNull; switch(symType) { case DiaSymbolType::BLOCK: tag = SymTagBlock; break; case DiaSymbolType::FUNCTION: tag = SymTagFunction; break; case DiaSymbolType::LABEL: tag = SymTagLabel; break; case DiaSymbolType::PUBLIC: tag = SymTagPublicSymbol; break; } long disp = 0; hr = m_session->findSymbolByRVAEx((DWORD)address, tag, &symbol, &disp); if(hr != S_OK) return false; CComPtr<IDiaSymbol> scopedSym(symbol); sym.disp = disp; InternalQueryContext_t context; context.collectSize = true; context.collectUndecoratedNames = true; if(!convertSymbolInfo(scopedSym, sym, context)) return false; return true; } bool PDBDiaFile::enumerateCompilandScope(IDiaSymbol* compiland, InternalQueryContext_t & context) { IDiaSymbol* symbol = nullptr; ULONG celt = 0; HRESULT hr; DWORD symTagType; DiaSymbol_t symbolInfo; uint32_t symId = getSymbolId(compiland); { CComPtr<IDiaEnumSymbols> enumSymbols; hr = compiland->findChildren(SymTagFunction, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(!processFunctionSymbol(sym, context)) { return false; } } } } } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = compiland->findChildren(SymTagData, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = compiland->findChildren(SymTagBlock, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = compiland->findChildren(SymTagLabel, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } return true; } bool PDBDiaFile::processFunctionSymbol(IDiaSymbol* functionSym, InternalQueryContext_t & context) { IDiaSymbol* symbol = nullptr; ULONG celt = 0; HRESULT hr; DWORD symTagType; uint32_t symId = getSymbolId(functionSym); if(context.visited.find(symId) != context.visited.end()) { GuiSymbolLogAdd("Dupe\n"); return true; } context.visited.insert(symId); DiaSymbol_t symbolInfo; if(convertSymbolInfo(functionSym, symbolInfo, context)) { if(!context.callback(symbolInfo)) return false; } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = functionSym->findChildren(SymTagData, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); LocationType locType; sym->get_locationType((DWORD*)&locType); if(hr == S_OK && locType == LocIsStatic) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = functionSym->findChildren(SymTagBlock, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } { CComPtr<IDiaEnumSymbols> enumSymbols; hr = functionSym->findChildren(SymTagLabel, nullptr, nsNone, &enumSymbols); if(hr == S_OK) { while((hr = enumSymbols->Next(1, &symbol, &celt)) == S_OK && celt == 1) { CComPtr<IDiaSymbol> sym(symbol); hr = sym->get_symTag(&symTagType); if(hr == S_OK) { if(convertSymbolInfo(sym, symbolInfo, context)) { if(!context.callback(symbolInfo)) { return false; } } } } } } return true; } bool PDBDiaFile::resolveSymbolSize(IDiaSymbol* symbol, uint64_t & size, uint32_t symTag) { bool res = false; HRESULT hr; uint64_t tempSize = -1; if(symTag == SymTagData) { CComPtr<IDiaSymbol> symType; hr = symbol->get_type(&symType); if(hr == S_OK && symType != nullptr) { DWORD symTagType = 0; hr = symType->get_symTag(&symTagType); switch(symTagType) { case SymTagFunctionType: { hr = symbol->get_length(&tempSize); if(hr == S_OK) { size = tempSize; } else res = false; } break; case SymTagPointerType: case SymTagArrayType: case SymTagUDT: { hr = symType->get_length(&tempSize); if(hr == S_OK) size = tempSize; else res = false; } break; case SymTagNull: { hr = symType->get_length(&tempSize); if(hr == S_OK) { size = tempSize; } else { hr = symbol->get_length(&tempSize); if(hr == S_OK) size = tempSize; else res = false; } } break; default: { // Native type. hr = symType->get_length(&tempSize); if(hr == S_OK) size = tempSize; else res = false; } break; } } // One last attempt. if(res == false || size == 0 || size == -1) { hr = symbol->get_length(&tempSize); if(hr == S_OK) { size = tempSize; res = true; } else res = false; } } else if(symTag == SymTagFunction || symTag == SymTagBlock) { hr = symbol->get_length(&tempSize); if(hr == S_OK) { size = tempSize; } else res = false; } return res; } bool PDBDiaFile::convertSymbolInfo(IDiaSymbol* symbol, DiaSymbol_t & symbolInfo, InternalQueryContext_t & context) { HRESULT hr; DWORD symTagType; // Default all values. symbolInfo.reachable = DiaReachableType::UNKNOWN; symbolInfo.returnable = DiaReturnableType::UNKNOWN; symbolInfo.convention = DiaCallingConvention::UNKNOWN; symbolInfo.size = -1; symbolInfo.offset = -1; symbolInfo.segment = -1; symbolInfo.disp = 0; symbolInfo.virtualAddress = -1; symbolInfo.perfectSize = false; symbolInfo.publicSymbol = false; hr = symbol->get_symTag(&symTagType); if(hr != S_OK) return false; symbolInfo.name = getSymbolNameString(symbol); if(context.collectUndecoratedNames && !symbolInfo.name.empty() && (symbolInfo.name.at(0) == '?' || symbolInfo.name.at(0) == '_' || symbolInfo.name.at(0) == '@')) { auto demangled = LLVMDemangle(symbolInfo.name.c_str()); if(demangled && symbolInfo.name.compare(demangled) != 0) symbolInfo.undecoratedName = demangled; LLVMDemangleFree(demangled); } else { symbolInfo.undecoratedName = ""; } hr = symbol->get_addressSection((DWORD*)&symbolInfo.segment); if(hr != S_OK) { return false; } hr = symbol->get_addressOffset((DWORD*)&symbolInfo.offset); if(hr != S_OK) { return false; } hr = symbol->get_virtualAddress(&symbolInfo.virtualAddress); if(hr != S_OK) { // NOTE: At this point we could still lookup the address over the executable. return false; } if(symbolInfo.virtualAddress == symbolInfo.offset) { return false; } symbolInfo.size = -1; if(context.collectSize) { if(!resolveSymbolSize(symbol, symbolInfo.size, symTagType) || symbolInfo.size == 0) { symbolInfo.size = -1; } } switch(symTagType) { case SymTagPublicSymbol: symbolInfo.type = DiaSymbolType::PUBLIC; symbolInfo.publicSymbol = true; break; case SymTagFunction: symbolInfo.type = DiaSymbolType::FUNCTION; break; case SymTagData: symbolInfo.type = DiaSymbolType::DATA; break; case SymTagLabel: symbolInfo.type = DiaSymbolType::LABEL; break; case SymTagBlock: symbolInfo.type = DiaSymbolType::BLOCK; break; } return true; }
C/C++
x64dbg-development/src/dbg/pdbdiafile.h
#pragma once #include "PDBDiaTypes.h" #include <vector> #include <map> #include <string> #include <set> #include <unordered_set> #include <unordered_map> #include <atomic> struct IDiaDataSource; struct IDiaSession; struct IDiaSymbol; class PDBDiaFile { public: struct Query_t { std::function<bool(DiaSymbol_t &)> callback; bool collectUndecoratedNames = false; bool collectSize = false; }; private: struct InternalQueryContext_t : public Query_t { std::unordered_set<uint32_t> visited; }; private: IStream* m_stream; IDiaDataSource* m_dataSource; IDiaSession* m_session; public: PDBDiaFile(); ~PDBDiaFile(); static bool initLibrary(); static bool shutdownLibrary(); bool open(const char* file, uint64_t loadAddress = 0, DiaValidationData_t* validationData = nullptr); bool open(const wchar_t* file, uint64_t loadAddress = 0, DiaValidationData_t* validationData = nullptr); bool isOpen() const; bool close(); bool enumerateLineNumbers(uint32_t rva, uint32_t size, std::vector<DiaLineInfo_t> & lines, std::map<DWORD, std::string> & files, const std::atomic<bool> & cancelled); bool enumerateLexicalHierarchy(const Query_t & query); bool findSymbolRVA(uint64_t address, DiaSymbol_t & sym, DiaSymbolType symType = DiaSymbolType::ANY); private: bool testError(HRESULT hr); std::string getSymbolNameString(IDiaSymbol* sym); std::string getSymbolUndecoratedNameString(IDiaSymbol* sym); bool enumerateCompilandScope(IDiaSymbol* compiland, InternalQueryContext_t & context); bool processFunctionSymbol(IDiaSymbol* profilerFunction, InternalQueryContext_t & context); bool resolveSymbolSize(IDiaSymbol* symbol, uint64_t & size, uint32_t symTag); bool convertSymbolInfo(IDiaSymbol* symbol, DiaSymbol_t & symbolInfo, InternalQueryContext_t & context); };
C/C++
x64dbg-development/src/dbg/pdbdiatypes.h
#ifndef PDBDIATYPES_H_ #define PDBDIATYPES_H_ #pragma once #include <string> #include <stdint.h> #include <set> #include <vector> #include <deque> #include <map> #include <windows.h> #include <functional> #include <string> enum class DiaSymbolType { ANY = -1, FUNCTION = 0, CODE, DATA, LABEL, THUNK, BLOCK, PUBLIC, SECTIONCONTRIB, }; enum class DiaReachableType { UNKNOWN, REACHABLE, NOTREACHABLE, }; enum class DiaReturnableType { UNKNOWN, RETURNABLE, NOTRETURNABLE, }; enum class DiaCallingConvention { UNKNOWN, CALL_NEAR_C, CALL_NEAR_FAST, CALL_NEAR_STD, CALL_NEAR_SYS, CALL_THISCALL, }; struct DiaValidationData_t { GUID guid; uint32_t signature; uint32_t age; }; struct DiaSymbol_t { DiaSymbolType type = DiaSymbolType::ANY; uint64_t virtualAddress = 0; uint64_t size = 0; uint32_t offset = 0; uint32_t disp = 0; uint32_t segment = 0; DiaReachableType reachable = DiaReachableType::UNKNOWN; DiaReturnableType returnable = DiaReturnableType::UNKNOWN; DiaCallingConvention convention = DiaCallingConvention::UNKNOWN; bool perfectSize = false; bool publicSymbol = false; std::string name; std::string undecoratedName; }; struct DiaLineInfo_t { DWORD sourceFileId; DWORD lineNumber; DWORD rva; }; #endif // PDBDIATYPES_H_
C++
x64dbg-development/src/dbg/plugin_loader.cpp
/** @file plugin_loader.cpp @brief Implements the plugin loader. */ #include "plugin_loader.h" #include "console.h" #include "debugger.h" #include "threading.h" #include "expressionfunctions.h" #include "formatfunctions.h" #include <algorithm> #include <shlwapi.h> /** \brief List of plugins. */ static std::vector<PLUG_DATA> pluginList; /** \brief Saved plugin directory */ static std::wstring pluginDirectory; /** \brief The current plugin handle. */ static int curPluginHandle = 0; /** \brief List of plugin callbacks. */ static std::vector<PLUG_CALLBACK> pluginCallbackList[CB_LAST]; /** \brief List of plugin commands. */ static std::vector<PLUG_COMMAND> pluginCommandList; /** \brief List of plugin menus. */ static std::vector<PLUG_MENU> pluginMenuList; /** \brief List of plugin menu entries. */ static std::vector<PLUG_MENUENTRY> pluginMenuEntryList; /** \brief List of plugin exprfunctions. */ static std::vector<PLUG_EXPRFUNCTION> pluginExprfunctionList; /** \brief List of plugin formatfunctions. */ static std::vector<PLUG_FORMATFUNCTION> pluginFormatfunctionList; static PLUG_DATA pluginData; /** \brief Loads a plugin from the plugin directory. \param pluginName Name of the plugin. \param loadall true on unload all. \return true if it succeeds, false if it fails. */ bool pluginload(const char* pluginName, bool loadall) { //no empty plugin names allowed if(!pluginName) return false; char name[MAX_PATH] = ""; strncpy_s(name, pluginName, _TRUNCATE); if(!loadall) #ifdef _WIN64 strncat_s(name, ".dp64", _TRUNCATE); #else strncat_s(name, ".dp32", _TRUNCATE); #endif wchar_t currentDir[deflen] = L""; if(!loadall) { GetCurrentDirectoryW(deflen, currentDir); SetCurrentDirectoryW(pluginDirectory.c_str()); } char searchName[deflen] = ""; #ifdef _WIN64 sprintf_s(searchName, "%s\\%s", StringUtils::Utf16ToUtf8(pluginDirectory.c_str()).c_str(), name); #else sprintf_s(searchName, "%s\\%s", StringUtils::Utf16ToUtf8(pluginDirectory.c_str()).c_str(), name); #endif // _WIN64 //Check to see if this plugin is already loaded if(!loadall) { EXCLUSIVE_ACQUIRE(LockPluginList); for(auto it = pluginList.begin(); it != pluginList.end(); ++it) { if(_stricmp(it->plugname, name) == 0 && it->isLoaded) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] %s already loaded\n"), name); SetCurrentDirectoryW(currentDir); return false; } } } //check if the file exists if(!loadall && !PathFileExistsW(StringUtils::Utf8ToUtf16(searchName).c_str())) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] Cannot find plugin: %s\n"), name); return false; } //setup plugin data memset(&pluginData, 0, sizeof(pluginData)); pluginData.initStruct.pluginHandle = curPluginHandle; pluginData.hPlugin = LoadLibraryW(StringUtils::Utf8ToUtf16(searchName).c_str()); //load the plugin library if(!pluginData.hPlugin) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] Failed to load plugin: %s\n"), name); SetCurrentDirectoryW(currentDir); return false; } pluginData.pluginit = (PLUGINIT)GetProcAddress(pluginData.hPlugin, "pluginit"); if(!pluginData.pluginit) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] Export \"pluginit\" not found in plugin: %s\n"), name); for(int i = CB_INITDEBUG; i < CB_LAST; i++) pluginunregistercallback(curPluginHandle, CBTYPE(i)); FreeLibrary(pluginData.hPlugin); SetCurrentDirectoryW(currentDir); return false; } pluginData.plugstop = (PLUGSTOP)GetProcAddress(pluginData.hPlugin, "plugstop"); pluginData.plugsetup = (PLUGSETUP)GetProcAddress(pluginData.hPlugin, "plugsetup"); strncpy_s(pluginData.plugpath, searchName, MAX_PATH); strncpy_s(pluginData.plugname, name, MAX_PATH); //init plugin if(!pluginData.pluginit(&pluginData.initStruct)) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] pluginit failed for plugin: %s\n"), name); for(int i = CB_INITDEBUG; i < CB_LAST; i++) pluginunregistercallback(curPluginHandle, CBTYPE(i)); FreeLibrary(pluginData.hPlugin); SetCurrentDirectoryW(currentDir); return false; } if(pluginData.initStruct.sdkVersion < PLUG_SDKVERSION) //the plugin SDK is not compatible { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] %s is incompatible with this SDK version\n"), pluginData.initStruct.pluginName); for(int i = CB_INITDEBUG; i < CB_LAST; i++) pluginunregistercallback(curPluginHandle, CBTYPE(i)); FreeLibrary(pluginData.hPlugin); SetCurrentDirectoryW(currentDir); return false; } dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] %s v%d Loaded!\n"), pluginData.initStruct.pluginName, pluginData.initStruct.pluginVersion); //auto-register callbacks for certain export names auto cbPlugin = CBPLUGIN(GetProcAddress(pluginData.hPlugin, "CBALLEVENTS")); if(cbPlugin) { for(int i = CB_INITDEBUG; i < CB_LAST; i++) pluginregistercallback(curPluginHandle, CBTYPE(i), cbPlugin); } auto regExport = [](const char* exportname, CBTYPE cbType) { auto cbPlugin = CBPLUGIN(GetProcAddress(pluginData.hPlugin, exportname)); if(cbPlugin) pluginregistercallback(curPluginHandle, cbType, cbPlugin); }; regExport("CBINITDEBUG", CB_INITDEBUG); regExport("CBSTOPDEBUG", CB_STOPDEBUG); regExport("CB_STOPPINGDEBUG", CB_STOPPINGDEBUG); regExport("CBCREATEPROCESS", CB_CREATEPROCESS); regExport("CBEXITPROCESS", CB_EXITPROCESS); regExport("CBCREATETHREAD", CB_CREATETHREAD); regExport("CBEXITTHREAD", CB_EXITTHREAD); regExport("CBSYSTEMBREAKPOINT", CB_SYSTEMBREAKPOINT); regExport("CBLOADDLL", CB_LOADDLL); regExport("CBUNLOADDLL", CB_UNLOADDLL); regExport("CBOUTPUTDEBUGSTRING", CB_OUTPUTDEBUGSTRING); regExport("CBEXCEPTION", CB_EXCEPTION); regExport("CBBREAKPOINT", CB_BREAKPOINT); regExport("CBPAUSEDEBUG", CB_PAUSEDEBUG); regExport("CBRESUMEDEBUG", CB_RESUMEDEBUG); regExport("CBSTEPPED", CB_STEPPED); regExport("CBATTACH", CB_ATTACH); regExport("CBDETACH", CB_DETACH); regExport("CBDEBUGEVENT", CB_DEBUGEVENT); regExport("CBMENUENTRY", CB_MENUENTRY); regExport("CBWINEVENT", CB_WINEVENT); regExport("CBWINEVENTGLOBAL", CB_WINEVENTGLOBAL); regExport("CBLOADDB", CB_LOADDB); regExport("CBSAVEDB", CB_SAVEDB); regExport("CBFILTERSYMBOL", CB_FILTERSYMBOL); regExport("CBTRACEEXECUTE", CB_TRACEEXECUTE); regExport("CBSELCHANGED", CB_SELCHANGED); regExport("CBANALYZE", CB_ANALYZE); regExport("CBADDRINFO", CB_ADDRINFO); regExport("CBVALFROMSTRING", CB_VALFROMSTRING); regExport("CBVALTOSTRING", CB_VALTOSTRING); regExport("CBMENUPREPARE", CB_MENUPREPARE); //add plugin menus { SectionLocker<LockPluginMenuList, false, false> menuLock; //exclusive lock auto addPluginMenu = [](GUIMENUTYPE type) { int hNewMenu = GuiMenuAdd(type, pluginData.initStruct.pluginName); if(hNewMenu == -1) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] GuiMenuAdd(%d) failed for plugin: %s\n"), type, pluginData.initStruct.pluginName); return -1; } else { PLUG_MENU newMenu; newMenu.hEntryMenu = hNewMenu; newMenu.hParentMenu = type; newMenu.pluginHandle = pluginData.initStruct.pluginHandle; pluginMenuList.push_back(newMenu); return newMenu.hEntryMenu; } }; pluginData.hMenu = addPluginMenu(GUI_PLUGIN_MENU); pluginData.hMenuDisasm = addPluginMenu(GUI_DISASM_MENU); pluginData.hMenuDump = addPluginMenu(GUI_DUMP_MENU); pluginData.hMenuStack = addPluginMenu(GUI_STACK_MENU); pluginData.hMenuGraph = addPluginMenu(GUI_GRAPH_MENU); pluginData.hMenuMemmap = addPluginMenu(GUI_MEMMAP_MENU); pluginData.hMenuSymmod = addPluginMenu(GUI_SYMMOD_MENU); } //add the plugin to the list { SectionLocker<LockPluginList, false> pluginLock; //exclusive lock pluginList.push_back(pluginData); } //setup plugin if(pluginData.plugsetup) { PLUG_SETUPSTRUCT setupStruct; setupStruct.hwndDlg = GuiGetWindowHandle(); setupStruct.hMenu = pluginData.hMenu; setupStruct.hMenuDisasm = pluginData.hMenuDisasm; setupStruct.hMenuDump = pluginData.hMenuDump; setupStruct.hMenuStack = pluginData.hMenuStack; setupStruct.hMenuGraph = pluginData.hMenuGraph; setupStruct.hMenuMemmap = pluginData.hMenuMemmap; setupStruct.hMenuSymmod = pluginData.hMenuSymmod; pluginData.plugsetup(&setupStruct); } pluginData.isLoaded = true; curPluginHandle++; if(!loadall) SetCurrentDirectoryW(currentDir); return true; } /** \brief Unloads a plugin from the plugin directory. \param pluginName Name of the plugin. \param unloadall true on unload all. \return true if it succeeds, false if it fails. */ bool pluginunload(const char* pluginName, bool unloadall) { char name[MAX_PATH] = ""; strncpy_s(name, pluginName, _TRUNCATE); if(!unloadall) #ifdef _WIN64 strncat_s(name, ".dp64", _TRUNCATE); #else strncat_s(name, ".dp32", _TRUNCATE); #endif auto found = pluginList.end(); { EXCLUSIVE_ACQUIRE(LockPluginList); found = std::find_if(pluginList.begin(), pluginList.end(), [&name](const PLUG_DATA & a) { return _stricmp(a.plugname, name) == 0; }); } if(found != pluginList.end()) { bool canFreeLibrary = true; auto currentPlugin = *found; if(currentPlugin.plugstop) canFreeLibrary = currentPlugin.plugstop(); int pluginHandle = currentPlugin.initStruct.pluginHandle; plugincmdunregisterall(pluginHandle); pluginexprfuncunregisterall(pluginHandle); pluginformatfuncunregisterall(pluginHandle); //remove the callbacks { EXCLUSIVE_ACQUIRE(LockPluginCallbackList); for(auto & cbList : pluginCallbackList) { for(auto it = cbList.begin(); it != cbList.end();) { if(it->pluginHandle == pluginHandle) it = cbList.erase(it); else ++it; } } } { EXCLUSIVE_ACQUIRE(LockPluginList); pluginmenuclear(currentPlugin.hMenu, true); pluginmenuclear(currentPlugin.hMenuDisasm, true); pluginmenuclear(currentPlugin.hMenuDump, true); pluginmenuclear(currentPlugin.hMenuStack, true); pluginmenuclear(currentPlugin.hMenuGraph, true); pluginmenuclear(currentPlugin.hMenuMemmap, true); pluginmenuclear(currentPlugin.hMenuSymmod, true); if(!unloadall) { //remove from main pluginlist. We do this so unloadall doesn't try to unload an already released plugin pluginList.erase(found); } } if(canFreeLibrary) FreeLibrary(currentPlugin.hPlugin); dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] %s unloaded\n"), name); return true; } dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] %s not found\n"), name); return false; } typedef BOOL(WINAPI* pfnAddDllDirectory)(LPCWSTR lpPathName); /** \brief Loads plugins from a specified directory. \param pluginDir The directory to load plugins from. */ void pluginloadall(const char* pluginDir) { //reserve menu space pluginMenuList.reserve(1024); pluginMenuEntryList.reserve(1024); //load new plugins wchar_t currentDir[deflen] = L""; pluginDirectory = StringUtils::Utf8ToUtf16(pluginDir); //add the plugins directory as valid dependency directory static auto pAddDllDirectory = (pfnAddDllDirectory)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "AddDllDirectory"); if(pAddDllDirectory) pAddDllDirectory(pluginDirectory.c_str()); GetCurrentDirectoryW(deflen, currentDir); SetCurrentDirectoryW(pluginDirectory.c_str()); char searchName[deflen] = ""; #ifdef _WIN64 sprintf_s(searchName, "%s\\*.dp64", pluginDir); #else sprintf_s(searchName, "%s\\*.dp32", pluginDir); #endif // _WIN64 WIN32_FIND_DATAW foundData; HANDLE hSearch = FindFirstFileW(StringUtils::Utf8ToUtf16(searchName).c_str(), &foundData); if(hSearch == INVALID_HANDLE_VALUE) { SetCurrentDirectoryW(currentDir); return; } do { pluginload(StringUtils::Utf16ToUtf8(foundData.cFileName).c_str(), true); } while(FindNextFileW(hSearch, &foundData)); FindClose(hSearch); SetCurrentDirectoryW(currentDir); } /** \brief Unloads all plugins. */ void pluginunloadall() { SHARED_ACQUIRE(LockPluginList); auto pluginListCopy = pluginList; SHARED_RELEASE(); for(const auto & plugin : pluginListCopy) pluginunload(plugin.plugname, true); } /** \brief Unregister all plugin commands. \param pluginHandle Handle of the plugin to remove the commands from. */ void plugincmdunregisterall(int pluginHandle) { SHARED_ACQUIRE(LockPluginCommandList); auto commandList = pluginCommandList; //copy for thread-safety reasons SHARED_RELEASE(); for(auto itr = commandList.begin(); itr != commandList.end();) { auto currentCommand = *itr; if(currentCommand.pluginHandle == pluginHandle) { itr = commandList.erase(itr); dbgcmddel(currentCommand.command); } else { ++itr; } } } /** \brief Unregister all plugin expression functions. \param pluginHandle Handle of the plugin to remove the expression functions from. */ void pluginexprfuncunregisterall(int pluginHandle) { SHARED_ACQUIRE(LockPluginExprfunctionList); auto exprFuncList = pluginExprfunctionList; //copy for thread-safety reasons SHARED_RELEASE(); auto i = exprFuncList.begin(); while(i != exprFuncList.end()) { auto currentExprFunc = *i; if(currentExprFunc.pluginHandle == pluginHandle) { i = exprFuncList.erase(i); ExpressionFunctions::Unregister(currentExprFunc.name); } else ++i; } } /** \brief Unregister all plugin format functions. \param pluginHandle Handle of the plugin to remove the format functions from. */ void pluginformatfuncunregisterall(int pluginHandle) { SHARED_ACQUIRE(LockPluginFormatfunctionList); auto formatFuncList = pluginFormatfunctionList; //copy for thread-safety reasons SHARED_RELEASE(); auto i = formatFuncList.begin(); while(i != formatFuncList.end()) { auto currentFormatFunc = *i; if(currentFormatFunc.pluginHandle == pluginHandle) { i = formatFuncList.erase(i); FormatFunctions::Unregister(currentFormatFunc.name); } else ++i; } } /** \brief Register a plugin callback. \param pluginHandle Handle of the plugin to register a callback for. \param cbType The type of the callback to register. \param cbPlugin The actual callback function. */ void pluginregistercallback(int pluginHandle, CBTYPE cbType, CBPLUGIN cbPlugin) { pluginunregistercallback(pluginHandle, cbType); //remove previous callback PLUG_CALLBACK cbStruct; cbStruct.pluginHandle = pluginHandle; cbStruct.cbType = cbType; cbStruct.cbPlugin = cbPlugin; EXCLUSIVE_ACQUIRE(LockPluginCallbackList); pluginCallbackList[cbType].push_back(cbStruct); } /** \brief Unregister all plugin callbacks of a certain type. \param pluginHandle Handle of the plugin to unregister a callback from. \param cbType The type of the callback to unregister. */ bool pluginunregistercallback(int pluginHandle, CBTYPE cbType) { EXCLUSIVE_ACQUIRE(LockPluginCallbackList); auto & cbList = pluginCallbackList[cbType]; for(auto it = cbList.begin(); it != cbList.end();) { if(it->pluginHandle == pluginHandle) { cbList.erase(it); return true; } else ++it; } return false; } /** \brief Call all registered callbacks of a certain type. \param cbType The type of callbacks to call. \param [in,out] callbackInfo Information describing the callback. See plugin documentation for more information on this. */ void plugincbcall(CBTYPE cbType, void* callbackInfo) { if(pluginCallbackList[cbType].empty()) return; SHARED_ACQUIRE(LockPluginCallbackList); auto cbList = pluginCallbackList[cbType]; //copy for thread-safety reasons SHARED_RELEASE(); for(const auto & currentCallback : cbList) currentCallback.cbPlugin(cbType, callbackInfo); } /** \brief Checks if any callbacks are registered \param cbType The type of the callback. \return true if no callbacks are registered. */ bool plugincbempty(CBTYPE cbType) { return pluginCallbackList[cbType].empty(); } static bool findPluginName(int pluginHandle, String & name) { SHARED_ACQUIRE(LockPluginList); if(pluginData.initStruct.pluginHandle == pluginHandle) { name = pluginData.initStruct.pluginName; return true; } for(auto & plugin : pluginList) { if(plugin.initStruct.pluginHandle == pluginHandle) { name = plugin.initStruct.pluginName; return true; } } dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN] Invalid plugin handle %d...\n"), pluginHandle); return false; } /** \brief Register a plugin command. \param pluginHandle Handle of the plugin to register a command for. \param command The command text to register. This text cannot contain the '\1' character. This text is not case sensitive. \param cbCommand The command callback. \param debugonly true if the command can only be called during debugging. \return true if it the registration succeeded, false otherwise. */ bool plugincmdregister(int pluginHandle, const char* command, CBPLUGINCOMMAND cbCommand, bool debugonly) { if(!command || strlen(command) >= deflen || strstr(command, "\1")) return false; String plugName; if(!findPluginName(pluginHandle, plugName)) return false; PLUG_COMMAND plugCmd; plugCmd.pluginHandle = pluginHandle; strcpy_s(plugCmd.command, command); if(!dbgcmdnew(command, (CBCOMMAND)cbCommand, debugonly)) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Command \"%s\" failed to register...\n"), plugName.c_str(), command); return false; } EXCLUSIVE_ACQUIRE(LockPluginCommandList); pluginCommandList.push_back(plugCmd); EXCLUSIVE_RELEASE(); dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Command \"%s\" registered!\n"), plugName.c_str(), command); return true; } /** \brief Unregister a plugin command. \param pluginHandle Handle of the plugin to unregister the command from. \param command The command text to unregister. This text is not case sensitive. \return true if the command was found and removed, false otherwise. */ bool plugincmdunregister(int pluginHandle, const char* command) { if(!command || strlen(command) >= deflen || strstr(command, "\1")) return false; String plugName; if(!findPluginName(pluginHandle, plugName)) return false; EXCLUSIVE_ACQUIRE(LockPluginCommandList); for(auto it = pluginCommandList.begin(); it != pluginCommandList.end(); ++it) { const auto & currentCommand = *it; if(currentCommand.pluginHandle == pluginHandle && !strcmp(currentCommand.command, command)) { pluginCommandList.erase(it); EXCLUSIVE_RELEASE(); if(!dbgcmddel(command)) goto beach; dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Command \"%s\" unregistered!\n"), plugName.c_str(), command); return true; } } beach: dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Command \"%s\" failed to unregister...\n"), plugName.c_str(), command); return false; } /** \brief Add a new plugin (sub)menu. \param hMenu The menu handle to add the (sub)menu to. \param title The title of the (sub)menu. \return The handle of the new (sub)menu. */ int pluginmenuadd(int hMenu, const char* title) { if(!title || !strlen(title)) return -1; EXCLUSIVE_ACQUIRE(LockPluginMenuList); int nFound = -1; for(unsigned int i = 0; i < pluginMenuList.size(); i++) { if(pluginMenuList.at(i).hEntryMenu == hMenu) { nFound = i; break; } } if(nFound == -1) //not a valid menu handle return -1; int hMenuNew = GuiMenuAdd(hMenu, title); PLUG_MENU newMenu; newMenu.pluginHandle = pluginMenuList.at(nFound).pluginHandle; newMenu.hEntryMenu = hMenuNew; newMenu.hParentMenu = hMenu; pluginMenuList.push_back(newMenu); return hMenuNew; } /** \brief Add a plugin menu entry to a menu. \param hMenu The menu to add the entry to. \param hEntry The handle you like to have the entry. This should be a unique value in the scope of the plugin that registered the \p hMenu. Cannot be -1. \param title The menu entry title. \return true if the \p hEntry was unique and the entry was successfully added, false otherwise. */ bool pluginmenuaddentry(int hMenu, int hEntry, const char* title) { if(!title || !strlen(title) || hEntry == -1) return false; EXCLUSIVE_ACQUIRE(LockPluginMenuList); int pluginHandle = -1; //find plugin handle for(const auto & currentMenu : pluginMenuList) { if(currentMenu.hEntryMenu == hMenu) { pluginHandle = currentMenu.pluginHandle; break; } } if(pluginHandle == -1) //not found return false; //search if hEntry was previously used for(const auto & currentMenu : pluginMenuEntryList) if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) return false; int hNewEntry = GuiMenuAddEntry(hMenu, title); if(hNewEntry == -1) return false; PLUG_MENUENTRY newMenu; newMenu.hEntryMenu = hNewEntry; newMenu.hParentMenu = hMenu; newMenu.hEntryPlugin = hEntry; newMenu.pluginHandle = pluginHandle; pluginMenuEntryList.push_back(newMenu); return true; } /** \brief Add a menu separator to a menu. \param hMenu The menu to add the separator to. \return true if it succeeds, false otherwise. */ bool pluginmenuaddseparator(int hMenu) { SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuList) { if(currentMenu.hEntryMenu == hMenu) { GuiMenuAddSeparator(hMenu); return true; } } return false; } /// <summary> /// Helper function that recursively clears the menus and their items. /// </summary> /// <param name="hMenu">Handle of the menu to clear.</param> static void pluginmenuclear_helper(int hMenu) { //delete menu entries for(auto i = pluginMenuEntryList.size() - 1; i != -1; i--) if(hMenu == pluginMenuEntryList.at(i).hParentMenu) //we found an entry that has the menu as parent pluginMenuEntryList.erase(pluginMenuEntryList.begin() + i); //delete the menus std::vector<int> menuClearQueue; for(auto i = pluginMenuList.size() - 1; i != -1; i--) { if(hMenu == pluginMenuList.at(i).hParentMenu) //we found a menu that has the menu as parent { menuClearQueue.push_back(pluginMenuList.at(i).hEntryMenu); pluginMenuList.erase(pluginMenuList.begin() + i); } } //recursively clear the menus for(auto & hMenu : menuClearQueue) pluginmenuclear_helper(hMenu); } /** \brief Clears a plugin menu. \param hMenu The menu to clear. \return true if it succeeds, false otherwise. */ bool pluginmenuclear(int hMenu, bool erase) { EXCLUSIVE_ACQUIRE(LockPluginMenuList); pluginmenuclear_helper(hMenu); for(auto it = pluginMenuList.begin(); it != pluginMenuList.end(); ++it) { const auto & currentMenu = *it; if(currentMenu.hEntryMenu == hMenu) { if(erase) { it = pluginMenuList.erase(it); GuiMenuRemove(hMenu); } else GuiMenuClear(hMenu); return true; } } return false; } /** \brief Call the registered CB_MENUENTRY callbacks for a menu entry. \param hEntry The menu entry that triggered the event. */ void pluginmenucall(int hEntry) { if(hEntry == -1) return; SectionLocker<LockPluginMenuList, true, false> menuLock; //shared lock auto i = pluginMenuEntryList.begin(); while(i != pluginMenuEntryList.end()) { const auto currentMenu = *i; ++i; if(currentMenu.hEntryMenu == hEntry && currentMenu.hEntryPlugin != -1) { PLUG_CB_MENUENTRY menuEntryInfo; menuEntryInfo.hEntry = currentMenu.hEntryPlugin; SectionLocker<LockPluginCallbackList, true> callbackLock; //shared lock const auto & cbList = pluginCallbackList[CB_MENUENTRY]; for(auto j = cbList.begin(); j != cbList.end();) { auto currentCallback = *j++; if(currentCallback.pluginHandle == currentMenu.pluginHandle) { menuLock.Unlock(); callbackLock.Unlock(); currentCallback.cbPlugin(currentCallback.cbType, &menuEntryInfo); return; } } } } } /** \brief Calls the registered CB_WINEVENT callbacks. \param [in,out] message the message that triggered the event. Cannot be null. \param [out] result The result value. Cannot be null. \return The value the plugin told it to return. See plugin documentation for more information. */ bool pluginwinevent(MSG* message, long* result) { PLUG_CB_WINEVENT winevent; winevent.message = message; winevent.result = result; winevent.retval = false; //false=handle event, true=ignore event plugincbcall(CB_WINEVENT, &winevent); return winevent.retval; } /** \brief Calls the registered CB_WINEVENTGLOBAL callbacks. \param [in,out] message the message that triggered the event. Cannot be null. \return The value the plugin told it to return. See plugin documentation for more information. */ bool pluginwineventglobal(MSG* message) { PLUG_CB_WINEVENTGLOBAL winevent; winevent.message = message; winevent.retval = false; //false=handle event, true=ignore event plugincbcall(CB_WINEVENTGLOBAL, &winevent); return winevent.retval; } /** \brief Sets an icon for a menu. \param hMenu The menu handle. \param icon The icon (can be all kinds of formats). */ void pluginmenuseticon(int hMenu, const ICONDATA* icon) { SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuList) { if(currentMenu.hEntryMenu == hMenu) { GuiMenuSetIcon(hMenu, icon); break; } } } /** \brief Sets an icon for a menu entry. \param pluginHandle Plugin handle. \param hEntry The menu entry handle (unique per plugin). \param icon The icon (can be all kinds of formats). */ void pluginmenuentryseticon(int pluginHandle, int hEntry, const ICONDATA* icon) { if(hEntry == -1) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuEntryList) { if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) { GuiMenuSetEntryIcon(currentMenu.hEntryMenu, icon); break; } } } void pluginmenuentrysetchecked(int pluginHandle, int hEntry, bool checked) { if(hEntry == -1) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuEntryList) { if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) { GuiMenuSetEntryChecked(currentMenu.hEntryMenu, checked); break; } } } void pluginmenusetvisible(int pluginHandle, int hMenu, bool visible) { SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuList) { if(currentMenu.hEntryMenu == hMenu) { GuiMenuSetVisible(hMenu, visible); break; } } } void pluginmenuentrysetvisible(int pluginHandle, int hEntry, bool visible) { if(hEntry == -1) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuEntryList) { if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) { GuiMenuSetEntryVisible(currentMenu.hEntryMenu, visible); break; } } } void pluginmenusetname(int pluginHandle, int hMenu, const char* name) { if(!name) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuList) { if(currentMenu.hEntryMenu == hMenu) { GuiMenuSetName(hMenu, name); break; } } } void pluginmenuentrysetname(int pluginHandle, int hEntry, const char* name) { if(hEntry == -1 || !name) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuEntryList) { if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) { GuiMenuSetEntryName(currentMenu.hEntryMenu, name); break; } } } void pluginmenuentrysethotkey(int pluginHandle, int hEntry, const char* hotkey) { if(hEntry == -1 || !hotkey) return; SHARED_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuEntryList) { if(currentMenu.pluginHandle == pluginHandle && currentMenu.hEntryPlugin == hEntry) { for(const auto & plugin : pluginList) { if(plugin.initStruct.pluginHandle == pluginHandle) { char name[MAX_PATH] = ""; strcpy_s(name, plugin.plugname); auto dot = strrchr(name, '.'); if(dot != nullptr) *dot = '\0'; auto hack = StringUtils::sprintf("%s\1%s_%d", hotkey, name, hEntry); GuiMenuSetEntryHotkey(currentMenu.hEntryMenu, hack.c_str()); break; } } break; } } } bool pluginmenuremove(int hMenu) { EXCLUSIVE_ACQUIRE(LockPluginMenuList); for(const auto & currentMenu : pluginMenuList) if(currentMenu.hEntryMenu == hMenu && currentMenu.hParentMenu < 256) return false; return pluginmenuclear(hMenu, true); } bool pluginmenuentryremove(int pluginHandle, int hEntry) { EXCLUSIVE_ACQUIRE(LockPluginMenuList); for(auto it = pluginMenuEntryList.begin(); it != pluginMenuEntryList.end(); ++it) { const auto & currentEntry = *it; if(currentEntry.pluginHandle == pluginHandle && currentEntry.hEntryPlugin == hEntry) { GuiMenuRemove(currentEntry.hEntryMenu); pluginMenuEntryList.erase(it); return true; } } return false; } struct ExprFuncWrapper { void* user; int argc; CBPLUGINEXPRFUNCTION cbFunc; std::vector<duint> cbArgv; static bool callback(ExpressionValue* result, int argc, const ExpressionValue* argv, void* userdata) { auto cbUser = reinterpret_cast<ExprFuncWrapper*>(userdata); cbUser->cbArgv.clear(); for(auto i = 0; i < argc; i++) cbUser->cbArgv.push_back(argv[i].number); result->type = ValueTypeNumber; result->number = cbUser->cbFunc(argc, cbUser->cbArgv.data(), cbUser->user); return true; } }; bool pluginexprfuncregister(int pluginHandle, const char* name, int argc, CBPLUGINEXPRFUNCTION cbFunction, void* userdata) { String plugName; if(!findPluginName(pluginHandle, plugName)) return false; PLUG_EXPRFUNCTION plugExprfunction; plugExprfunction.pluginHandle = pluginHandle; strcpy_s(plugExprfunction.name, name); ExprFuncWrapper* wrapper = new ExprFuncWrapper; wrapper->argc = argc; wrapper->cbFunc = cbFunction; wrapper->user = userdata; std::vector<ValueType> args(argc); for(auto & arg : args) arg = ValueTypeNumber; if(!ExpressionFunctions::Register(name, ValueTypeNumber, args, wrapper->callback, wrapper)) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" failed to register...\n"), plugName.c_str(), name); return false; } EXCLUSIVE_ACQUIRE(LockPluginExprfunctionList); pluginExprfunctionList.push_back(plugExprfunction); EXCLUSIVE_RELEASE(); dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" registered!\n"), plugName.c_str(), name); return true; } bool pluginexprfuncregisterex(int pluginHandle, const char* name, const ValueType & returnType, const ValueType* argTypes, size_t argCount, CBPLUGINEXPRFUNCTIONEX cbFunction, void* userdata) { String plugName; if(!findPluginName(pluginHandle, plugName)) return false; PLUG_EXPRFUNCTION plugExprfunction; plugExprfunction.pluginHandle = pluginHandle; strcpy_s(plugExprfunction.name, name); std::vector<ValueType> argTypesVec(argCount); for(size_t i = 0; i < argCount; i++) argTypesVec[i] = argTypes[i]; if(!ExpressionFunctions::Register(name, returnType, argTypesVec, cbFunction, userdata)) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" failed to register...\n"), plugName.c_str(), name); return false; } EXCLUSIVE_ACQUIRE(LockPluginExprfunctionList); pluginExprfunctionList.push_back(plugExprfunction); EXCLUSIVE_RELEASE(); dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" registered!\n"), plugName.c_str(), name); return true; } bool pluginexprfuncunregister(int pluginHandle, const char* name) { String plugName; if(!findPluginName(pluginHandle, plugName)) return false; EXCLUSIVE_ACQUIRE(LockPluginExprfunctionList); for(auto it = pluginExprfunctionList.begin(); it != pluginExprfunctionList.end(); ++it) { const auto & currentExprfunction = *it; if(currentExprfunction.pluginHandle == pluginHandle && !strcmp(currentExprfunction.name, name)) { pluginExprfunctionList.erase(it); EXCLUSIVE_RELEASE(); if(!ExpressionFunctions::Unregister(name)) goto beach; dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" unregistered!\n"), plugName.c_str(), name); return true; } } beach: dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Expression function \"%s\" failed to unregister...\n"), plugName.c_str(), name); return false; } bool pluginformatfuncregister(int pluginHandle, const char* type, CBPLUGINFORMATFUNCTION cbFunction, void* userdata) { String plugName; if(!findPluginName(pluginHandle, plugName)) return false; PLUG_FORMATFUNCTION plugFormatfunction; plugFormatfunction.pluginHandle = pluginHandle; strcpy_s(plugFormatfunction.name, type); if(!FormatFunctions::Register(type, cbFunction, userdata)) { dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Format function \"%s\" failed to register...\n"), plugName.c_str(), type); return false; } EXCLUSIVE_ACQUIRE(LockPluginFormatfunctionList); pluginFormatfunctionList.push_back(plugFormatfunction); EXCLUSIVE_RELEASE(); dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Format function \"%s\" registered!\n"), plugName.c_str(), type); return true; } bool pluginformatfuncunregister(int pluginHandle, const char* type) { String plugName; if(!findPluginName(pluginHandle, plugName)) return false; EXCLUSIVE_ACQUIRE(LockPluginFormatfunctionList); for(auto it = pluginFormatfunctionList.begin(); it != pluginFormatfunctionList.end(); ++it) { const auto & currentFormatfunction = *it; if(currentFormatfunction.pluginHandle == pluginHandle && !strcmp(currentFormatfunction.name, type)) { pluginFormatfunctionList.erase(it); EXCLUSIVE_RELEASE(); if(!FormatFunctions::Unregister(type)) goto beach; dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Format function \"%s\" unregistered!\n"), plugName.c_str(), type); return true; } } beach: dprintf(QT_TRANSLATE_NOOP("DBG", "[PLUGIN, %s] Format function \"%s\" failed to unregister...\n"), plugName.c_str(), type); return false; }
C/C++
x64dbg-development/src/dbg/plugin_loader.h
#ifndef _PLUGIN_LOADER_H #define _PLUGIN_LOADER_H #include "_global.h" #include "_plugins.h" //typedefs typedef bool (*PLUGINIT)(PLUG_INITSTRUCT* initStruct); typedef bool (*PLUGSTOP)(); typedef void (*PLUGSETUP)(PLUG_SETUPSTRUCT* setupStruct); //structures struct PLUG_MENU { int pluginHandle; //plugin handle int hEntryMenu; //GUI entry/menu handle (unique) int hParentMenu; //parent GUI menu handle }; struct PLUG_MENUENTRY : PLUG_MENU { int hEntryPlugin; //plugin entry handle (unique per plugin) }; struct PLUG_DATA { char plugpath[MAX_PATH]; char plugname[MAX_PATH]; bool isLoaded; HINSTANCE hPlugin; PLUGINIT pluginit; PLUGSTOP plugstop; PLUGSETUP plugsetup; int hMenu; int hMenuDisasm; int hMenuDump; int hMenuStack; int hMenuGraph; int hMenuMemmap; int hMenuSymmod; PLUG_INITSTRUCT initStruct; }; struct PLUG_CALLBACK { int pluginHandle; CBTYPE cbType; CBPLUGIN cbPlugin; }; struct PLUG_COMMAND { int pluginHandle; char command[deflen]; }; struct PLUG_EXPRFUNCTION { int pluginHandle; char name[deflen]; }; struct PLUG_FORMATFUNCTION { int pluginHandle; char name[deflen]; }; //plugin management functions bool pluginload(const char* pluginname, bool loadall = false); bool pluginunload(const char* pluginname, bool unloadall = false); void pluginloadall(const char* pluginDir); void pluginunloadall(); void plugincmdunregisterall(int pluginHandle); void pluginexprfuncunregisterall(int pluginHandle); void pluginformatfuncunregisterall(int pluginHandle); void pluginregistercallback(int pluginHandle, CBTYPE cbType, CBPLUGIN cbPlugin); bool pluginunregistercallback(int pluginHandle, CBTYPE cbType); void plugincbcall(CBTYPE cbType, void* callbackInfo); bool plugincbempty(CBTYPE cbType); bool plugincmdregister(int pluginHandle, const char* command, CBPLUGINCOMMAND cbCommand, bool debugonly); bool plugincmdunregister(int pluginHandle, const char* command); int pluginmenuadd(int hMenu, const char* title); bool pluginmenuaddentry(int hMenu, int hEntry, const char* title); bool pluginmenuaddseparator(int hMenu); bool pluginmenuclear(int hMenu, bool erase); void pluginmenucall(int hEntry); bool pluginwinevent(MSG* message, long* result); bool pluginwineventglobal(MSG* message); void pluginmenuseticon(int hMenu, const ICONDATA* icon); void pluginmenuentryseticon(int pluginHandle, int hEntry, const ICONDATA* icon); void pluginmenuentrysetchecked(int pluginHandle, int hEntry, bool checked); void pluginmenusetvisible(int pluginHandle, int hMenu, bool visible); void pluginmenuentrysetvisible(int pluginHandle, int hEntry, bool visible); void pluginmenusetname(int pluginHandle, int hMenu, const char* name); void pluginmenuentrysetname(int pluginHandle, int hEntry, const char* name); void pluginmenuentrysethotkey(int pluginHandle, int hEntry, const char* hotkey); bool pluginmenuremove(int hMenu); bool pluginmenuentryremove(int pluginHandle, int hEntry); bool pluginexprfuncregister(int pluginHandle, const char* name, int argc, CBPLUGINEXPRFUNCTION cbFunction, void* userdata); bool pluginexprfuncregisterex(int pluginHandle, const char* name, const ValueType & returnType, const ValueType* argTypes, size_t argCount, CBPLUGINEXPRFUNCTIONEX cbFunction, void* userdata); bool pluginexprfuncunregister(int pluginHandle, const char* name); bool pluginformatfuncregister(int pluginHandle, const char* type, CBPLUGINFORMATFUNCTION cbFunction, void* userdata); bool pluginformatfuncunregister(int pluginHandle, const char* type); #endif // _PLUGIN_LOADER_H
C++
x64dbg-development/src/dbg/reference.cpp
/** @file reference.cpp @brief Implements the reference class. */ #include "reference.h" #include "memory.h" #include "console.h" #include "module.h" #include "threading.h" /** @brief RefFind Find reference to the buffer by a given criterion. @param Address The base address of the buffer @param Size The size of the buffer @param Callback The callback that is invoked to identify whether an instruction satisfies the criterion. prototype: bool callback(Zydis* disasm, BASIC_INSTRUCTION_INFO* basicinfo, REFINFO* refinfo) @param UserData The data that will be passed to Callback @param Silent If true, no log will be outputed. @param Name The name of the reference criterion. Not null. @param type The type of the memory buffer. Possible values:CURRENT_REGION,CURRENT_MODULE,ALL_MODULES @param disasmText If false, disassembled text will not be available. */ int RefFind(duint Address, duint Size, CBREF Callback, void* UserData, bool Silent, const char* Name, REFFINDTYPE type, bool disasmText) { char fullName[deflen]; char moduleName[MAX_MODULE_SIZE]; duint scanStart, scanSize; REFINFO refInfo; if(type == CURRENT_REGION) // Search in current Region { duint regionSize = 0; duint regionBase = MemFindBaseAddr(Address, &regionSize, true); // If the memory page wasn't found, fail if(!regionBase || !regionSize) { if(!Silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Invalid memory page 0x%p\n"), Address); return 0; } // Assume the entire range is used scanStart = regionBase; scanSize = regionSize; // Otherwise use custom boundaries if size was supplied if(Size) { duint maxsize = Size - (Address - regionBase); // Make sure the size fits in one page scanStart = Address; scanSize = min(Size, maxsize); } // Determine the full module name if(ModNameFromAddr(scanStart, moduleName, true)) sprintf_s(fullName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "%s (Region %s)")), Name, moduleName); else sprintf_s(fullName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "%s (Region %p)")), Name, scanStart); // Initialize disassembler Zydis cp; // Allow an "initialization" notice refInfo.refcount = 0; refInfo.userinfo = UserData; refInfo.name = fullName; RefFindInRange(scanStart, scanSize, Callback, UserData, Silent, refInfo, cp, true, [](int percent) { GuiReferenceSetCurrentTaskProgress(percent, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Region Search"))); GuiReferenceSetProgress(percent); }, disasmText); } else if(type == CURRENT_MODULE) // Search in current Module { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(Address); if(!modInfo) { if(!Silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Couldn't locate module for 0x%p\n"), Address); return 0; } duint modBase = modInfo->base; duint modSize = modInfo->size; SHARED_RELEASE(); scanStart = modBase; scanSize = modSize; // Determine the full module name if(ModNameFromAddr(scanStart, moduleName, true)) sprintf_s(fullName, "%s (%s)", Name, moduleName); else sprintf_s(fullName, "%s (%p)", Name, scanStart); // Initialize disassembler Zydis cp; // Allow an "initialization" notice refInfo.refcount = 0; refInfo.userinfo = UserData; refInfo.name = fullName; RefFindInRange(scanStart, scanSize, Callback, UserData, Silent, refInfo, cp, true, [](int percent) { GuiReferenceSetCurrentTaskProgress(percent, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Module Search"))); GuiReferenceSetProgress(percent); }, disasmText); } else if(type == USER_MODULES) // Search in All User Modules { bool initCallBack = true; struct RefModInfo { duint base; duint size; char name[MAX_MODULE_SIZE]; }; std::vector<RefModInfo> modList; ModEnum([&modList](const MODINFO & mod) { RefModInfo info; info.base = mod.base; info.size = mod.size; strncpy_s(info.name, mod.name, _TRUNCATE); strncat_s(info.name, mod.extension, _TRUNCATE); modList.push_back(info); }); if(!modList.size()) { if(!Silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Couldn't get module list")); return 0; } // Initialize disassembler Zydis cp; // Determine the full module sprintf_s(fullName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "User Modules (%s)")), Name); // Allow an "initialization" notice refInfo.refcount = 0; refInfo.userinfo = UserData; refInfo.name = fullName; for(duint i = 0; i < modList.size(); i++) { int party = ModGetParty(duint(modList[i].base)); if(party != mod_user) continue; scanStart = modList[i].base; scanSize = modList[i].size; RefFindInRange(scanStart, scanSize, Callback, UserData, Silent, refInfo, cp, initCallBack, [&i, &modList](int percent) { float fPercent = (float)percent / 100.f; float fTotalPercent = ((float)i + fPercent) / (float)modList.size(); int totalPercent = (int)floor(fTotalPercent * 100.f); GuiReferenceSetCurrentTaskProgress(percent, modList[i].name); GuiReferenceSetProgress(totalPercent); }, disasmText); initCallBack = false; } } else if(type == SYSTEM_MODULES) // Search in All System Modules { bool initCallBack = true; struct RefModInfo { duint base; duint size; char name[MAX_MODULE_SIZE]; }; std::vector<RefModInfo> modList; ModEnum([&modList](const MODINFO & mod) { RefModInfo info; info.base = mod.base; info.size = mod.size; strncpy_s(info.name, mod.name, _TRUNCATE); strncat_s(info.name, mod.extension, _TRUNCATE); modList.push_back(info); }); if(!modList.size()) { if(!Silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Couldn't get module list")); return 0; } // Initialize disassembler Zydis cp; // Determine the full module sprintf_s(fullName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "System Modules (%s)")), Name); // Allow an "initialization" notice refInfo.refcount = 0; refInfo.userinfo = UserData; refInfo.name = fullName; for(duint i = 0; i < modList.size(); i++) { int party = ModGetParty(duint(modList[i].base)); if(party != mod_system) continue; scanStart = modList[i].base; scanSize = modList[i].size; RefFindInRange(scanStart, scanSize, Callback, UserData, Silent, refInfo, cp, initCallBack, [&i, &modList](int percent) { float fPercent = (float)percent / 100.f; float fTotalPercent = ((float)i + fPercent) / (float)modList.size(); int totalPercent = (int)floor(fTotalPercent * 100.f); GuiReferenceSetCurrentTaskProgress(percent, modList[i].name); GuiReferenceSetProgress(totalPercent); }, disasmText); initCallBack = false; } } else if(type == ALL_MODULES) // Search in all Modules { bool initCallBack = true; struct RefModInfo { duint base; duint size; char name[MAX_MODULE_SIZE]; }; std::vector<RefModInfo> modList; ModEnum([&modList](const MODINFO & mod) { RefModInfo info; info.base = mod.base; info.size = mod.size; strncpy_s(info.name, mod.name, _TRUNCATE); strncat_s(info.name, mod.extension, _TRUNCATE); modList.push_back(info); }); if(!modList.size()) { if(!Silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Couldn't get module list")); return 0; } // Initialize disassembler Zydis cp; // Determine the full module sprintf_s(fullName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "All Modules (%s)")), Name); // Allow an "initialization" notice refInfo.refcount = 0; refInfo.userinfo = UserData; refInfo.name = fullName; for(duint i = 0; i < modList.size(); i++) { scanStart = modList[i].base; scanSize = modList[i].size; if(i != 0) initCallBack = false; RefFindInRange(scanStart, scanSize, Callback, UserData, Silent, refInfo, cp, initCallBack, [&i, &modList](int percent) { float fPercent = (float)percent / 100.f; float fTotalPercent = ((float)i + fPercent) / (float)modList.size(); int totalPercent = (int)floor(fTotalPercent * 100.f); GuiReferenceSetCurrentTaskProgress(percent, modList[i].name); GuiReferenceSetProgress(totalPercent); }, disasmText); } } else return 0; GuiReferenceSetProgress(100); GuiReferenceReloadData(); return refInfo.refcount; } int RefFindInRange(duint scanStart, duint scanSize, CBREF Callback, void* UserData, bool Silent, REFINFO & refInfo, Zydis & cp, bool initCallBack, const CBPROGRESS & cbUpdateProgress, bool disasmText) { // Allocate and read a buffer from the remote process Memory<unsigned char*> data(scanSize, "reffind:data"); memset(data(), 0xCC, data.size()); MemReadDumb(scanStart, data(), scanSize); if(initCallBack) Callback(0, 0, &refInfo); auto percentCount = scanSize / 500; //concurrency::parallel_for(duint (0), scanSize, [&](duint i) for(duint i = 0; i < scanSize;) { // Print the progress every percent if((i % percentCount) == 0) { // Percent = (current / total) * 100 // Integer = floor(percent) int percent = (int)floor(((float)i / (float)scanSize) * 100.0f); cbUpdateProgress(percent); } // Disassemble the instruction int disasmMaxSize = min(MAX_DISASM_BUFFER, (int)(scanSize - i)); // Prevent going past the boundary int disasmLen = 1; if(cp.Disassemble(scanStart, data() + i, disasmMaxSize)) { BASIC_INSTRUCTION_INFO basicinfo; fillbasicinfo(&cp, &basicinfo, disasmText); if(Callback(&cp, &basicinfo, &refInfo)) refInfo.refcount++; disasmLen = cp.Size(); } else { // Invalid instruction detected, so just skip the byte } scanStart += disasmLen; i += disasmLen; } cbUpdateProgress(100); return refInfo.refcount; }
C/C++
x64dbg-development/src/dbg/reference.h
#ifndef _REFERENCE_H #define _REFERENCE_H #include "_global.h" #include "disasm_fast.h" #include <functional> struct REFINFO { int refcount; void* userinfo; const char* name; }; typedef enum { CURRENT_REGION, CURRENT_MODULE, ALL_MODULES, USER_MODULES, SYSTEM_MODULES } REFFINDTYPE; // Reference callback typedef typedef bool (*CBREF)(Zydis* disasm, BASIC_INSTRUCTION_INFO* basicinfo, REFINFO* refinfo); typedef std::function<void(int)> CBPROGRESS; int RefFind(duint Address, duint Size, CBREF Callback, void* UserData, bool Silent, const char* Name, REFFINDTYPE type, bool disasmText); int RefFindInRange(duint scanStart, duint scanSize, CBREF Callback, void* UserData, bool Silent, REFINFO & refInfo, Zydis & cp, bool initCallBack, const CBPROGRESS & cbUpdateProgress, bool disasmText); #endif // _REFERENCE_H
Text
x64dbg-development/src/dbg/script_commands.txt
odbgscript commands: general purpose: $result $result_1 $result_2 $result_3 $result_4 $version **eval refresh *var *varlist *help assembly: *asm *asmtxt **exec ende *opcode preop automation: an **cmt *dbh *dbs key ***lbl **lc **lclr opendump opentrace tc breakpoints: *bc *bd *bp bpcnd *bpd ***bpgoto *bphwc *bphws bpl bplcnd *bpmc *bprm *bpwm *bpx cob coe eob eoe gpmb gbpr mathematic, binary operands: *add *and *dec *div *inc *mov *mul *neg *not *or *rev *rol *ror *shl *shr *sub *test *xor *xchg jump, call, conditional jumps: call *cmp cret goto //jump ifa //if above ifae //if above or equal ifb //if below ifbe //if below or equal ifeq //if equal ifneq //if not equal ja //jump above jae //jump above or equal jb //jump below jbe //jump below or equal je //jump equal jg //jump greater jge //jump greater or equal jl //jump less jle //jump less or equal jmp //jump jne //jump if not equal jnz //jump if not zero jz //jump if zero ret //end if script log commands: #log **log **logbuf ***wrt ***wrta strings: *atoi buf *itoa *len readstr scmp scmpi *str stepping: ai ao *erun *esti *esto *go *rtr **rtu *run *sti *sto ti ticnd to tocnd information: gapi *gci gcmt gma *gmemi *gmi gn *gpa gpi gro **ref tick memory: *alloc *dm *dma *dpe *fill *free *lm *memcpy *pop *push search: *find **findcalls **findcmd *findop *findmem gref *repl user interface: ***ask ***msg ***msgyn ***pause setoption
C/C++
x64dbg-development/src/dbg/serializablemap.h
#ifndef _SERIALIZABLEMAP_H #define _SERIALIZABLEMAP_H #include "_global.h" #include "threading.h" #include "module.h" #include "memory.h" #include "jansson/jansson_x64dbg.h" template<class TValue> class JSONWrapper { public: virtual ~JSONWrapper() { } void SetJson(JSON json) { mJson = json; } virtual bool Save(const TValue & value) = 0; virtual bool Load(TValue & value) = 0; protected: void setString(const char* key, const std::string & value) { set(key, json_string(value.c_str())); } bool getString(const char* key, std::string & dest) const { auto jsonValue = get(key); if(!jsonValue) return false; auto str = json_string_value(jsonValue); if(!str) return false; dest = str; return true; } void setHex(const char* key, duint value) { set(key, json_hex(value)); } bool getHex(const char* key, duint & value) const { auto jsonValue = get(key); if(!jsonValue) return false; value = duint(json_hex_value(jsonValue)); return true; } void setBool(const char* key, bool value) { set(key, json_boolean(value)); } bool getBool(const char* key, bool & value) const { auto jsonValue = get(key); if(!jsonValue) return false; value = json_boolean_value(jsonValue); return true; } template<typename T> void setInt(const char* key, T value) { set(key, json_integer(value)); } template<typename T> bool getInt(const char* key, T & value) { auto jsonValue = get(key); if(!jsonValue) return false; value = T(json_integer_value(jsonValue)); return true; } // ReSharper disable once CppMemberFunctionMayBeConst void set(const char* key, JSON value) { json_object_set_new(mJson, key, value); } JSON get(const char* key) const { return json_object_get(mJson, key); } JSON mJson = nullptr; }; template<SectionLock TLock, class TKey, class TValue, class TMap, class TSerializer> class SerializableTMap { static_assert(std::is_base_of<JSONWrapper<TValue>, TSerializer>::value, "TSerializer is not derived from JSONWrapper<TValue>"); public: using TValuePred = std::function<bool(const TValue & value)>; virtual ~SerializableTMap() { } bool Add(const TValue & value) { EXCLUSIVE_ACQUIRE(TLock); return addNoLock(value); } bool Get(const TKey & key, TValue & value) const { SHARED_ACQUIRE(TLock); auto found = mMap.find(key); if(found == mMap.end()) return false; value = found->second; return true; } bool Contains(const TKey & key) const { SHARED_ACQUIRE(TLock); return mMap.count(key) > 0; } bool Delete(const TKey & key) { EXCLUSIVE_ACQUIRE(TLock); return mMap.erase(key) > 0; } void DeleteWhere(TValuePred predicate) { EXCLUSIVE_ACQUIRE(TLock); for(auto itr = mMap.begin(); itr != mMap.end();) { if(predicate(itr->second)) itr = mMap.erase(itr); else ++itr; } } bool GetWhere(TValuePred predicate, TValue & value) { return getWhere(predicate, &value); } bool GetWhere(TValuePred predicate) { return getWhere(predicate, nullptr); } void Clear() { EXCLUSIVE_ACQUIRE(TLock); TMap empty; std::swap(mMap, empty); } void CacheSave(JSON root) const { SHARED_ACQUIRE(TLock); auto jsonValues = json_array(); TSerializer serializer; for(const auto & itr : mMap) { auto jsonValue = json_object(); serializer.SetJson(jsonValue); if(serializer.Save(itr.second)) json_array_append(jsonValues, jsonValue); json_decref(jsonValue); } if(json_array_size(jsonValues)) json_object_set(root, jsonKey(), jsonValues); json_decref(jsonValues); } void CacheLoad(JSON root, const char* keyprefix = nullptr) { EXCLUSIVE_ACQUIRE(TLock); auto jsonValues = json_object_get(root, keyprefix ? (keyprefix + String(jsonKey())).c_str() : jsonKey()); if(!jsonValues) return; size_t i; JSON jsonValue; TSerializer deserializer; json_array_foreach(jsonValues, i, jsonValue) { deserializer.SetJson(jsonValue); TValue value; if(deserializer.Load(value)) addNoLock(value); } } void GetList(std::vector<TValue> & values) const { SHARED_ACQUIRE(TLock); values.clear(); values.reserve(mMap.size()); for(const auto & itr : mMap) values.push_back(itr.second); } bool Enum(TValue* list, size_t* size) const { if(!list && !size) return false; SHARED_ACQUIRE(TLock); if(size) { *size = mMap.size() * sizeof(TValue); if(!list) return true; } for(auto & itr : mMap) { *list = TValue(itr.second); AdjustValue(*list); ++list; } return true; } bool GetInfo(const TKey & key, TValue* valuePtr) const { TValue value; if(!Get(key, value)) return false; if(valuePtr) *valuePtr = value; return true; } TMap & GetDataUnsafe() { return mMap; } virtual void AdjustValue(TValue & value) const = 0; protected: virtual const char* jsonKey() const = 0; virtual TKey makeKey(const TValue & value) const = 0; private: TMap mMap; bool addNoLock(const TValue & value) { mMap[makeKey(value)] = value; return true; } bool getWhere(TValuePred predicate, TValue* value) { SHARED_ACQUIRE(TLock); for(const auto & itr : mMap) { if(!predicate(itr.second)) continue; if(value) *value = itr.second; return true; } return false; } }; template<SectionLock TLock, class TKey, class TValue, class TSerializer, class THash = std::hash<TKey>> using SerializableUnorderedMap = SerializableTMap<TLock, TKey, TValue, std::unordered_map<TKey, TValue, THash>, TSerializer>; template<SectionLock TLock, class TKey, class TValue, class TSerializer, class TCompare = std::less<TKey>> using SerializableMap = SerializableTMap<TLock, TKey, TValue, std::map<TKey, TValue, TCompare>, TSerializer>; template<SectionLock TLock, class TValue, class TSerializer> struct SerializableModuleRangeMap : SerializableMap<TLock, ModuleRange, TValue, TSerializer, ModuleRangeCompare> { static ModuleRange VaKey(duint start, duint end) { auto moduleBase = ModBaseFromAddr(start); return ModuleRange(ModHashFromAddr(moduleBase), Range(start - moduleBase, end - moduleBase)); } }; template<SectionLock TLock, class TValue, class TSerializer> struct SerializableModuleHashMap : SerializableUnorderedMap<TLock, duint, TValue, TSerializer> { static duint VaKey(duint addr) { return ModHashFromAddr(addr); } void DeleteRangeWhere(duint start, duint end, std::function<bool(duint, duint, const TValue &)> inRange) { // Are all comments going to be deleted? // 0x00000000 - 0xFFFFFFFF if(start == 0 && end == ~0) { this->Clear(); } else { // Make sure 'Start' and 'End' reference the same module duint moduleBase = ModBaseFromAddr(start); if(moduleBase != ModBaseFromAddr(end)) return; // Virtual -> relative offset start -= moduleBase; end -= moduleBase; this->DeleteWhere([start, end, inRange](const TValue & value) { return inRange(start, end, value); }); } } }; struct AddrInfo { duint modhash; duint addr; bool manual; std::string mod() const { return ModNameFromHash(modhash); } }; template<class TValue> struct AddrInfoSerializer : JSONWrapper<TValue> { static_assert(std::is_base_of<AddrInfo, TValue>::value, "TValue is not derived from AddrInfo"); bool Save(const TValue & value) override { this->setString("module", value.mod()); this->setHex("address", value.addr); this->setBool("manual", value.manual); return true; } bool Load(TValue & value) override { value.manual = true; //legacy support this->getBool("manual", value.manual); std::string mod; if(!this->getString("module", mod)) return false; value.modhash = ModHashFromName(mod.c_str()); return this->getHex("address", value.addr); } }; template<SectionLock TLock, class TValue, class TSerializer> struct AddrInfoHashMap : SerializableModuleHashMap<TLock, TValue, TSerializer> { static_assert(std::is_base_of<AddrInfo, TValue>::value, "TValue is not derived from AddrInfo"); static_assert(std::is_base_of<AddrInfoSerializer<TValue>, TSerializer>::value, "TSerializer is not derived from AddrInfoSerializer"); void AdjustValue(TValue & value) const override { value.addr += ModBaseFromName(value.mod().c_str()); } bool PrepareValue(TValue & value, duint addr, bool manual) { if(!MemIsValidReadPtr(addr)) return false; auto base = ModBaseFromAddr(addr); value.modhash = ModHashFromAddr(base); value.manual = manual; value.addr = addr - base; return true; } void DeleteRange(duint start, duint end, bool manual) { this->DeleteRangeWhere(start, end, [manual](duint start, duint end, const TValue & value) { if(manual ? !value.manual : value.manual) //ignore non-matching entries return false; return value.addr >= start && value.addr < end; }); } protected: duint makeKey(const TValue & value) const override { return value.modhash + value.addr; } }; #endif // _SERIALIZABLEMAP_H
C++
x64dbg-development/src/dbg/simplescript.cpp
/** @file simplescript.cpp @brief Implements the simplescript class. */ #include "simplescript.h" #include "console.h" #include "variable.h" #include "debugger.h" #include "filehelper.h" #include <thread> enum CMDRESULT { STATUS_ERROR = false, STATUS_CONTINUE = true, STATUS_EXIT = 2, STATUS_PAUSE = 3 }; static std::vector<LINEMAPENTRY> linemap; static std::vector<SCRIPTBP> scriptbplist; static std::vector<int> scriptstack; static int scriptIp = 0; static int scriptIpOld = 0; static bool volatile bAbort = false; static bool volatile bIsRunning = false; static bool scriptLogEnabled = false; static CMDRESULT scriptLastError = STATUS_ERROR; static SCRIPTBRANCHTYPE scriptgetbranchtype(const char* text) { char newtext[MAX_SCRIPT_LINE_SIZE] = ""; strcpy_s(newtext, StringUtils::Trim(text).c_str()); if(!strstr(newtext, " ")) strcat_s(newtext, " "); if(!strncmp(newtext, "jmp ", 4) || !strncmp(newtext, "goto ", 5)) return scriptjmp; else if(!strncmp(newtext, "jbe ", 4) || !strncmp(newtext, "ifbe ", 5) || !strncmp(newtext, "ifbeq ", 6) || !strncmp(newtext, "jle ", 4) || !strncmp(newtext, "ifle ", 5) || !strncmp(newtext, "ifleq ", 6)) return scriptjbejle; else if(!strncmp(newtext, "jae ", 4) || !strncmp(newtext, "ifae ", 5) || !strncmp(newtext, "ifaeq ", 6) || !strncmp(newtext, "jge ", 4) || !strncmp(newtext, "ifge ", 5) || !strncmp(newtext, "ifgeq ", 6)) return scriptjaejge; else if(!strncmp(newtext, "jne ", 4) || !strncmp(newtext, "ifne ", 5) || !strncmp(newtext, "ifneq ", 6) || !strncmp(newtext, "jnz ", 4) || !strncmp(newtext, "ifnz ", 5)) return scriptjnejnz; else if(!strncmp(newtext, "je ", 3) || !strncmp(newtext, "ife ", 4) || !strncmp(newtext, "ifeq ", 5) || !strncmp(newtext, "jz ", 3) || !strncmp(newtext, "ifz ", 4)) return scriptjejz; else if(!strncmp(newtext, "jb ", 3) || !strncmp(newtext, "ifb ", 4) || !strncmp(newtext, "jl ", 3) || !strncmp(newtext, "ifl ", 4)) return scriptjbjl; else if(!strncmp(newtext, "ja ", 3) || !strncmp(newtext, "ifa ", 4) || !strncmp(newtext, "jg ", 3) || !strncmp(newtext, "ifg ", 4)) return scriptjajg; else if(!strncmp(newtext, "call ", 5)) return scriptcall; return scriptnobranch; } static int scriptlabelfind(const char* labelname) { int linecount = (int)linemap.size(); for(int i = 0; i < linecount; i++) if(linemap.at(i).type == linelabel && !strcmp(linemap.at(i).u.label, labelname)) return i + 1; return 0; } static inline bool isEmptyLine(SCRIPTLINETYPE type) { return type == lineempty || type == linecomment || type == linelabel; } static int scriptinternalstep(int fromIp) //internal step routine { int maxIp = (int)linemap.size(); //maximum ip if(fromIp >= maxIp) //script end return fromIp; while(isEmptyLine(linemap.at(fromIp).type) && fromIp < maxIp) //skip empty lines fromIp++; fromIp++; return fromIp; } static bool scriptisinternalcommand(const char* text, const char* cmd) { int len = (int)strlen(text); int cmdlen = (int)strlen(cmd); if(cmdlen > len) return false; else if(cmdlen == len) return scmp(text, cmd); else if(text[cmdlen] == ' ') return (!_strnicmp(text, cmd, cmdlen)); return false; } static bool scriptcreatelinemap(const char* filename) { String filedata; if(!FileHelper::ReadAllText(filename, filedata)) { String TranslatedString = GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "FileHelper::ReadAllText failed...")); GuiScriptError(0, TranslatedString.c_str()); return false; } auto len = filedata.length(); char temp[256] = ""; LINEMAPENTRY entry; memset(&entry, 0, sizeof(entry)); linemap.clear(); for(size_t i = 0, j = 0; i < len; i++) //make raw line map { if(filedata[i] == '\r' && filedata[i + 1] == '\n') //windows file { memset(&entry, 0, sizeof(entry)); int add = 0; while(isspace(temp[add])) add++; strcpy_s(entry.raw, temp + add); *temp = 0; j = 0; i++; linemap.push_back(entry); } else if(filedata[i] == '\n') //other file { memset(&entry, 0, sizeof(entry)); int add = 0; while(isspace(temp[add])) add++; strcpy_s(entry.raw, temp + add); *temp = 0; j = 0; linemap.push_back(entry); } else if(j >= 254) { memset(&entry, 0, sizeof(entry)); int add = 0; while(isspace(temp[add])) add++; strcpy_s(entry.raw, temp + add); *temp = 0; j = 0; linemap.push_back(entry); } else j += sprintf_s(temp + j, sizeof(temp) - j, "%c", filedata[i]); } if(*temp) { memset(&entry, 0, sizeof(entry)); strcpy_s(entry.raw, temp); linemap.push_back(entry); } int linemapsize = (int)linemap.size(); while(linemapsize && !*linemap.at(linemapsize - 1).raw) //remove empty lines from the end { linemapsize--; linemap.pop_back(); } for(int i = 0; i < linemapsize; i++) { LINEMAPENTRY cur = linemap.at(i); //temp. remove comments from the raw line char line_comment[256] = ""; char* comment = nullptr; { auto len = strlen(cur.raw); auto inquote = false; auto inescape = false; for(size_t i = 0; i < len; i++) { auto ch = cur.raw[i]; switch(ch) //simple state machine to determine if the "//" is in quotes { case '\"': if(!inescape) inquote = !inquote; inescape = false; break; case '\\': inescape = !inescape; break; default: inescape = false; } if(!inquote && ch == '/' && i + 1 < len && cur.raw[i + 1] == '/') { comment = cur.raw + i; break; } } } if(comment && comment != cur.raw) //only when the line doesnt start with a comment { if(*(comment - 1) == ' ') //space before comment { strcpy_s(line_comment, comment); *(comment - 1) = '\0'; } else //no space before comment { strcpy_s(line_comment, comment); *comment = 0; } } int rawlen = (int)strlen(cur.raw); if(!rawlen) //empty { cur.type = lineempty; } else if(!strncmp(cur.raw, "//", 2) || *cur.raw == ';') //comment { cur.type = linecomment; strcpy_s(cur.u.comment, cur.raw); } else if(cur.raw[rawlen - 1] == ':') //label { cur.type = linelabel; sprintf_s(cur.u.label, "l %.*s", rawlen - 1, cur.raw); //create a fake command for formatting strcpy_s(cur.u.label, StringUtils::Trim(cur.u.label).c_str()); strcpy_s(temp, cur.u.label + 2); strcpy_s(cur.u.label, temp); //remove fake command if(!*cur.u.label || !strcmp(cur.u.label, "\"\"")) //no label text { char message[256] = ""; sprintf_s(message, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Empty label detected on line %d!")), i + 1); GuiScriptError(0, message); linemap.clear(); return false; } int foundlabel = scriptlabelfind(cur.u.label); if(foundlabel) //label defined twice { char message[256] = ""; sprintf_s(message, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Duplicate label \"%s\" detected on lines %d and %d!")), cur.u.label, foundlabel, i + 1); GuiScriptError(0, message); linemap.clear(); return false; } } else if(scriptgetbranchtype(cur.raw) != scriptnobranch) //branch { cur.type = linebranch; cur.u.branch.type = scriptgetbranchtype(cur.raw); char newraw[MAX_SCRIPT_LINE_SIZE] = ""; strcpy_s(newraw, StringUtils::Trim(cur.raw).c_str()); int rlen = (int)strlen(newraw); for(int j = 0; j < rlen; j++) if(newraw[j] == ' ') { strcpy_s(cur.u.branch.branchlabel, newraw + j + 1); break; } } else { cur.type = linecommand; strcpy_s(cur.u.command, cur.raw); } //append the comment to the raw line again if(*line_comment) sprintf_s(cur.raw + rawlen, sizeof(cur.raw) - rawlen, "\1%s", line_comment); linemap.at(i) = cur; } linemapsize = (int)linemap.size(); for(int i = 0; i < linemapsize; i++) { auto & currentLine = linemap.at(i); if(currentLine.type == linebranch) //invalid branch label { int labelline = scriptlabelfind(currentLine.u.branch.branchlabel); if(!labelline) //invalid branch label { char message[256] = ""; sprintf_s(message, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Invalid branch label \"%s\" detected on line %d!")), currentLine.u.branch.branchlabel, i + 1); GuiScriptError(0, message); linemap.clear(); return false; } else //set the branch destination line currentLine.u.branch.dest = scriptinternalstep(labelline); } } // append a ret instruction at the end of the script when appropriate if(!linemap.empty()) { memset(&entry, 0, sizeof(entry)); entry.type = linecommand; strcpy_s(entry.raw, "ret"); strcpy_s(entry.u.command, "ret"); const auto & lastline = linemap.back(); switch(lastline.type) { case linecommand: if(scriptisinternalcommand(lastline.u.command, "ret") || scriptisinternalcommand(lastline.u.command, "invalid") || scriptisinternalcommand(lastline.u.command, "error")) { // there is already a terminating command at the end of the script } else { linemap.push_back(entry); } break; case linebranch: // an unconditional branch at the end of the script can only go back if(lastline.u.branch.type == scriptjmp) break; // fallthough to append the ret case linelabel: case linecomment: case lineempty: linemap.push_back(entry); break; } } return true; } static bool scriptinternalbpget(int line) //internal bpget routine { int bpcount = (int)scriptbplist.size(); for(int i = 0; i < bpcount; i++) if(scriptbplist.at(i).line == line) return true; return false; } static bool scriptinternalbptoggle(int line) //internal breakpoint { if(!line || line > (int)linemap.size()) //invalid line return false; line = scriptinternalstep(line - 1); //no breakpoints on non-executable locations if(scriptinternalbpget(line)) //remove breakpoint { int bpcount = (int)scriptbplist.size(); for(int i = 0; i < bpcount; i++) if(scriptbplist.at(i).line == line) { scriptbplist.erase(scriptbplist.begin() + i); break; } } else //add breakpoint { SCRIPTBP newbp; newbp.silent = true; newbp.line = line; scriptbplist.push_back(newbp); } return true; } static bool scriptinternalbranch(SCRIPTBRANCHTYPE type) //determine if we should jump { duint ezflag = 0; duint bsflag = 0; varget("$_EZ_FLAG", &ezflag, 0, 0); varget("$_BS_FLAG", &bsflag, 0, 0); bool bJump = false; switch(type) { case scriptcall: case scriptjmp: bJump = true; break; case scriptjnejnz: //$_EZ_FLAG=0 if(!ezflag) bJump = true; break; case scriptjejz: //$_EZ_FLAG=1 if(ezflag) bJump = true; break; case scriptjbjl: //$_BS_FLAG=0 and $_EZ_FLAG=0 //below, not equal if(!bsflag && !ezflag) bJump = true; break; case scriptjajg: //$_BS_FLAG=1 and $_EZ_FLAG=0 //above, not equal if(bsflag && !ezflag) bJump = true; break; case scriptjbejle: //$_BS_FLAG=0 or $_EZ_FLAG=1 if(!bsflag || ezflag) bJump = true; break; case scriptjaejge: //$_BS_FLAG=1 or $_EZ_FLAG=1 if(bsflag || ezflag) bJump = true; break; default: bJump = false; break; } return bJump; } static CMDRESULT scriptinternalcmdexec(const char* cmd, bool silentRet) { if(scriptisinternalcommand(cmd, "ret")) //script finished { if(!scriptstack.size()) //nothing on the stack { if(!silentRet) { String TranslatedString = GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Script finished!")); GuiScriptMessage(TranslatedString.c_str()); } return STATUS_EXIT; } scriptIp = scriptstack.back(); scriptstack.pop_back(); //remove last stack entry return STATUS_CONTINUE; } else if(scriptisinternalcommand(cmd, "error")) //show an error and end the script { GuiScriptError(0, StringUtils::Trim(cmd + strlen("error"), " \"'").c_str()); return STATUS_EXIT; } else if(scriptisinternalcommand(cmd, "invalid")) //invalid command for testing return STATUS_ERROR; else if(scriptisinternalcommand(cmd, "pause")) //pause the script return STATUS_PAUSE; else if(scriptisinternalcommand(cmd, "nop")) //do nothing return STATUS_CONTINUE; else if(scriptisinternalcommand(cmd, "log")) scriptLogEnabled = true; //super disgusting hack(s) to support branches in the GUI { auto branchtype = scriptgetbranchtype(cmd); if(branchtype != scriptnobranch) { String cmdStr = cmd; auto branchlabel = StringUtils::Trim(cmdStr.substr(cmdStr.find(' '))); auto labelIp = scriptlabelfind(branchlabel.c_str()); if(!labelIp) { char message[256] = ""; sprintf_s(message, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Invalid branch label \"%s\" detected on line %d!")), branchlabel.c_str(), 0); GuiScriptError(0, message); return STATUS_ERROR; } if(scriptinternalbranch(branchtype)) { if(branchtype == scriptcall) //calls have a special meaning scriptstack.push_back(scriptIp); scriptIp = scriptinternalstep(labelIp); //go to the first command after the label GuiScriptSetIp(scriptIp); } return STATUS_CONTINUE; } } auto res = cmddirectexec(cmd); while(DbgIsDebugging() && dbgisrunning() && !bAbort) //while not locked (NOTE: possible deadlock) { Sleep(1); GuiProcessEvents(); //workaround for scripts being executed on the GUI thread } scriptLogEnabled = false; return res ? STATUS_CONTINUE : STATUS_ERROR; } static bool scriptinternalcmd(bool silentRet) { bool bContinue = true; if(size_t(scriptIp - 1) >= linemap.size()) return false; const LINEMAPENTRY & cur = linemap.at(scriptIp - 1); scriptIpOld = scriptIp; scriptIp = scriptinternalstep(scriptIp); if(cur.type == linecommand) { scriptLastError = scriptinternalcmdexec(cur.u.command, silentRet); switch(scriptLastError) { case STATUS_CONTINUE: if(scriptIp == scriptIpOld) { bContinue = false; scriptIp = scriptinternalstep(0); } break; case STATUS_ERROR: bContinue = false; scriptIp = scriptIpOld; GuiScriptError(scriptIp, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Error executing command!"))); break; case STATUS_EXIT: bContinue = false; scriptIp = scriptinternalstep(0); GuiScriptSetIp(scriptIp); break; case STATUS_PAUSE: bContinue = false; //stop running the script GuiScriptSetIp(scriptIp); break; } } else if(cur.type == linebranch) { if(scriptinternalbranch(cur.u.branch.type)) { if(cur.u.branch.type == scriptcall) //calls have a special meaning scriptstack.push_back(scriptIp); scriptIp = scriptlabelfind(cur.u.branch.branchlabel); scriptIp = scriptinternalstep(scriptIp); //go to the first command after the label } } return bContinue; } static DWORD WINAPI scriptLoadSyncThread(LPVOID filename) { scriptLoadSync(reinterpret_cast<const char*>(filename)); return 0; } bool scriptRunSync(int destline, bool silentRet) { // disable GUI updates auto guiUpdateWasDisabled = GuiIsUpdateDisabled(); if(!guiUpdateWasDisabled) GuiUpdateDisable(); if(!destline || destline > (int)linemap.size()) //invalid line destline = 0; if(destline) { destline = scriptinternalstep(destline - 1); //no breakpoints on non-executable locations if(!scriptinternalbpget(destline)) //no breakpoint set scriptinternalbptoggle(destline); } bAbort = false; if(scriptIp) scriptIp--; scriptIp = scriptinternalstep(scriptIp); bool bContinue = true; bool bIgnoreTimeout = settingboolget("Engine", "NoScriptTimeout"); unsigned long long kernelTime, userTime; FILETIME creationTime, exitTime; // unused while(bContinue && !bAbort) //run loop { bContinue = scriptinternalcmd(silentRet); if(scriptinternalbpget(scriptIp)) //breakpoint=stop run loop bContinue = false; if(bContinue && !bIgnoreTimeout && GetThreadTimes(GetCurrentThread(), &creationTime, &exitTime, reinterpret_cast<LPFILETIME>(&kernelTime), reinterpret_cast<LPFILETIME>(&userTime)) != 0) { if(userTime + kernelTime >= 10 * 10000000) // time out in 10 seconds of CPU time { if(GuiScriptMsgyn(GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "The script is too busy. Would you like to terminate it now?"))) != 0) { dputs(QT_TRANSLATE_NOOP("DBG", "Script is terminated by user.")); break; } else bIgnoreTimeout = true; } } } bIsRunning = false; //not running anymore // re-enable GUI updates when appropriate if(!guiUpdateWasDisabled) GuiUpdateEnable(true); GuiScriptSetIp(scriptIp); // the script fully executed (which means scriptIp is reset to the first line), without any errors return scriptIp == scriptinternalstep(0) && (scriptLastError == STATUS_EXIT || scriptLastError == STATUS_CONTINUE); } bool scriptLoadSync(const char* filename) { GuiScriptClear(); GuiScriptEnableHighlighting(true); //enable default script syntax highlighting scriptIp = 0; scriptIpOld = 0; scriptbplist.clear(); scriptstack.clear(); bAbort = false; if(!scriptcreatelinemap(reinterpret_cast<const char*>(filename))) return false; // Script load failed int lines = (int)linemap.size(); const char** script = reinterpret_cast<const char**>(BridgeAlloc(lines * sizeof(const char*))); for(int i = 0; i < lines; i++) //add script lines script[i] = linemap.at(i).raw; GuiScriptAdd(lines, script); scriptIp = scriptinternalstep(0); GuiScriptSetIp(scriptIp); return true; } void scriptload(const char* filename) { static char filename_[MAX_PATH] = ""; strcpy_s(filename_, filename); auto hThread = CreateThread(nullptr, 0, scriptLoadSyncThread, filename_, 0, nullptr); while(WaitForSingleObject(hThread, 100) == WAIT_TIMEOUT) GuiProcessEvents(); CloseHandle(hThread); } void scriptunload() { GuiScriptClear(); linemap.clear(); scriptbplist.clear(); scriptstack.clear(); scriptIp = 0; scriptIpOld = 0; bAbort = false; } void scriptrun(int destline) { if(DbgIsDebugging() && dbgisrunning()) { GuiScriptError(0, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Debugger must be paused to run a script!"))); return; } if(bIsRunning) //already running return; bIsRunning = true; std::thread t([destline] { scriptRunSync(destline, false); }); t.detach(); } void scriptstep() { std::thread t([] { if(!bIsRunning) //only step when not running { scriptinternalcmd(false); GuiScriptSetIp(scriptIp); } }); t.detach(); } bool scriptbptoggle(int line) { if(!line || line > (int)linemap.size()) //invalid line return false; line = scriptinternalstep(line - 1); //no breakpoints on non-executable locations if(scriptbpget(line)) //remove breakpoint { int bpcount = (int)scriptbplist.size(); for(int i = 0; i < bpcount; i++) if(scriptbplist.at(i).line == line && !scriptbplist.at(i).silent) { scriptbplist.erase(scriptbplist.begin() + i); break; } } else //add breakpoint { SCRIPTBP newbp; newbp.silent = false; newbp.line = line; scriptbplist.push_back(newbp); } return true; } bool scriptbpget(int line) { int bpcount = (int)scriptbplist.size(); for(int i = 0; i < bpcount; i++) if(scriptbplist.at(i).line == line && !scriptbplist.at(i).silent) return true; return false; } bool scriptcmdexec(const char* command) { scriptIpOld = scriptIp; scriptLastError = scriptinternalcmdexec(command, false); switch(scriptLastError) { case STATUS_ERROR: return false; case STATUS_EXIT: scriptIp = scriptinternalstep(0); GuiScriptSetIp(scriptIp); break; case STATUS_PAUSE: case STATUS_CONTINUE: break; } return true; } void scriptabort() { if(bIsRunning) { bAbort = true; while(bIsRunning) Sleep(1); } else //reset the script scriptsetip(0); } SCRIPTLINETYPE scriptgetlinetype(int line) { if(line > (int)linemap.size()) return lineempty; return linemap.at(line - 1).type; } void scriptsetip(int line) { if(line) line--; scriptIp = scriptinternalstep(line); GuiScriptSetIp(scriptIp); } void scriptreset() { while(bIsRunning) { bAbort = true; Sleep(1); } Sleep(10); scriptsetip(0); } bool scriptgetbranchinfo(int line, SCRIPTBRANCH* info) { if(!info || !line || line > (int)linemap.size()) //invalid line return false; if(linemap.at(line - 1).type != linebranch) //no branch return false; memcpy(info, &linemap.at(line - 1).u.branch, sizeof(SCRIPTBRANCH)); return true; } void scriptlog(const char* msg) { if(!scriptLogEnabled) return; GuiScriptSetInfoLine(scriptIpOld, msg); }
C/C++
x64dbg-development/src/dbg/simplescript.h
#ifndef _SIMPLESCRIPT_H #define _SIMPLESCRIPT_H #include "command.h" //structures struct SCRIPTBP { int line; bool silent; //do not show in GUI }; struct LINEMAPENTRY { SCRIPTLINETYPE type; char raw[256]; union { char command[256]; SCRIPTBRANCH branch; char label[256]; char comment[256]; } u; }; //functions void scriptload(const char* filename); void scriptunload(); void scriptrun(int destline); void scriptstep(); bool scriptbptoggle(int line); bool scriptbpget(int line); bool scriptcmdexec(const char* command); void scriptabort(); SCRIPTLINETYPE scriptgetlinetype(int line); void scriptsetip(int line); void scriptreset(); bool scriptgetbranchinfo(int line, SCRIPTBRANCH* info); void scriptlog(const char* msg); bool scriptLoadSync(const char* filename); bool scriptRunSync(int destline, bool silentRet); //script commands #endif // _SIMPLESCRIPT_H
C++
x64dbg-development/src/dbg/stackinfo.cpp
/** @file stackinfo.cpp @brief Implements the stackinfo class. */ #include "stackinfo.h" #include "memory.h" #include "disasm_helper.h" #include "disasm_fast.h" #include "_exports.h" #include "module.h" #include "thread.h" #include "threading.h" #include "exhandlerinfo.h" #include "symbolinfo.h" #include "debugger.h" #include "dbghelp_safe.h" using SehMap = std::unordered_map<duint, STACK_COMMENT>; static SehMap SehCache; bool ShowSuspectedCallStack; void stackupdateseh() { SehMap newcache; std::vector<duint> SEHList; if(ExHandlerGetSEH(SEHList)) { STACK_COMMENT comment; strcpy_s(comment.color, "!sehclr"); // Special token for SEH chain color. auto count = SEHList.size(); for(duint i = 0; i < count; i++) { if(i + 1 != count) sprintf_s(comment.comment, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Pointer to SEH_Record[%d]")), i + 1); else sprintf_s(comment.comment, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "End of SEH Chain"))); newcache.insert({ SEHList[i], comment }); } } EXCLUSIVE_ACQUIRE(LockSehCache); SehCache = std::move(newcache); } template<size_t _Count> static void getSymAddrName(duint addr, char(& str)[_Count]) { BRIDGE_ADDRINFO addrinfo; if(addr == 0) { memcpy(str, "???", 4); return; } addrinfo.flags = flaglabel | flagmodule; _dbg_addrinfoget(addr, SEG_DEFAULT, &addrinfo); if(addrinfo.module[0] != '\0') _snprintf_s(str, _TRUNCATE, "%s.", addrinfo.module); if(addrinfo.label[0] == '\0') _snprintf_s(addrinfo.label, _TRUNCATE, "%p", addr); strncat_s(str, addrinfo.label, _TRUNCATE); } bool stackcommentget(duint addr, STACK_COMMENT* comment) { SHARED_ACQUIRE(LockSehCache); const auto found = SehCache.find(addr); if(found != SehCache.end()) { *comment = found->second; return true; } SHARED_RELEASE(); duint data = 0; memset(comment, 0, sizeof(STACK_COMMENT)); MemRead(addr, &data, sizeof(duint)); if(!MemIsValidReadPtr(data)) //the stack value is no pointer return false; duint size = 0; duint base = MemFindBaseAddr(data, &size); duint readStart = data - 16 * 4; if(readStart < base) readStart = base; unsigned char disasmData[256]; MemRead(readStart, disasmData, sizeof(disasmData)); duint prev = disasmback(disasmData, 0, sizeof(disasmData), data - readStart, 1); duint previousInstr = readStart + prev; BASIC_INSTRUCTION_INFO basicinfo; bool valid = disasmfast(disasmData + prev, previousInstr, &basicinfo); if(valid && basicinfo.call) //call { char returnToAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(data, returnToAddr); data = basicinfo.addr; char returnFromAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(data, returnFromAddr); _snprintf_s(comment->comment, _TRUNCATE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "return to %s from %s")), returnToAddr, returnFromAddr); strcpy_s(comment->color, "!rtnclr"); // Special token for return address color; return true; } //label char label[MAX_LABEL_SIZE] = ""; BRIDGE_ADDRINFO addrinfo; addrinfo.flags = flaglabel; if(_dbg_addrinfoget(data, SEG_DEFAULT, &addrinfo)) strcpy_s(label, addrinfo.label); char module[MAX_MODULE_SIZE] = ""; ModNameFromAddr(data, module, false); if(*module) //module { if(*label) //+label { sprintf_s(comment->comment, "%s.%s", module, label); } else //module only { //prefer strings over just module.address char string[MAX_STRING_SIZE] = ""; if(DbgGetStringAt(data, string)) { _snprintf_s(comment->comment, _TRUNCATE, "%s.%s", module, string); } else { _snprintf_s(comment->comment, _TRUNCATE, "%s.%p", module, data); } } return true; } else if(*label) //label only { sprintf_s(comment->comment, "<%s>", label); return true; } //string char string[MAX_STRING_SIZE] = ""; if(DbgGetStringAt(data, string)) { strncpy_s(comment->comment, string, _TRUNCATE); return true; } return false; } static BOOL CALLBACK StackReadProcessMemoryProc64(HANDLE hProcess, DWORD64 lpBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead) { // Fix for 64-bit sizes SIZE_T bytesRead = 0; if(MemRead((duint)lpBaseAddress, lpBuffer, nSize, &bytesRead)) { if(lpNumberOfBytesRead) *lpNumberOfBytesRead = (DWORD)bytesRead; return true; } return false; } static PVOID CALLBACK StackSymFunctionTableAccess64(HANDLE hProcess, DWORD64 AddrBase) { #ifdef _WIN64 // https://github.com/dotnet/coreclr/blob/master/src/unwinder/amd64/dbs_stack_x64.cpp MODINFO* info = ModInfoFromAddr(AddrBase); if(info) { return (PVOID)info->findRuntimeFunction(DWORD(AddrBase - info->base)); } else { return nullptr; } #else return SymFunctionTableAccess64(hProcess, AddrBase); #endif // _WIN64 } static DWORD64 CALLBACK StackGetModuleBaseProc64(HANDLE hProcess, DWORD64 Address) { return (DWORD64)ModBaseFromAddr((duint)Address); } static DWORD64 CALLBACK StackTranslateAddressProc64(HANDLE hProcess, HANDLE hThread, LPADDRESS64 lpaddr) { ASSERT_ALWAYS("This function should never be called"); return 0; } void StackEntryFromFrame(CALLSTACKENTRY* Entry, duint Address, duint From, duint To) { Entry->addr = Address; Entry->from = From; Entry->to = To; /* https://github.com/x64dbg/x64dbg/pull/1478 char returnToAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(To, returnToAddr); char returnFromAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(From, returnFromAddr); _snprintf_s(Entry->comment, _TRUNCATE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "return to %s from %s")), returnToAddr, returnFromAddr); */ getSymAddrName(From, Entry->comment); } #define MAX_CALLSTACK_CACHE 20 using CallstackMap = std::unordered_map<duint, std::vector<CALLSTACKENTRY>>; static CallstackMap CallstackCache; void stackupdatecallstack(duint csp) { std::vector<CALLSTACKENTRY> callstack; stackgetcallstack(csp, callstack, false); } static void stackgetsuspectedcallstack(duint csp, std::vector<CALLSTACKENTRY> & callstackVector) { duint size; duint base = MemFindBaseAddr(csp, &size); if(!base) return; duint end = base + size; size = end - csp; Memory<duint*> stackdata(size); MemRead(csp, stackdata(), size); for(duint i = csp; i < end; i += sizeof(duint)) { duint data = stackdata()[(i - csp) / sizeof(duint)]; duint size = 0; duint base = MemFindBaseAddr(data, &size); duint readStart = data - 16 * 4; if(readStart < base) readStart = base; unsigned char disasmData[256]; if(base != 0 && size != 0 && MemRead(readStart, disasmData, sizeof(disasmData))) { duint prev = disasmback(disasmData, 0, sizeof(disasmData), data - readStart, 1); duint previousInstr = readStart + prev; BASIC_INSTRUCTION_INFO basicinfo; bool valid = disasmfast(disasmData + prev, previousInstr, &basicinfo); if(valid && basicinfo.call) { CALLSTACKENTRY stackframe; stackframe.addr = i; stackframe.to = data; char returnToAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(data, returnToAddr); data = basicinfo.addr; char returnFromAddr[MAX_LABEL_SIZE] = ""; getSymAddrName(data, returnFromAddr); _snprintf_s(stackframe.comment, _TRUNCATE, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "return to %s from %s")), returnToAddr, returnFromAddr); stackframe.from = data; callstackVector.push_back(stackframe); } } } } void stackgetcallstack(duint csp, std::vector<CALLSTACKENTRY> & callstackVector, bool cache) { if(cache) { SHARED_ACQUIRE(LockCallstackCache); auto found = CallstackCache.find(csp); if(found != CallstackCache.end()) { callstackVector = found->second; return; } callstackVector.clear(); return; } // Gather context data CONTEXT context; memset(&context, 0, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; if(SuspendThread(hActiveThread) == -1) return; if(!GetThreadContext(hActiveThread, &context)) return; if(ResumeThread(hActiveThread) == -1) return; if(ShowSuspectedCallStack) { stackgetsuspectedcallstack(csp, callstackVector); } else { // Set up all frame data STACKFRAME64 frame; ZeroMemory(&frame, sizeof(STACKFRAME64)); #ifdef _M_IX86 DWORD machineType = IMAGE_FILE_MACHINE_I386; frame.AddrPC.Offset = context.Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = csp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 DWORD machineType = IMAGE_FILE_MACHINE_AMD64; frame.AddrPC.Offset = context.Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Rbp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = csp; frame.AddrStack.Mode = AddrModeFlat; #endif const int MaxWalks = 50; // Container for each callstack entry (50 pre-allocated entries) callstackVector.clear(); callstackVector.reserve(MaxWalks); for(auto i = 0; i < MaxWalks; i++) { if(!SafeStackWalk64( machineType, fdProcessInfo->hProcess, hActiveThread, &frame, &context, StackReadProcessMemoryProc64, StackSymFunctionTableAccess64, StackGetModuleBaseProc64, StackTranslateAddressProc64)) { // Maybe it failed, maybe we have finished walking the stack break; } if(frame.AddrPC.Offset != 0) { // Valid frame CALLSTACKENTRY entry; memset(&entry, 0, sizeof(CALLSTACKENTRY)); StackEntryFromFrame(&entry, (duint)frame.AddrFrame.Offset + sizeof(duint), (duint)frame.AddrPC.Offset, (duint)frame.AddrReturn.Offset); callstackVector.push_back(entry); } else { // Base reached break; } } } EXCLUSIVE_ACQUIRE(LockCallstackCache); if(CallstackCache.size() > MAX_CALLSTACK_CACHE) CallstackCache.clear(); CallstackCache[csp] = callstackVector; } void stackgetcallstackbythread(HANDLE thread, CALLSTACK* callstack) { std::vector<CALLSTACKENTRY> callstackVector; duint csp = GetContextDataEx(thread, UE_CSP); // Gather context data CONTEXT context; memset(&context, 0, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; if(SuspendThread(thread) == -1) return; if(!GetThreadContext(thread, &context)) return; if(ResumeThread(thread) == -1) return; if(ShowSuspectedCallStack) { stackgetsuspectedcallstack(csp, callstackVector); } else { // Set up all frame data STACKFRAME64 frame; ZeroMemory(&frame, sizeof(STACKFRAME64)); #ifdef _M_IX86 DWORD machineType = IMAGE_FILE_MACHINE_I386; frame.AddrPC.Offset = context.Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = csp; frame.AddrStack.Mode = AddrModeFlat; #elif _M_X64 DWORD machineType = IMAGE_FILE_MACHINE_AMD64; frame.AddrPC.Offset = context.Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Rbp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = csp; frame.AddrStack.Mode = AddrModeFlat; #endif const int MaxWalks = 50; // Container for each callstack entry (50 pre-allocated entries) callstackVector.clear(); callstackVector.reserve(MaxWalks); for(auto i = 0; i < MaxWalks; i++) { if(!SafeStackWalk64( machineType, fdProcessInfo->hProcess, thread, &frame, &context, StackReadProcessMemoryProc64, StackSymFunctionTableAccess64, StackGetModuleBaseProc64, StackTranslateAddressProc64)) { // Maybe it failed, maybe we have finished walking the stack break; } if(frame.AddrPC.Offset != 0) { // Valid frame CALLSTACKENTRY entry; memset(&entry, 0, sizeof(CALLSTACKENTRY)); StackEntryFromFrame(&entry, (duint)frame.AddrFrame.Offset + sizeof(duint), (duint)frame.AddrPC.Offset, (duint)frame.AddrReturn.Offset); callstackVector.push_back(entry); } else { // Base reached break; } } } callstack->total = (int)callstackVector.size(); if(callstack->total > 0) { callstack->entries = (CALLSTACKENTRY*)BridgeAlloc(callstack->total * sizeof(CALLSTACKENTRY)); // Copy data directly from the vector memcpy(callstack->entries, callstackVector.data(), callstack->total * sizeof(CALLSTACKENTRY)); } else { callstack->entries = nullptr; } } void stackgetcallstack(duint csp, CALLSTACK* callstack) { std::vector<CALLSTACKENTRY> callstackVector; stackgetcallstack(csp, callstackVector, true); // Convert to a C data structure callstack->total = (int)callstackVector.size(); if(callstack->total > 0) { callstack->entries = (CALLSTACKENTRY*)BridgeAlloc(callstack->total * sizeof(CALLSTACKENTRY)); // Copy data directly from the vector memcpy(callstack->entries, callstackVector.data(), callstack->total * sizeof(CALLSTACKENTRY)); } else { callstack->entries = nullptr; } } void stackupdatesettings() { ShowSuspectedCallStack = settingboolget("Engine", "ShowSuspectedCallStack"); std::vector<CALLSTACKENTRY> dummy; if(hActiveThread) stackgetcallstack(GetContextDataEx(hActiveThread, UE_CSP), dummy, false); }
C/C++
x64dbg-development/src/dbg/stackinfo.h
#ifndef _STACKINFO_H #define _STACKINFO_H #include "_global.h" struct CALLSTACKENTRY { duint addr; duint from; duint to; char comment[MAX_COMMENT_SIZE]; }; struct CALLSTACK { int total; CALLSTACKENTRY* entries; }; void stackupdateseh(); bool stackcommentget(duint addr, STACK_COMMENT* comment); void stackupdatecallstack(duint csp); void stackgetcallstack(duint csp, CALLSTACK* callstack); void stackgetcallstack(duint csp, std::vector<CALLSTACKENTRY> & callstack, bool cache); void stackgetcallstackbythread(HANDLE thread, CALLSTACK* callstack); void stackupdatesettings(); #endif //_STACKINFO_H
C++
x64dbg-development/src/dbg/stringformat.cpp
#include "stringformat.h" #include "value.h" #include "symbolinfo.h" #include "module.h" #include "disasm_fast.h" #include "disasm_helper.h" #include "formatfunctions.h" #include "expressionparser.h" enum class StringValueType { Unknown, Default, // hex or string SignedDecimal, UnsignedDecimal, Hex, Pointer, String, AddrInfo, Module, Instruction, FloatingPointSingle, FloatingPointDouble }; // get an offset of REGDUMP structure, or 0 when the input is not an SSE register. // value: string like "xmm0" // elementSize: 4 or 8 for float and double respectively static size_t getSSERegisterOffset(FormatValueType value, size_t elementSize) { char buf[16]; // a safe buffer with sufficient length to prevent buffer overflow while parsing memset(buf, 0, sizeof(buf)); strcpy_s(buf, value); // copy value into buf _strlwr_s(buf); // convert "XMM" to "xmm" if(buf[1] == 'm' && buf[2] == 'm' && (buf[0] == 'x' || buf[0] == 'y')) // begins with /[xy]mm/ { int index = 0; // the index of XMM/YMM register int bufptr = 0; // where is the character after the XMM register string if(buf[3] >= '0' && buf[3] <= '9' && buf[4] >= '0' && buf[4] <= '9') { index = (buf[3] - '0') * 10 + (buf[4] - '0'); // convert "10" to 10 if(index >= ArchValue(8, 16)) // limit to available XMM registers (32bit: XMM0~XMM7, 64bit: XMM0~XMM15) return 0; bufptr = 5; } else if(buf[3] >= '0' && buf[3] <= '9') { index = buf[3] - '0'; // convert "7" to 7 if(index >= ArchValue(8, 16)) // limit to available XMM registers (32bit: XMM0~XMM7, 64bit: XMM0~XMM15) return 0; bufptr = 4; } else return 0; // return value 0 is EAX which is not an SSE register, and represents in general the input value is not an SSE register. if(buf[bufptr] == '\0') // [xy]mm\d{1,2} return offsetof(REGDUMP, regcontext.XmmRegisters[index]); else if(elementSize == 8 && buf[0] == 'x' && buf[bufptr] == 'h' && buf[bufptr + 1] == '\0') // xmm\d{1,2}h return offsetof(REGDUMP, regcontext.XmmRegisters[index].High); else if(buf[bufptr] == '[') { if(buf[bufptr + 1] >= '0' && buf[bufptr + 1] <= '9' && buf[bufptr + 2] == ']' && buf[bufptr + 3] == '\0') // [xy]mm\d{1,2}\[\d\] { size_t item = buf[bufptr + 1] - '0'; if(buf[0] == 'x' && item >= 0 && item < 16 / elementSize) // xmm return offsetof(REGDUMP, regcontext.XmmRegisters[index]) + item * elementSize; else if(buf[0] == 'y' && item >= 0 && item < 32 / elementSize) // ymm return offsetof(REGDUMP, regcontext.YmmRegisters[index]) + item * elementSize; else return 0; } else return 0; } else return 0; } else return 0; // TO DO: ST(...) } template<class T> String printFloatValue(FormatValueType value) { static_assert(std::is_same<T, double>::value || std::is_same<T, float>::value, "This function is used to print float and double values."); size_t offset = getSSERegisterOffset(value, sizeof(T)); REGDUMP registers; T data; if(offset != 0) // prints an FPU register { assert((offset + sizeof(T)) <= sizeof(REGDUMP)); if(DbgGetRegDumpEx(&registers, sizeof(registers))) data = *(T*)((char*)&registers + offset); else return "???"; } else // prints a memory pointer { duint valuint = 0; if(!(valfromstring(value, &valuint) && DbgMemRead(valuint, &data, sizeof(data)))) return "???"; } std::stringstream wFloatingStr; wFloatingStr << std::setprecision(std::numeric_limits<T>::digits10) << data; return wFloatingStr.str(); } static String printValue(FormatValueType value, StringValueType type) { char string[MAX_STRING_SIZE] = ""; if(type == StringValueType::FloatingPointDouble) { return printFloatValue<double>(value); } else if(type == StringValueType::FloatingPointSingle) { return printFloatValue<float>(value); } else { ExpressionParser parser(value); ExpressionParser::EvalValue evalue(0); if(!parser.Calculate(evalue, valuesignedcalc(), false)) return "???"; if(type == StringValueType::Default && evalue.isString) return evalue.data; duint valuint = 0; if(evalue.isString || !evalue.DoEvaluate(valuint)) return "???"; switch(type) { #ifdef _WIN64 case StringValueType::SignedDecimal: return StringUtils::sprintf("%lld", valuint); case StringValueType::UnsignedDecimal: return StringUtils::sprintf("%llu", valuint); case StringValueType::Default: case StringValueType::Hex: return StringUtils::sprintf("%llX", valuint); #else //x86 case StringValueType::SignedDecimal: return StringUtils::sprintf("%d", valuint); case StringValueType::UnsignedDecimal: return StringUtils::sprintf("%u", valuint); case StringValueType::Default: case StringValueType::Hex: return StringUtils::sprintf("%X", valuint); #endif //_WIN64 case StringValueType::Pointer: return StringUtils::sprintf("%p", valuint); case StringValueType::String: if(disasmgetstringatwrapper(valuint, string, false)) return string; break; case StringValueType::AddrInfo: { auto symbolic = SymGetSymbolicName(valuint); if(disasmgetstringatwrapper(valuint, string, false)) return symbolic + " " + string; else return symbolic; } break; case StringValueType::Module: ModNameFromAddr(valuint, string, true); return string; case StringValueType::Instruction: { BASIC_INSTRUCTION_INFO info; if(disasmfast(valuint, &info, true)) return info.instruction; } break; default: break; } } return "???"; } static bool typeFromCh(char ch, StringValueType & type) { switch(ch) { case 'd': type = StringValueType::SignedDecimal; break; case 'u': type = StringValueType::UnsignedDecimal; break; case 'p': type = StringValueType::Pointer; break; case 's': type = StringValueType::String; break; case 'x': type = StringValueType::Hex; break; case 'a': type = StringValueType::AddrInfo; break; case 'm': type = StringValueType::Module; break; case 'i': type = StringValueType::Instruction; break; case 'f': type = StringValueType::FloatingPointSingle; break; case 'F': type = StringValueType::FloatingPointDouble; break; default: //invalid format return false; } return true; } static const char* getArgExpressionType(const String & formatString, StringValueType & type, String & complexArgs) { size_t toSkip = 0; type = StringValueType::Default; complexArgs.clear(); if(formatString.size() > 2 && !isdigit(formatString[0]) && formatString[1] == ':') //simple type { if(!typeFromCh(formatString[0], type)) return nullptr; toSkip = 2; //skip '?:' } else if(formatString.size() > 2 && formatString.find('@') != String::npos) //complex type { for(; toSkip < formatString.length(); toSkip++) if(formatString[toSkip] == '@') { toSkip++; break; } complexArgs = formatString.substr(0, toSkip - 1); if(complexArgs.length() == 1 && typeFromCh(complexArgs[0], type)) complexArgs.clear(); } return formatString.c_str() + toSkip; } static unsigned int getArgNumType(const String & formatString, StringValueType & type) { String complexArgs; auto expression = getArgExpressionType(formatString, type, complexArgs); unsigned int argnum = 0; if(!expression || sscanf_s(expression, "%u", &argnum) != 1) type = StringValueType::Unknown; return argnum; } static String handleFormatString(const String & formatString, const FormatValueVector & values) { auto type = StringValueType::Unknown; auto argnum = getArgNumType(formatString, type); if(type != StringValueType::Unknown && argnum < values.size()) return printValue(values.at(argnum), type); return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "[Formatting Error]")); } String stringformat(String format, const FormatValueVector & values) { int len = (int)format.length(); String output; String formatString; bool inFormatter = false; for(int i = 0; i < len; i++) { //handle escaped format sequences "{{" and "}}" if(format[i] == '{' && (i + 1 < len && format[i + 1] == '{')) { output += "{"; i++; continue; } if(format[i] == '}' && (i + 1 < len && format[i + 1] == '}')) { output += "}"; i++; continue; } //handle actual formatting if(format[i] == '{' && !inFormatter) //opening bracket { inFormatter = true; formatString.clear(); } else if(format[i] == '}' && inFormatter) //closing bracket { inFormatter = false; if(formatString.length()) { output += handleFormatString(formatString, values); formatString.clear(); } } else if(inFormatter) //inside brackets formatString += format[i]; else //outside brackets output += format[i]; } if(inFormatter && formatString.size()) output += handleFormatString(formatString, values); else if(inFormatter) output += "{"; return output; } static String printComplexValue(FormatValueType value, const String & complexArgs) { auto split = StringUtils::Split(complexArgs, ';'); duint valuint; if(!split.empty() && valfromstring(value, &valuint)) { std::vector<char> dest; if(FormatFunctions::Call(dest, split[0], split, valuint)) return String(dest.data()); } return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "[Formatting Error]")); } static String handleFormatStringInline(const String & formatString) { auto type = StringValueType::Unknown; String complexArgs; auto value = getArgExpressionType(formatString, type, complexArgs); if(!complexArgs.empty()) return printComplexValue(value, complexArgs); else if(value && *value) return printValue(value, type); return GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "[Formatting Error]")); } String stringformatinline(String format) { int len = (int)format.length(); String output; String formatString; bool inFormatter = false; for(int i = 0; i < len; i++) { //handle escaped format sequences "{{" and "}}" if(format[i] == '{' && (i + 1 < len && format[i + 1] == '{')) { output += "{"; i++; continue; } if(format[i] == '}' && (i + 1 < len && format[i + 1] == '}')) { output += "}"; i++; continue; } //handle actual formatting if(format[i] == '{' && !inFormatter) //opening bracket { inFormatter = true; formatString.clear(); } else if(format[i] == '}' && inFormatter) //closing bracket { inFormatter = false; if(formatString.length()) { output += handleFormatStringInline(formatString); formatString.clear(); } } else if(inFormatter) //inside brackets formatString += format[i]; else //outside brackets output += format[i]; } if(inFormatter && formatString.size()) output += handleFormatStringInline(formatString); else if(inFormatter) output += "{"; return output; }
C/C++
x64dbg-development/src/dbg/stringformat.h
#ifndef _STRINGFORMAT_H #define _STRINGFORMAT_H #include "_global.h" typedef const char* FormatValueType; typedef std::vector<FormatValueType> FormatValueVector; String stringformat(String format, const FormatValueVector & values); String stringformatinline(String format); #endif //_STRINGFORMAT_H
C++
x64dbg-development/src/dbg/stringutils.cpp
#include "stringutils.h" #include <windows.h> #include <cstdint> static inline bool convertLongLongNumber(const char* str, unsigned long long & result, int radix) { errno = 0; char* end; result = strtoull(str, &end, radix); if(!result && end == str) return false; if(result == ULLONG_MAX && errno) return false; if(*end) return false; return true; } static inline bool convertNumber(const char* str, size_t & result, int radix) { unsigned long long llr; if(!convertLongLongNumber(str, llr, radix)) return false; result = size_t(llr); return true; } void StringUtils::Split(const String & s, char delim, std::vector<String> & elems) { elems.clear(); String item; item.reserve(s.length()); for(size_t i = 0; i < s.length(); i++) { if(s[i] == delim) { if(!item.empty()) elems.push_back(item); item.clear(); } else item.push_back(s[i]); } if(!item.empty()) elems.push_back(std::move(item)); } StringList StringUtils::Split(const String & s, char delim) { std::vector<String> elems; Split(s, delim, elems); return elems; } //https://github.com/lefticus/presentations/blob/master/PracticalPerformancePractices.md#smaller-code-is-faster-code-11 String StringUtils::Escape(unsigned char ch, bool escapeSafe) { char buf[8] = ""; switch(ch) { case '\0': return "\\0"; case '\t': return escapeSafe ? "\\t" : "\t"; case '\f': return "\\f"; case '\v': return "\\v"; case '\n': return escapeSafe ? "\\n" : "\n"; case '\r': return escapeSafe ? "\\r" : "\r"; case '\\': return escapeSafe ? "\\\\" : "\\"; case '\"': return escapeSafe ? "\\\"" : "\""; case '\a': return "\\a"; case '\b': return "\\b"; default: if(!isprint(ch)) //unknown unprintable character sprintf_s(buf, "\\x%02X", ch); else *buf = ch; return buf; } } static int IsValidUTF8Char(const char* data, int size) { if(*(unsigned char*)data >= 0xF8) //5 or 6 bytes return 0; else if(*(unsigned char*)data >= 0xF0) //4 bytes { if(size < 4) return 0; for(int i = 1; i <= 3; i++) { if((*(unsigned char*)(data + i) & 0xC0) != 0x80) return 0; } return 4; } else if(*(unsigned char*)data >= 0xE0) //3 bytes { if(size < 3) return 0; for(int i = 1; i <= 2; i++) { if((*(unsigned char*)(data + i) & 0xC0) != 0x80) return 0; } return 3; } else if(*(unsigned char*)data >= 0xC0) //2 bytes { if(size < 2) return 0; if((*(unsigned char*)(data + 1) & 0xC0) != 0x80) return 0; return 2; } else if(*(unsigned char*)data >= 0x80) // BAD return 0; else return 1; } String StringUtils::Escape(const String & s, bool escapeSafe) { std::string escaped; escaped.reserve(s.length() + s.length() / 2); for(size_t i = 0; i < s.length(); i++) { char buf[8]; memset(buf, 0, sizeof(buf)); unsigned char ch = (unsigned char)s[i]; switch(ch) { case '\0': memcpy(buf, "\\0", 2); break; case '\t': if(escapeSafe) memcpy(buf, "\\t", 2); else memcpy(buf, &ch, 1); break; case '\f': memcpy(buf, "\\f", 2); break; case '\v': memcpy(buf, "\\v", 2); break; case '\n': if(escapeSafe) memcpy(buf, "\\n", 2); else memcpy(buf, &ch, 1); break; case '\r': if(escapeSafe) memcpy(buf, "\\r", 2); else memcpy(buf, &ch, 1); break; case '\\': if(escapeSafe) memcpy(buf, "\\\\", 2); else memcpy(buf, &ch, 1); break; case '\"': if(escapeSafe) memcpy(buf, "\\\"", 2); else memcpy(buf, &ch, 1); break; default: int UTF8CharSize; if(ch >= 0x80 && (UTF8CharSize = IsValidUTF8Char(s.c_str() + i, int(s.length() - i))) != 0) //UTF-8 Character is emitted directly { memcpy(buf, s.c_str() + i, UTF8CharSize); i += UTF8CharSize - 1; } else if(!isprint(ch)) //unknown unprintable character sprintf_s(buf, "\\x%02X", ch); else *buf = ch; } escaped.append(buf); } return escaped; } bool StringUtils::Unescape(const String & s, String & result, bool quoted) { int mLastChar = EOF; size_t i = 0; auto nextChar = [&]() { if(i == s.length()) return mLastChar = EOF; return mLastChar = s[i++]; }; if(quoted) { nextChar(); if(mLastChar != '\"') //start of quoted string literal return false; //invalid string literal } result.reserve(s.length()); while(true) { nextChar(); if(mLastChar == EOF) //end of file { if(!quoted) break; return false; //unexpected end of file in string literal (1) } if(mLastChar == '\r' || mLastChar == '\n') return false; //unexpected newline in string literal (1) if(quoted && mLastChar == '\"') //end of quoted string literal break; if(mLastChar == '\\') //escape sequence { nextChar(); if(mLastChar == EOF) return false; //unexpected end of file in string literal (2) if(mLastChar == '\r' || mLastChar == '\n') return false; //unexpected newline in string literal (2) if(mLastChar == '\'' || mLastChar == '\"' || mLastChar == '?' || mLastChar == '\\') mLastChar = mLastChar; else if(mLastChar == 'a') mLastChar = '\a'; else if(mLastChar == 'b') mLastChar = '\b'; else if(mLastChar == 'f') mLastChar = '\f'; else if(mLastChar == 'n') mLastChar = '\n'; else if(mLastChar == 'r') mLastChar = '\r'; else if(mLastChar == 't') mLastChar = '\t'; else if(mLastChar == 'v') mLastChar = '\v'; else if(mLastChar == '0') mLastChar = '\0'; else if(mLastChar == 'x') //\xHH { auto ch1 = nextChar(); auto ch2 = nextChar(); if(isxdigit(ch1) && isxdigit(ch2)) { char byteStr[3] = ""; byteStr[0] = ch1; byteStr[1] = ch2; uint64_t hexData; auto error = convertLongLongNumber(byteStr, hexData, 16); if(error) return false; //convertNumber failed (%s) for hex sequence \"\\x%c%c\" in string literal mLastChar = hexData & 0xFF; } else return false; //invalid hex sequence \"\\x%c%c\" in string literal } else return false; //invalid escape sequence \"\\%c\" in string literal } result.push_back(mLastChar); } return true; } //Trim functions taken from: https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/16743707#16743707 const String StringUtils::WHITESPACE = " \n\r\t"; String StringUtils::Trim(const String & s, const String & delim) { return TrimRight(TrimLeft(s, delim), delim); } String StringUtils::TrimLeft(const String & s, const String & delim) { size_t startpos = s.find_first_not_of(delim); return (startpos == String::npos) ? "" : s.substr(startpos); } String StringUtils::TrimRight(const String & s, const String & delim) { size_t endpos = s.find_last_not_of(delim); return (endpos == String::npos) ? "" : s.substr(0, endpos + 1); } String StringUtils::PadLeft(const String & s, size_t minLength, char ch) { if(s.length() >= minLength) return s; String pad; pad.resize(minLength - s.length()); for(size_t i = 0; i < pad.length(); i++) pad[i] = ch; return pad + s; } //Conversion functions taken from: http://www.nubaria.com/en/blog/?p=289 String StringUtils::Utf16ToUtf8(const WString & wstr) { return Utf16ToUtf8(wstr.c_str()); } String StringUtils::Utf16ToUtf8(const wchar_t* wstr) { String convertedString; if(!wstr || !*wstr) return convertedString; auto requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr); if(requiredSize > 0) { convertedString.resize(requiredSize - 1); if(!WideCharToMultiByte(CP_UTF8, 0, wstr, -1, (char*)convertedString.c_str(), requiredSize, nullptr, nullptr)) convertedString.clear(); } return convertedString; } WString StringUtils::Utf8ToUtf16(const String & str) { return Utf8ToUtf16(str.c_str()); } WString StringUtils::Utf8ToUtf16(const char* str) { WString convertedString; if(!str || !*str) return convertedString; int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0); if(requiredSize > 0) { convertedString.resize(requiredSize - 1); if(!MultiByteToWideChar(CP_UTF8, 0, str, -1, (wchar_t*)convertedString.c_str(), requiredSize)) convertedString.clear(); } return convertedString; } String StringUtils::LocalCpToUtf8(const String & str) { return LocalCpToUtf8(str.c_str()); } String StringUtils::LocalCpToUtf8(const char* str) { return Utf16ToUtf8(LocalCpToUtf16(str).c_str()); } WString StringUtils::LocalCpToUtf16(const String & str) { return LocalCpToUtf16(str.c_str()); } WString StringUtils::LocalCpToUtf16(const char* str) { WString convertedString; if(!str || !*str) return convertedString; int requiredSize = MultiByteToWideChar(CP_ACP, 0, str, -1, nullptr, 0); if(requiredSize > 0) { convertedString.resize(requiredSize - 1); if(!MultiByteToWideChar(CP_ACP, 0, str, -1, (wchar_t*)convertedString.c_str(), requiredSize)) convertedString.clear(); } return convertedString; } String StringUtils::Utf16ToLocalCp(const WString & str) { String convertedString; if(str.size() == 0) return convertedString; int requiredSize = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr); if(requiredSize > 0) { convertedString.resize(requiredSize - 1); if(!WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, (char*)convertedString.c_str(), requiredSize, nullptr, nullptr)) convertedString.clear(); } return convertedString; } //Taken from: https://stackoverflow.com/a/24315631 void StringUtils::ReplaceAll(String & s, const String & from, const String & to) { size_t start_pos = 0; while((start_pos = s.find(from, start_pos)) != std::string::npos) { s.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } } void StringUtils::ReplaceAll(WString & s, const WString & from, const WString & to) { size_t start_pos = 0; while((start_pos = s.find(from, start_pos)) != std::string::npos) { s.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } } String StringUtils::vsprintf(_In_z_ _Printf_format_string_ const char* format, va_list args) { char sbuffer[64] = ""; if(_vsnprintf_s(sbuffer, _TRUNCATE, format, args) != -1) return sbuffer; std::vector<char> buffer(256, '\0'); while(true) { int res = _vsnprintf_s(buffer.data(), buffer.size(), _TRUNCATE, format, args); if(res == -1) { buffer.resize(buffer.size() * 2); continue; } else break; } return String(buffer.data()); } String StringUtils::sprintf(_In_z_ _Printf_format_string_ const char* format, ...) { va_list args; va_start(args, format); auto result = vsprintf(format, args); va_end(args); return result; } WString StringUtils::vsprintf(_In_z_ _Printf_format_string_ const wchar_t* format, va_list args) { wchar_t sbuffer[64] = L""; if(_vsnwprintf_s(sbuffer, _TRUNCATE, format, args) != -1) return sbuffer; std::vector<wchar_t> buffer(256, L'\0'); while(true) { int res = _vsnwprintf_s(buffer.data(), buffer.size(), _TRUNCATE, format, args); if(res == -1) { buffer.resize(buffer.size() * 2); continue; } else break; } return WString(buffer.data()); } WString StringUtils::sprintf(_In_z_ _Printf_format_string_ const wchar_t* format, ...) { va_list args; va_start(args, format); auto result = vsprintf(format, args); va_end(args); return result; } String StringUtils::ToLower(const String & s) { auto result = s; for(size_t i = 0; i < result.size(); i++) result[i] = tolower(result[i]); return result; } bool StringUtils::StartsWith(const String & str, const String & prefix) { return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix); } bool StringUtils::EndsWith(const String & str, const String & suffix) { return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix); } static int hex2int(char ch) { if(ch >= '0' && ch <= '9') return ch - '0'; if(ch >= 'A' && ch <= 'F') return ch - 'A' + 10; if(ch >= 'a' && ch <= 'f') return ch - 'a' + 10; return -1; } bool StringUtils::FromHex(const String & text, std::vector<unsigned char> & data, bool reverse) { auto size = text.size(); if(size % 2) return false; data.resize(size / 2); for(size_t i = 0, j = 0; i < size; i += 2, j++) { auto high = hex2int(text[i]); auto low = hex2int(text[i + 1]); if(high == -1 || low == -1) return false; data[reverse ? data.size() - j - 1 : j] = (high << 4) | low; } return true; } String StringUtils::ToHex(unsigned long long value) { char buf[32]; sprintf_s(buf, "%llX", value); return buf; } #define HEXLOOKUP "0123456789ABCDEF" String StringUtils::ToHex(const unsigned char* buffer, size_t size, bool reverse) { String result; result.resize(size * 2); for(size_t i = 0, j = 0; i < size; i++, j += 2) { auto ch = buffer[reverse ? size - i - 1 : i]; result[j] = HEXLOOKUP[(ch >> 4) & 0xF]; result[j + 1] = HEXLOOKUP[ch & 0xF]; } return result; } String StringUtils::ToCompressedHex(const unsigned char* buffer, size_t size) { if(!size) return ""; String result; result.reserve(size * 2); for(size_t i = 0; i < size;) { size_t repeat = 0; auto lastCh = buffer[i]; result.push_back(HEXLOOKUP[(lastCh >> 4) & 0xF]); result.push_back(HEXLOOKUP[lastCh & 0xF]); for(; i < size && buffer[i] == lastCh; i++) repeat++; if(repeat == 2) { result.push_back(HEXLOOKUP[(lastCh >> 4) & 0xF]); result.push_back(HEXLOOKUP[lastCh & 0xF]); } else if(repeat > 2) #ifdef _WIN64 result.append(StringUtils::sprintf("{%llX}", repeat)); #else //x86 result.append(StringUtils::sprintf("{%X}", repeat)); #endif //_WIN64 } return result; } bool StringUtils::FromCompressedHex(const String & text, std::vector<unsigned char> & data) { auto size = text.size(); if(size < 2) return false; data.clear(); data.reserve(size); //TODO: better initial estimate String repeatStr; for(size_t i = 0; i < size;) { if(isspace(text[i])) //skip whitespace { i++; continue; } auto high = hex2int(text[i++]); //eat high nibble if(i >= size) //not enough data return false; auto low = hex2int(text[i++]); //eat low nibble if(high == -1 || low == -1) //invalid character return false; auto lastCh = (high << 4) | low; data.push_back(lastCh); if(i >= size) //end of buffer break; if(text[i] == '{') { repeatStr.clear(); i++; //eat '{' while(text[i] != '}') { repeatStr.push_back(text[i++]); //eat character if(i >= size) //unexpected end of buffer (missing '}') return false; } i++; //eat '}' size_t repeat = 0; if(!convertNumber(repeatStr.c_str(), repeat, 16) || !repeat) //conversion failed or repeat zero times return false; for(size_t j = 1; j < repeat; j++) data.push_back(lastCh); } } return true; } int StringUtils::hackicmp(const char* s1, const char* s2) { unsigned char c1, c2; while((c1 = *s1++) == (c2 = *s2++)) if(c1 == '\0') return 0; s1--, s2--; while((c1 = tolower(*s1++)) == (c2 = tolower(*s2++))) if(c1 == '\0') return 0; return c1 - c2; }
C/C++
x64dbg-development/src/dbg/stringutils.h
#ifndef _STRINGUTILS_H #define _STRINGUTILS_H #include <string> #include <vector> #include <sstream> #include <iomanip> typedef std::string String; typedef std::wstring WString; typedef std::vector<String> StringList; typedef std::vector<WString> WStringList; class StringUtils { public: static void Split(const String & s, char delim, std::vector<String> & elems); static StringList Split(const String & s, char delim); static String Escape(unsigned char ch, bool escapeSafe = true); static String Escape(const String & s, bool escapeSafe = true); static bool Unescape(const String & s, String & result, bool quoted = true); static String Trim(const String & s, const String & delim = StringUtils::WHITESPACE); static String TrimLeft(const String & s, const String & delim = StringUtils::WHITESPACE); static String TrimRight(const String & s, const String & delim = StringUtils::WHITESPACE); static String PadLeft(const String & s, size_t minLength, char ch); static String Utf16ToUtf8(const WString & wstr); static String Utf16ToUtf8(const wchar_t* wstr); static String Utf16ToLocalCp(const WString & wstr); static WString Utf8ToUtf16(const String & str); static WString Utf8ToUtf16(const char* str); static String LocalCpToUtf8(const String & str); static String LocalCpToUtf8(const char* str); static WString LocalCpToUtf16(const String & wstr); static WString LocalCpToUtf16(const char* wstr); static void ReplaceAll(String & s, const String & from, const String & to); static void ReplaceAll(WString & s, const WString & from, const WString & to); static String vsprintf(_In_z_ _Printf_format_string_ const char* format, va_list args); static String sprintf(_In_z_ _Printf_format_string_ const char* format, ...); static WString vsprintf(_In_z_ _Printf_format_string_ const wchar_t* format, va_list args); static WString sprintf(_In_z_ _Printf_format_string_ const wchar_t* format, ...); static String ToLower(const String & s); static bool StartsWith(const String & str, const String & prefix); static bool EndsWith(const String & str, const String & suffix); static bool FromHex(const String & text, std::vector<unsigned char> & data, bool reverse = false); static String ToHex(unsigned long long value); static String ToHex(const unsigned char* buffer, size_t size, bool reverse = false); static String ToCompressedHex(const unsigned char* buffer, size_t size); static bool FromCompressedHex(const String & text, std::vector<unsigned char> & data); static int hackicmp(const char* s1, const char* s2); template<typename T> static String ToFloatingString(void* buffer) { auto value = *(T*)buffer; std::stringstream wFloatingStr; wFloatingStr << std::setprecision(std::numeric_limits<T>::digits10) << value; return wFloatingStr.str(); } template<typename T> static String ToIntegralString(void* buffer) { auto value = *(T*)buffer; return ToHex(value); } private: static const String WHITESPACE; }; #endif //_STRINGUTILS_H
C++
x64dbg-development/src/dbg/symbolinfo.cpp
/** @file symbolinfo.cpp @brief Implements the symbolinfo class. */ #include "symbolinfo.h" #include "debugger.h" #include "console.h" #include "module.h" #include "addrinfo.h" #include "dbghelp_safe.h" #include "exception.h" #include "ntdll/ntdll.h" #include "WinInet-Downloader/downslib.h" #include <shlwapi.h> duint symbolDownloadingBase = 0; struct SYMBOLCBDATA { CBSYMBOLENUM cbSymbolEnum; void* user = nullptr; }; bool SymEnum(duint Base, CBSYMBOLENUM EnumCallback, void* UserData, duint BeginRva, duint EndRva, unsigned int SymbolMask) { SYMBOLCBDATA cbData; cbData.cbSymbolEnum = EnumCallback; cbData.user = UserData; SHARED_ACQUIRE(LockModules); MODINFO* modInfo = ModInfoFromAddr(Base); if(modInfo == nullptr) return false; if(SymbolMask & SYMBOL_MASK_SYMBOL && modInfo->symbols->isOpen()) { modInfo->symbols->enumSymbols([&cbData, Base](const SymbolInfo & info) { SYMBOLPTR symbolptr; symbolptr.modbase = Base; symbolptr.symbol = &info; return cbData.cbSymbolEnum(&symbolptr, cbData.user); }, BeginRva, EndRva); } if(SymbolMask & SYMBOL_MASK_EXPORT) { auto entry = &modInfo->entrySymbol; // There is a pseudo-export for the entry point function auto emitEntryExport = [&]() { if(modInfo->entry != 0 && entry->rva >= BeginRva && entry->rva <= EndRva) { SYMBOLPTR symbolptr; symbolptr.modbase = Base; symbolptr.symbol = entry; entry = nullptr; return cbData.cbSymbolEnum(&symbolptr, cbData.user); } entry = nullptr; return true; }; if(!modInfo->exportsByRva.empty()) { auto it = modInfo->exportsByRva.begin(); if(BeginRva > modInfo->exports[*it].rva) { it = std::lower_bound(modInfo->exportsByRva.begin(), modInfo->exportsByRva.end(), BeginRva, [&modInfo](size_t index, duint rva) { return modInfo->exports[index].rva < rva; }); } if(it != modInfo->exportsByRva.end()) { for(; it != modInfo->exportsByRva.end(); it++) { const auto & symbol = modInfo->exports[*it]; if(symbol.rva > EndRva) break; // This is only executed if there is another export after the entry if(entry != nullptr && symbol.rva >= entry->rva) { if(!emitEntryExport()) return true; } SYMBOLPTR symbolptr; symbolptr.modbase = Base; symbolptr.symbol = &symbol; if(!cbData.cbSymbolEnum(&symbolptr, cbData.user)) return true; } // This is executed if the entry is the last 'export' if(entry != nullptr) { emitEntryExport(); } } else { // This is executed if there are exports, but the range doesn't include any real ones emitEntryExport(); } } else { // This is executed if there are no exports emitEntryExport(); } } if(SymbolMask & SYMBOL_MASK_IMPORT && !modInfo->importsByRva.empty()) { auto it = modInfo->importsByRva.begin(); if(BeginRva > modInfo->imports[*it].iatRva) { it = std::lower_bound(modInfo->importsByRva.begin(), modInfo->importsByRva.end(), BeginRva, [&modInfo](size_t index, duint rva) { return modInfo->imports[index].iatRva < rva; }); } if(it != modInfo->importsByRva.end()) { for(; it != modInfo->importsByRva.end(); it++) { const auto & symbol = modInfo->imports[*it]; if(symbol.iatRva > EndRva) break; SYMBOLPTR symbolptr; symbolptr.modbase = Base; symbolptr.symbol = &symbol; if(!cbData.cbSymbolEnum(&symbolptr, cbData.user)) return true; } } } return true; } bool SymGetModuleList(std::vector<SYMBOLMODULEINFO>* List) { ModEnum([List](const MODINFO & mod) { SYMBOLMODULEINFO curMod; curMod.base = mod.base; strcpy_s(curMod.name, mod.name); strcat_s(curMod.name, mod.extension); List->push_back(curMod); }); return true; } void SymUpdateModuleList() { // Build the vector of modules std::vector<SYMBOLMODULEINFO> modList; if(!SymGetModuleList(&modList)) { GuiSymbolUpdateModuleList(0, nullptr); return; } // Create a new array to be sent to the GUI thread size_t moduleCount = modList.size(); SYMBOLMODULEINFO* data = (SYMBOLMODULEINFO*)BridgeAlloc(moduleCount * sizeof(SYMBOLMODULEINFO)); // Direct copy from std::vector data memcpy(data, modList.data(), moduleCount * sizeof(SYMBOLMODULEINFO)); // Send the module data to the GUI for updating GuiSymbolUpdateModuleList((int)moduleCount, data); } static void SymSetProgress(int percentage, const char* pdbBaseFile) { if(percentage == 0) GuiAddStatusBarMessage(StringUtils::sprintf("%s\n", pdbBaseFile).c_str()); else GuiAddStatusBarMessage(StringUtils::sprintf("%s %d%%\n", pdbBaseFile, percentage).c_str()); GuiSymbolSetProgress(percentage); } bool SymDownloadSymbol(duint Base, const char* SymbolStore) { struct DownloadBaseGuard { DownloadBaseGuard(duint downloadBase) { symbolDownloadingBase = downloadBase; GuiRepaintTableView(); } ~DownloadBaseGuard() { symbolDownloadingBase = 0; GuiRepaintTableView(); } } g(Base); #define symprintf(format, ...) GuiSymbolLogAdd(StringUtils::sprintf(GuiTranslateText(format), __VA_ARGS__).c_str()) // Default to Microsoft's symbol server if(!SymbolStore) SymbolStore = "https://msdl.microsoft.com/download/symbols"; String pdbSignature, pdbFile; { SHARED_ACQUIRE(LockModules); auto info = ModInfoFromAddr(Base); if(!info) { symprintf(QT_TRANSLATE_NOOP("DBG", "Module not found...\n")); return false; } pdbSignature = info->pdbSignature; pdbFile = info->pdbFile; } if(pdbSignature.empty() || pdbFile.empty()) // TODO: allow using module filename instead of pdbFile ? { symprintf(QT_TRANSLATE_NOOP("DBG", "Module has no symbol information...\n")); return false; } auto found = strrchr(pdbFile.c_str(), '\\'); auto pdbBaseFile = found ? found + 1 : pdbFile.c_str(); // TODO: strict checks if this path is absolute WString symbolPath(StringUtils::Utf8ToUtf16(szSymbolCachePath)); if(symbolPath.empty()) { symprintf(QT_TRANSLATE_NOOP("DBG", "No symbol path specified...\n")); return false; } CreateDirectoryW(symbolPath.c_str(), nullptr); if(symbolPath.back() != L'\\') symbolPath += L'\\'; symbolPath += StringUtils::Utf8ToUtf16(pdbBaseFile); CreateDirectoryW(symbolPath.c_str(), nullptr); symbolPath += L'\\'; symbolPath += StringUtils::Utf8ToUtf16(pdbSignature); CreateDirectoryW(symbolPath.c_str(), nullptr); symbolPath += '\\'; symbolPath += StringUtils::Utf8ToUtf16(pdbBaseFile); auto szSymbolPath = StringUtils::Utf16ToUtf8(symbolPath); // Try to load the symbol file directly if it exists locally if(FileExists(szSymbolPath.c_str())) { { EXCLUSIVE_ACQUIRE(LockModules); auto info = ModInfoFromAddr(Base); if(info && info->loadSymbols(szSymbolPath, bForceLoadSymbols)) return true; } // Load failed. If the file is empty, we just delete it and retry the download. Otherwise, bail auto hFile = CreateFileW(symbolPath.c_str(), FILE_READ_ATTRIBUTES | DELETE, 0, nullptr, OPEN_EXISTING, 0, nullptr); bool deleted = false; if(hFile != INVALID_HANDLE_VALUE) { LARGE_INTEGER fileSize; if(GetFileSizeEx(hFile, &fileSize) && fileSize.QuadPart == 0) { IO_STATUS_BLOCK iosb; FILE_DISPOSITION_INFORMATION dispositionInfo; dispositionInfo.DeleteFile = TRUE; deleted = NT_SUCCESS(NtSetInformationFile(hFile, &iosb, &dispositionInfo, sizeof(dispositionInfo), FileDispositionInformation)); // use NT API for XP } CloseHandle(hFile); } if(!deleted) { symprintf(QT_TRANSLATE_NOOP("DBG", "Symbol file '%s' exists but could not be loaded!\n"), szSymbolPath.c_str()); return false; } } String symbolUrl(SymbolStore); if(symbolUrl.empty()) { symprintf(QT_TRANSLATE_NOOP("DBG", "No symbol store URL specified...\n")); return false; } if(symbolUrl.back() != '/') symbolUrl += '/'; symbolUrl += StringUtils::sprintf("%s/%s/%s", pdbBaseFile, pdbSignature.c_str(), pdbBaseFile); symprintf(QT_TRANSLATE_NOOP("DBG", "Downloading symbol %s\n Signature: %s\n Destination: %s\n URL: %s\n"), pdbBaseFile, pdbSignature.c_str(), StringUtils::Utf16ToUtf8(symbolPath).c_str(), symbolUrl.c_str()); DWORD lineDownloadStart = GetTickCount(); auto result = downslib_download(symbolUrl.c_str(), symbolPath.c_str(), "x64dbg", 1000, [](void* userdata, unsigned long long read_bytes, unsigned long long total_bytes) { if(total_bytes) { auto progress = (double)read_bytes / (double)total_bytes; SymSetProgress((int)(progress * 100.0), (const char*)userdata); } return true; }, (void*)pdbBaseFile); SymSetProgress(0, pdbBaseFile); switch(result) { case downslib_error::ok: break; case downslib_error::createfile: //TODO: handle ERROR_SHARING_VIOLATION (unload symbols and try again) symprintf(QT_TRANSLATE_NOOP("DBG", "Failed to create destination file (%s)...\n"), ErrorCodeToName(GetLastError()).c_str()); return false; case downslib_error::inetopen: symprintf(QT_TRANSLATE_NOOP("DBG", "InternetOpen failed (%s)...\n"), ErrorCodeToName(GetLastError()).c_str()); return false; case downslib_error::openurl: symprintf(QT_TRANSLATE_NOOP("DBG", "InternetOpenUrl failed (%s)...\n"), ErrorCodeToName(GetLastError()).c_str()); return false; case downslib_error::statuscode: symprintf(QT_TRANSLATE_NOOP("DBG", "Connection succeeded, but download failed (status code: %d)...\n"), GetLastError()); return false; case downslib_error::cancel: symprintf(QT_TRANSLATE_NOOP("DBG", "Download interrupted...\n"), ErrorCodeToName(GetLastError()).c_str()); return false; case downslib_error::incomplete: symprintf(QT_TRANSLATE_NOOP("DBG", "Download incomplete...\n"), ErrorCodeToName(GetLastError()).c_str()); return false; default: __debugbreak(); } DWORD ms = GetTickCount() - lineDownloadStart; double secs = (double)ms / 1000.0; symprintf(QT_TRANSLATE_NOOP("DBG", "Finished downloading symbol %s in %.03fs\n"), pdbBaseFile, secs); { EXCLUSIVE_ACQUIRE(LockModules); auto info = ModInfoFromAddr(Base); if(!info) { // TODO: this really isn't supposed to happen, but could if the module is suddenly unloaded dputs("module not found..."); return false; } // trigger a symbol load info->loadSymbols(szSymbolPath, bForceLoadSymbols); } return true; #undef symprintf } void SymDownloadAllSymbols(const char* SymbolStore) { // Default to Microsoft's symbol server if(!SymbolStore) SymbolStore = "https://msdl.microsoft.com/download/symbols"; //TODO: refactor this in a function because this pattern will become common std::vector<duint> mods; ModEnum([&mods](const MODINFO & info) { mods.push_back(info.base); }); for(duint base : mods) SymDownloadSymbol(base, SymbolStore); } bool SymAddrFromName(const char* Name, duint* Address) { if(!Name || Name[0] == '\0') return false; if(!Address) return false; // Skip 'OrdinalXXX' if(_strnicmp(Name, "Ordinal#", 8) == 0 && strlen(Name) > 8) { const char* Name1 = Name + 8; bool notNonNumbersFound = true; do { if(!(Name1[0] >= '0' && Name1[0] <= '9')) { notNonNumbersFound = false; break; } Name1++; } while(Name1[0] != 0); if(notNonNumbersFound) return false; } //TODO: refactor this in a function because this pattern will become common std::vector<duint> mods; ModEnum([&mods](const MODINFO & info) { mods.push_back(info.base); }); std::string name(Name); for(duint base : mods) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(base); if(modInfo && modInfo->symbols->isOpen()) { SymbolInfo symInfo; if(modInfo->symbols->findSymbolByName(name, symInfo, true)) { *Address = base + symInfo.rva; return true; } } } return false; } String SymGetSymbolicName(duint Address, bool IncludeAddress) { // // This resolves an address to a module and symbol: // [modname.]symbolname // char label[MAX_SYM_NAME]; char modname[MAX_MODULE_SIZE]; auto hasModule = ModNameFromAddr(Address, modname, false); // User labels have priority, but if one wasn't found, // default to a symbol lookup if(!DbgGetLabelAt(Address, SEG_DEFAULT, label)) { if(hasModule) return StringUtils::sprintf("%s.%p", modname, Address); else if(IncludeAddress) return StringUtils::sprintf("%p", Address); else return ""; } if(hasModule) { if(IncludeAddress) return StringUtils::sprintf("<%s.%s> (%p)", modname, label, Address); else return StringUtils::sprintf("<%s.%s>", modname, label); } else { if(IncludeAddress) return StringUtils::sprintf("<%s> (%p)", label, Address); else return StringUtils::sprintf("<%s>", label); } } bool SymbolFromAddressExact(duint address, SYMBOLINFO* info) { if(address == 0) return false; SHARED_ACQUIRE(LockModules); MODINFO* modInfo = ModInfoFromAddr(address); if(modInfo == nullptr) return false; duint base = modInfo->base; duint rva = address - base; // search in symbols if(modInfo->symbols->isOpen()) { SymbolInfo symInfo; if(modInfo->symbols->findSymbolExact(rva, symInfo)) { symInfo.copyToGuiSymbol(base, info); return true; } } // search in module exports { auto modExport = modInfo->findExport(rva); if(modExport != nullptr) { modExport->copyToGuiSymbol(base, info); return true; } } if(modInfo->entry != 0 && modInfo->entrySymbol.rva == rva) { modInfo->entrySymbol.convertToGuiSymbol(base, info); return true; } // search in module imports { auto modImport = modInfo->findImport(rva); if(modImport != nullptr) { modImport->copyToGuiSymbol(base, info); return true; } } return false; } bool SymbolFromAddressExactOrLower(duint address, SYMBOLINFO* info) { if(address == 0) return false; SHARED_ACQUIRE(LockModules); MODINFO* modInfo = ModInfoFromAddr(address); if(modInfo == nullptr) return false; duint rva = address - modInfo->base; // search in module symbols if(modInfo->symbols->isOpen()) { SymbolInfo symInfo; if(modInfo->symbols->findSymbolExactOrLower(rva, symInfo)) { symInfo.copyToGuiSymbol(modInfo->base, info); return true; } } // search in module exports if(!modInfo->exports.empty()) { auto it = [&]() { auto it = std::lower_bound(modInfo->exportsByRva.begin(), modInfo->exportsByRva.end(), rva, [&modInfo](size_t index, duint rva) { return modInfo->exports.at(index).rva < rva; }); // not found if(it == modInfo->exportsByRva.end()) return --it; // exact match if(modInfo->exports[*it].rva == rva) return it; // right now 'it' points to the first element bigger than rva return it == modInfo->exportsByRva.begin() ? modInfo->exportsByRva.end() : --it; }(); if(it != modInfo->exportsByRva.end()) { const auto & symbol = modInfo->exports[*it]; symbol.copyToGuiSymbol(modInfo->base, info); return true; } } return false; } bool SymGetSourceLine(duint Cip, char* FileName, int* Line, duint* disp) { SHARED_ACQUIRE(LockModules); MODINFO* modInfo = ModInfoFromAddr(Cip); if(!modInfo) return false; SymbolSourceBase* sym = modInfo->symbols; if(!sym || sym == &EmptySymbolSource) return false; LineInfo lineInfo; if(!sym->findSourceLineInfo(Cip - modInfo->base, lineInfo)) return false; if(disp) *disp = lineInfo.disp; if(Line) *Line = lineInfo.lineNumber; if(FileName) { strncpy_s(FileName, MAX_STRING_SIZE, lineInfo.sourceFile.c_str(), _TRUNCATE); // Check if it was a full path if(!PathIsRelativeW(StringUtils::Utf8ToUtf16(lineInfo.sourceFile).c_str())) return true; // Construct full path from pdb path { SHARED_ACQUIRE(LockModules); MODINFO* info = ModInfoFromAddr(Cip); if(!info) return true; String sourceFilePath = info->symbols->loadedSymbolPath(); // Strip the name, leaving only the file directory size_t bslash = sourceFilePath.rfind('\\'); if(bslash != String::npos) sourceFilePath.resize(bslash + 1); sourceFilePath += lineInfo.sourceFile; // Attempt to remap the source file if it exists (more heuristics could be added in the future) if(FileExists(sourceFilePath.c_str())) { if(info->symbols->mapSourceFilePdbToDisk(lineInfo.sourceFile, sourceFilePath)) { strncpy_s(FileName, MAX_STRING_SIZE, sourceFilePath.c_str(), _TRUNCATE); } } } } return true; } bool SymGetSourceAddr(duint Module, const char* FileName, int Line, duint* Address) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(Module); if(!modInfo) return false; auto sym = modInfo->symbols; if(!sym || sym == &EmptySymbolSource) return false; LineInfo lineInfo; if(!sym->findSourceLineInfo(FileName, Line, lineInfo)) return false; *Address = lineInfo.rva + modInfo->base; return true; }
C/C++
x64dbg-development/src/dbg/symbolinfo.h
#pragma once #include "_global.h" extern duint symbolDownloadingBase; bool SymEnum(duint Base, CBSYMBOLENUM EnumCallback, void* UserData, duint BeginRva, duint EndRva, unsigned int SymbolMask); bool SymGetModuleList(std::vector<SYMBOLMODULEINFO>* List); void SymUpdateModuleList(); bool SymDownloadSymbol(duint Base, const char* SymbolStore); void SymDownloadAllSymbols(const char* SymbolStore); bool SymAddrFromName(const char* Name, duint* Address); String SymGetSymbolicName(duint Address, bool IncludeAddress = true); bool SymbolFromAddressExact(duint address, SYMBOLINFO* info); bool SymbolFromAddressExactOrLower(duint address, SYMBOLINFO* info); /** \brief Gets the source code file name and line from an address. \param cip The address to check. \param [out] szFileName Source code file. Buffer of MAX_STRING_SIZE length. UTF-8. Can be null. \param [out] nLine Line number. Can be null. \return true if it succeeds, false if it fails. */ bool SymGetSourceLine(duint Cip, char* FileName, int* Line, duint* displacement = nullptr); bool SymGetSourceAddr(duint Module, const char* FileName, int Line, duint* Address);
C++
x64dbg-development/src/dbg/symbolsourcebase.cpp
#include "symbolsourcebase.h" #include <algorithm> bool NameIndex::findByPrefix(const std::vector<NameIndex> & byName, const std::string & prefix, const std::function<bool(const NameIndex &)> & cbFound, bool caseSensitive) { struct PrefixCmp { PrefixCmp(size_t n) : n(n) { } bool operator()(const NameIndex & a, const NameIndex & b) { return cmp(a, b, false) < 0; } int cmp(const NameIndex & a, const NameIndex & b, bool caseSensitive) { return (caseSensitive ? strncmp : _strnicmp)(a.name, b.name, n); } private: size_t n; } prefixCmp(prefix.size()); if(byName.empty()) return false; NameIndex find; find.name = prefix.c_str(); find.index = -1; auto found = binary_find(byName.begin(), byName.end(), find, prefixCmp); if(found == byName.end()) return false; bool result = false; for(; found != byName.end() && prefixCmp.cmp(find, *found, false) == 0; ++found) { if(!caseSensitive || prefixCmp.cmp(find, *found, true) == 0) { result = true; if(!cbFound(*found)) break; } } return result; } bool NameIndex::findByName(const std::vector<NameIndex> & byName, const std::string & name, NameIndex & foundIndex, bool caseSensitive) { NameIndex find; find.name = name.c_str(); auto found = binary_find(byName.begin(), byName.end(), find); if(found != byName.end()) { do { if(find.cmp(*found, find, caseSensitive) == 0) { foundIndex = *found; return true; } ++found; } while(found != byName.end() && find.cmp(find, *found, false) == 0); } return false; } bool SymbolSourceBase::mapSourceFilePdbToDisk(const std::string & pdb, const std::string & disk) { std::string pdblower = pdb, disklower = disk; std::transform(pdblower.begin(), pdblower.end(), pdblower.begin(), tolower); std::transform(disklower.begin(), disklower.end(), disklower.begin(), tolower); // Abort if the disk file doesn't exist if(!FileExists(disklower.c_str())) return false; // Remove existing mapping if found auto found = _sourceFileMapPdbToDisk.find(pdblower); if(found != _sourceFileMapPdbToDisk.end()) { // Abort if there is already an existing mapping for the destination (we want 1 to 1 mapping) // Done here because we can avoid corrupting the state if(disklower != found->second && _sourceFileMapDiskToPdb.count(disklower)) return false; // Remove existing mapping _sourceFileMapDiskToPdb.erase(found->second); _sourceFileMapPdbToDisk.erase(found); } // Abort if there is already an existing mapping for the destination (we want 1 to 1 mapping) else if(_sourceFileMapDiskToPdb.count(disklower)) { return false; } // Insert destinations _sourceFileMapPdbToDisk.insert({ pdblower, disk }); _sourceFileMapDiskToPdb.insert({ disklower, pdb }); return true; } bool SymbolSourceBase::getSourceFileDiskToPdb(const std::string & disk, std::string & pdb) const { std::string disklower = disk; std::transform(disklower.begin(), disklower.end(), disklower.begin(), tolower); auto found = _sourceFileMapDiskToPdb.find(disklower); if(found == _sourceFileMapDiskToPdb.end()) return false; pdb = found->second; return true; } bool SymbolSourceBase::getSourceFilePdbToDisk(const std::string & pdb, std::string & disk) const { std::string pdblower = pdb; std::transform(pdblower.begin(), pdblower.end(), pdblower.begin(), tolower); auto found = _sourceFileMapPdbToDisk.find(pdblower); if(found == _sourceFileMapPdbToDisk.end()) return false; disk = found->second; return true; }
C/C++
x64dbg-development/src/dbg/symbolsourcebase.h
#ifndef _SYMBOLSOURCEBASE_H_ #define _SYMBOLSOURCEBASE_H_ #include "_global.h" #include <stdint.h> #include <vector> #include <functional> #include <map> #include <algorithm> //http://en.cppreference.com/w/cpp/algorithm/lower_bound template<class ForwardIt, class T, class Compare = std::less<>> static ForwardIt binary_find(ForwardIt first, ForwardIt last, const T & value, Compare comp = {}) { // Note: BOTH type T and the type after ForwardIt is dereferenced // must be implicitly convertible to BOTH Type1 and Type2, used in Compare. // This is stricter than lower_bound requirement (see above) first = std::lower_bound(first, last, value, comp); return first != last && !comp(value, *first) ? first : last; } struct SymbolInfoGui { virtual void convertToGuiSymbol(duint base, SYMBOLINFO* info) const = 0; void copyToGuiSymbol(duint modbase, SYMBOLINFO* info) const { convertToGuiSymbol(modbase, info); if(!info->freeDecorated) { const char* name = info->decoratedSymbol; size_t len = strlen(name); info->decoratedSymbol = (char*)BridgeAlloc(len + 1); memcpy(info->decoratedSymbol, name, len + 1); info->freeDecorated = true; } if(!info->freeUndecorated) { const char* name = info->undecoratedSymbol; size_t len = strlen(name); info->undecoratedSymbol = (char*)BridgeAlloc(len + 1); memcpy(info->undecoratedSymbol, name, len + 1); info->freeUndecorated = true; } } }; struct SymbolInfo : SymbolInfoGui { duint rva = 0; duint size = 0; int32 disp = 0; String decoratedName; String undecoratedName; bool publicSymbol = false; void convertToGuiSymbol(duint modbase, SYMBOLINFO* info) const override { info->addr = modbase + this->rva; info->decoratedSymbol = (char*)this->decoratedName.c_str(); info->undecoratedSymbol = (char*)this->undecoratedName.c_str(); info->type = sym_symbol; info->freeDecorated = info->freeUndecorated = false; info->ordinal = 0; } }; struct LineInfo { duint rva = 0; duint size = 0; duint disp = 0; int lineNumber = 0; String sourceFile; }; struct NameIndex { const char* name; size_t index; bool operator<(const NameIndex & b) const { return cmp(*this, b, false) < 0; } static int cmp(const NameIndex & a, const NameIndex & b, bool caseSensitive) { return (caseSensitive ? strcmp : StringUtils::hackicmp)(a.name, b.name); } static bool findByPrefix(const std::vector<NameIndex> & byName, const std::string & prefix, const std::function<bool(const NameIndex &)> & cbFound, bool caseSensitive); static bool findByName(const std::vector<NameIndex> & byName, const std::string & name, NameIndex & foundIndex, bool caseSensitive); }; using CbEnumSymbol = std::function<bool(const SymbolInfo &)>; class SymbolSourceBase { private: std::vector<uint8_t> _symbolBitmap; // TODO: what is the maximum size for this? std::map<std::string, std::string> _sourceFileMapPdbToDisk; // pdb source path -> disk source path std::map<std::string, std::string> _sourceFileMapDiskToPdb; // disk source path -> pdb source path public: virtual ~SymbolSourceBase() = default; void resizeSymbolBitmap(size_t imageSize) { if(!isOpen()) return; _symbolBitmap.resize(imageSize); std::fill(_symbolBitmap.begin(), _symbolBitmap.end(), false); } void markAdressInvalid(duint rva) { if(_symbolBitmap.empty()) return; _symbolBitmap[rva] = true; } bool isAddressInvalid(duint rva) const { if(_symbolBitmap.empty()) return false; return !!_symbolBitmap[rva]; } // Tells us if the symbols are loaded for this module. virtual bool isOpen() const { return false; // Stub } virtual bool isLoading() const { return false; // Stub } virtual bool cancelLoading() { return false; // Stub } virtual void waitUntilLoaded() { // Stub } // Get the symbol at the specified address, will return false if not found. virtual bool findSymbolExact(duint rva, SymbolInfo & symInfo) { return false; // Stub } // Get the symbol at the address or the closest behind, in case it got the closest it will set disp to non-zero, false on nothing. virtual bool findSymbolExactOrLower(duint rva, SymbolInfo & symInfo) { return false; // Stub } // only call if isOpen && !isLoading virtual void enumSymbols(const CbEnumSymbol & cbEnum, duint beginRva = 0, duint endRva = -1) { // Stub } virtual bool findSourceLineInfo(duint rva, LineInfo & lineInfo) { return false; // Stub } virtual bool findSourceLineInfo(const std::string & file, int line, LineInfo & lineInfo) { return false; // Stub } virtual bool findSymbolByName(const std::string & name, SymbolInfo & symInfo, bool caseSensitive) { return false; // Stub } virtual bool findSymbolsByPrefix(const std::string & prefix, const std::function<bool(const SymbolInfo &)> & cbSymbol, bool caseSensitive) { return false; // Stub } virtual std::string loadedSymbolPath() const { return ""; // Stub } bool mapSourceFilePdbToDisk(const std::string & pdb, const std::string & disk); bool getSourceFilePdbToDisk(const std::string & pdb, std::string & disk) const; bool getSourceFileDiskToPdb(const std::string & disk, std::string & pdb) const; }; static SymbolSourceBase EmptySymbolSource; #endif // _SYMBOLSOURCEBASE_H_
C++
x64dbg-development/src/dbg/symbolsourcedia.cpp
#include "symbolsourcedia.h" #include "console.h" #include "debugger.h" #include <algorithm> SymbolSourceDIA::SymbolSourceDIA() : _isOpen(false), _requiresShutdown(false), _loadCounter(0), _imageBase(0), _imageSize(0) { } SymbolSourceDIA::~SymbolSourceDIA() { SymbolSourceDIA::cancelLoading(); if(_imageBase) GuiInvalidateSymbolSource(_imageBase); } static void SetWin10ThreadDescription(HANDLE threadHandle, const WString & name) { typedef HRESULT(WINAPI * fnSetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription); fnSetThreadDescription fp = (fnSetThreadDescription)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription"); if(!fp) return; // Only available on windows 10. fp(threadHandle, name.c_str()); } DWORD WINAPI SymbolSourceDIA::SymbolsThread(void* parameter) { ((SymbolSourceDIA*)parameter)->loadSymbolsAsync(); return 0; } DWORD WINAPI SymbolSourceDIA::SourceLinesThread(void* parameter) { ((SymbolSourceDIA*)parameter)->loadSourceLinesAsync(); return 0; } bool SymbolSourceDIA::loadPDB(const std::string & path, const std::string & modname, duint imageBase, duint imageSize, DiaValidationData_t* validationData) { if(!validationData) { GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] Skipping PDB validation, expect invalid results!\n", imageBase, modname.c_str()).c_str()); } PDBDiaFile pdb; // Instance used for validation only. _isOpen = pdb.open(path.c_str(), 0, validationData); if(_isOpen) { _path = path; _imageSize = imageSize; _modname = modname; _imageBase = imageBase; _requiresShutdown = false; _symbolsLoaded = false; _loadCounter.store(2); _symbolsThread = CreateThread(nullptr, 0, SymbolsThread, this, CREATE_SUSPENDED, nullptr); SetWin10ThreadDescription(_symbolsThread, L"SymbolsThread"); _sourceLinesThread = CreateThread(nullptr, 0, SourceLinesThread, this, CREATE_SUSPENDED, nullptr); SetWin10ThreadDescription(_sourceLinesThread, L"SourceLinesThread"); ResumeThread(_symbolsThread); ResumeThread(_sourceLinesThread); } return _isOpen; } bool SymbolSourceDIA::isOpen() const { return _isOpen; } bool SymbolSourceDIA::isLoading() const { return _loadCounter > 0; } bool SymbolSourceDIA::cancelLoading() { _requiresShutdown.store(true); if(_symbolsThread) { WaitForSingleObject(_symbolsThread, INFINITE); CloseHandle(_symbolsThread); _symbolsThread = nullptr; } if(_sourceLinesThread) { WaitForSingleObject(_sourceLinesThread, INFINITE); CloseHandle(_sourceLinesThread); _sourceLinesThread = nullptr; } return true; } void SymbolSourceDIA::waitUntilLoaded() { while(isLoading()) Sleep(10); } template<size_t Count> static bool startsWith(const char* str, const char(&prefix)[Count]) { return strncmp(str, prefix, Count - 1) == 0; } bool SymbolSourceDIA::loadSymbolsAsync() { ScopedDecrement ref(_loadCounter); GuiRepaintTableView(); PDBDiaFile pdb; if(!pdb.open(_path.c_str())) { return false; } DWORD lastUpdate = 0; DWORD loadStart = GetTickCount(); PDBDiaFile::Query_t query; query.collectSize = false; query.collectUndecoratedNames = true; query.callback = [&](DiaSymbol_t & sym) -> bool { if(_requiresShutdown) return false; if(sym.name.c_str()[0] == 0x7F) return true; #define filter(prefix) if(startsWith(sym.name.c_str(), prefix)) return true filter("__imp__"); filter("__imp_?"); filter("_imp___"); filter("__NULL_IMPORT_DESCRIPTOR"); filter("__IMPORT_DESCRIPTOR_"); #undef filter if(sym.type == DiaSymbolType::PUBLIC || sym.type == DiaSymbolType::FUNCTION || sym.type == DiaSymbolType::LABEL || sym.type == DiaSymbolType::DATA) //TODO: properly handle import thunks + empty names + line symbols { _symData.emplace_back(); SymbolInfo & symInfo = _symData.back(); symInfo.decoratedName = std::move(sym.name); symInfo.undecoratedName = std::move(sym.undecoratedName); symInfo.size = (duint)sym.size; symInfo.disp = sym.disp; symInfo.rva = (duint)sym.virtualAddress; symInfo.publicSymbol = sym.publicSymbol; } return true; }; bool res = pdb.enumerateLexicalHierarchy(query); if(!res) { return false; } //handle symbol address sorting { _symAddrMap.resize(_symData.size()); for(size_t i = 0; i < _symData.size(); i++) { AddrIndex addrIndex; addrIndex.rva = _symData[i].rva; addrIndex.index = i; _symAddrMap[i] = addrIndex; } std::sort(_symAddrMap.begin(), _symAddrMap.end(), [this](const AddrIndex & a, const AddrIndex & b) { // smaller if(a.rva < b.rva) { return true; } // bigger else if(a.rva > b.rva) { return false; } // equal else { // Check if we already have it inside, public symbols have priority over private symbols. return !_symData[a.index].publicSymbol < !_symData[b.index].publicSymbol; } }); } //remove duplicate symbols from view if(!_symAddrMap.empty()) { SymbolInfo* prev = nullptr; size_t insertPos = 0; for(size_t i = 0; i < _symAddrMap.size(); i++) { AddrIndex addrIndex = _symAddrMap[i]; SymbolInfo & sym = _symData[addrIndex.index]; if(prev && sym.rva == prev->rva && sym.decoratedName == prev->decoratedName && sym.undecoratedName == prev->undecoratedName) { String().swap(sym.decoratedName); String().swap(sym.undecoratedName); continue; } prev = &sym; _symAddrMap[insertPos++] = addrIndex; } _symAddrMap.resize(insertPos); } //handle symbol name sorting { _symNameMap.resize(_symAddrMap.size()); for(size_t i = 0; i < _symAddrMap.size(); i++) { size_t symIndex = _symAddrMap[i].index; NameIndex nameIndex; nameIndex.name = _symData[symIndex].decoratedName.c_str(); //NOTE: DO NOT MODIFY decoratedName is any way! nameIndex.index = symIndex; _symNameMap[i] = nameIndex; } std::sort(_symNameMap.begin(), _symNameMap.end()); } if(_requiresShutdown) return false; _symbolsLoaded = true; DWORD ms = GetTickCount() - loadStart; double secs = (double)ms / 1000.0; GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] Loaded %u symbols in %.03fs\n", _imageBase, _modname.c_str(), _symAddrMap.size(), secs).c_str()); GuiInvalidateSymbolSource(_imageBase); GuiUpdateAllViews(); return true; } bool SymbolSourceDIA::loadSourceLinesAsync() { ScopedDecrement ref(_loadCounter); GuiRepaintTableView(); PDBDiaFile pdb; if(!pdb.open(_path.c_str())) { return false; } DWORD lineLoadStart = GetTickCount(); const uint32_t rangeSize = 1024 * 1024 * 10; std::vector<DiaLineInfo_t> lines; std::map<DWORD, String> files; if(!pdb.enumerateLineNumbers(0, uint32_t(_imageSize), lines, files, _requiresShutdown)) return false; if(files.size() == 1) { GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] Since there is only one file, attempting line overflow detection (%ums)..\n", _imageBase, _modname.c_str(), GetTickCount() - lineLoadStart).c_str()); // This is a super hack to adjust for the (undocumented) limit of 16777215 lines (unsigned 24 bits maximum). // It is unclear at this point if yasm/coff/link/pdb is causing this issue. // We can fix this because there is only a single source file and the returned result is sorted by *both* rva/line (IMPORTANT!). // For supporting multiple source files in the future we could need multiple 'lineOverflow' variables. uint32_t maxLine = 0, maxRva = 0, lineOverflows = 0; for(auto & line : lines) { if(_requiresShutdown) return false; uint32_t overflowValue = 0x1000000 * (lineOverflows + 1) - 1; //0xffffff, 0x1ffffff, 0x2ffffff, etc if((line.lineNumber & 0xfffff0) == 0 && (maxLine & 0xfffffff0) == (overflowValue & 0xfffffff0)) // allow 16 lines of play, perhaps there is a label/comment on line 0xffffff+1 { GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] Line number overflow detected (%u -> %u), adjusting with hacks...\n", _imageBase, _modname.c_str(), maxLine, line.lineNumber).c_str()); lineOverflows++; } line.lineNumber += lineOverflows * 0xffffff + lineOverflows; if(!(line.lineNumber > maxLine)) { GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] The line information is not sorted by line (violated assumption)! lineNumber: %u, maxLine: %u\n", _imageBase, _modname.c_str(), line.lineNumber, maxLine).c_str()); } maxLine = line.lineNumber; if(!(line.rva > maxRva)) { GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] The line information is not sorted by rva (violated assumption)! rva: 0x%x, maxRva: 0x%x\n", _imageBase, _modname.c_str(), line.rva, maxRva).c_str()); } maxRva = line.rva; } } _linesData.reserve(lines.size()); _sourceFiles.reserve(files.size()); _lineAddrMap.reserve(lines.size()); struct SourceFileInfo { uint32_t sourceFileIndex; uint32_t lineCount; }; std::map<DWORD, SourceFileInfo> sourceIdMap; //DIA sourceId -> sourceFileInfo for(const auto & line : lines) { if(_requiresShutdown) return false; _linesData.emplace_back(); CachedLineInfo & lineInfo = _linesData.back(); lineInfo.rva = line.rva; lineInfo.lineNumber = line.lineNumber; auto sourceFileId = line.sourceFileId; auto found = sourceIdMap.find(sourceFileId); if(found == sourceIdMap.end()) { SourceFileInfo info; info.sourceFileIndex = uint32_t(_sourceFiles.size()); info.lineCount = 0; _sourceFiles.push_back(files[sourceFileId]); found = sourceIdMap.insert({ sourceFileId, info }).first; } found->second.lineCount++; lineInfo.sourceFileIndex = found->second.sourceFileIndex; AddrIndex lineIndex; lineIndex.rva = lineInfo.rva; lineIndex.index = _linesData.size() - 1; _lineAddrMap.push_back(lineIndex); } // stable because first line encountered has to be found std::stable_sort(_lineAddrMap.begin(), _lineAddrMap.end()); // perfectly allocate memory for line info vectors _sourceLines.resize(_sourceFiles.size()); for(const auto & it : sourceIdMap) _sourceLines[it.second.sourceFileIndex].reserve(it.second.lineCount); // insert source line information for(size_t i = 0; i < _linesData.size(); i++) { auto & line = _linesData[i]; LineIndex lineIndex; lineIndex.line = line.lineNumber; lineIndex.index = uint32_t(i); _sourceLines[line.sourceFileIndex].push_back(lineIndex); } // sort source line information for(size_t i = 0; i < _sourceLines.size(); i++) { auto & lineMap = _sourceLines[i]; std::stable_sort(lineMap.begin(), lineMap.end()); } if(_requiresShutdown) return false; _linesLoaded = true; DWORD ms = GetTickCount() - lineLoadStart; double secs = (double)ms / 1000.0; GuiSymbolLogAdd(StringUtils::sprintf("[%p, %s] Loaded %d line infos in %.03fs\n", _imageBase, _modname.c_str(), _linesData.size(), secs).c_str()); GuiUpdateAllViews(); return true; } uint32_t SymbolSourceDIA::findSourceFile(const std::string & fileName) const { // Map the disk file name back to PDB file name std::string mappedFileName; if(!getSourceFileDiskToPdb(fileName, mappedFileName)) mappedFileName = fileName; //TODO: make this fast uint32_t idx = -1; for(uint32_t n = 0; n < _sourceFiles.size(); n++) { const String & str = _sourceFiles[n]; if(_stricmp(str.c_str(), mappedFileName.c_str()) == 0) { idx = n; break; } } return idx; } bool SymbolSourceDIA::findSymbolExact(duint rva, SymbolInfo & symInfo) { if(!_symbolsLoaded) return false; if(SymbolSourceBase::isAddressInvalid(rva)) return false; AddrIndex find; find.rva = rva; find.index = -1; auto it = binary_find(_symAddrMap.begin(), _symAddrMap.end(), find); if(it != _symAddrMap.end()) { symInfo = _symData[it->index]; return true; } if(isLoading() == false) markAdressInvalid(rva); return false; } bool SymbolSourceDIA::findSymbolExactOrLower(duint rva, SymbolInfo & symInfo) { if(!_symbolsLoaded) return false; if(_symAddrMap.empty()) return false; AddrIndex find; find.rva = rva; find.index = -1; auto it = [&]() { auto it = std::lower_bound(_symAddrMap.begin(), _symAddrMap.end(), find); // not found if(it == _symAddrMap.end()) return --it; // exact match if(it->rva == rva) return it; // right now 'it' points to the first element bigger than rva return it == _symAddrMap.begin() ? _symAddrMap.end() : --it; }(); if(it != _symAddrMap.end()) { symInfo = _symData[it->index]; symInfo.disp = (int32_t)(rva - symInfo.rva); return true; } return false; } void SymbolSourceDIA::enumSymbols(const CbEnumSymbol & cbEnum, duint beginRva, duint endRva) { if(!_symbolsLoaded) return; if(_symAddrMap.empty()) return; if(beginRva > endRva) return; AddrIndex find; find.rva = beginRva; find.index = -1; auto it = _symAddrMap.begin(); if(beginRva > it->rva) { it = std::lower_bound(_symAddrMap.begin(), _symAddrMap.end(), find); if(it == _symAddrMap.end()) return; } for(; it != _symAddrMap.end(); it++) { const SymbolInfo & sym = _symData[it->index]; if(sym.rva > endRva) { break; } if(!cbEnum(sym)) { break; } } } bool SymbolSourceDIA::findSourceLineInfo(duint rva, LineInfo & lineInfo) { if(!_linesLoaded) return false; AddrIndex find; find.rva = rva; find.index = -1; auto it = binary_find(_lineAddrMap.begin(), _lineAddrMap.end(), find); if(it == _lineAddrMap.end()) return false; auto & cached = _linesData.at(it->index); lineInfo.rva = cached.rva; lineInfo.lineNumber = cached.lineNumber; lineInfo.disp = 0; lineInfo.size = 0; lineInfo.sourceFile = _sourceFiles[cached.sourceFileIndex]; getSourceFilePdbToDisk(lineInfo.sourceFile, lineInfo.sourceFile); return true; } bool SymbolSourceDIA::findSourceLineInfo(const std::string & file, int line, LineInfo & lineInfo) { if(!_linesLoaded) return false; auto sourceIdx = findSourceFile(file); if(sourceIdx == -1) return false; auto & lineMap = _sourceLines[sourceIdx]; LineIndex find; find.line = line; find.index = -1; auto found = binary_find(lineMap.begin(), lineMap.end(), find); if(found == lineMap.end()) return false; auto & cached = _linesData[found->index]; lineInfo.rva = cached.rva; lineInfo.lineNumber = cached.lineNumber; lineInfo.disp = 0; lineInfo.size = 0; lineInfo.sourceFile = _sourceFiles[cached.sourceFileIndex]; getSourceFilePdbToDisk(lineInfo.sourceFile, lineInfo.sourceFile); return true; } bool SymbolSourceDIA::findSymbolByName(const std::string & name, SymbolInfo & symInfo, bool caseSensitive) { if(!_symbolsLoaded) return false; NameIndex found; if(!NameIndex::findByName(_symNameMap, name, found, caseSensitive)) return false; symInfo = _symData[found.index]; return true; } bool SymbolSourceDIA::findSymbolsByPrefix(const std::string & prefix, const std::function<bool(const SymbolInfo &)> & cbSymbol, bool caseSensitive) { if(!_symbolsLoaded) return false; return NameIndex::findByPrefix(_symNameMap, prefix, [this, &cbSymbol](const NameIndex & index) { return cbSymbol(_symData[index.index]); }, caseSensitive); } std::string SymbolSourceDIA::loadedSymbolPath() const { return _path; }
C/C++
x64dbg-development/src/dbg/symbolsourcedia.h
#ifndef _SYMBOLSOURCEDIA_H_ #define _SYMBOLSOURCEDIA_H_ #include "_global.h" #include "pdbdiafile.h" #include "symbolsourcebase.h" #include <thread> #include <atomic> #include <mutex> class SymbolSourceDIA : public SymbolSourceBase { struct CachedLineInfo { uint32 rva; uint32 lineNumber; uint32 sourceFileIndex; }; struct ScopedDecrement { private: std::atomic<duint> & _counter; public: ScopedDecrement(const ScopedDecrement &) = delete; ScopedDecrement & operator=(const ScopedDecrement &) = delete; ScopedDecrement(std::atomic<duint> & counter) : _counter(counter) {} ~ScopedDecrement() { _counter--; } }; private: //symbols std::vector<SymbolInfo> _symData; struct AddrIndex { duint rva; size_t index; bool operator<(const AddrIndex & b) const { return rva < b.rva; } }; std::vector<AddrIndex> _symAddrMap; //rva -> data index (sorted on rva) std::vector<NameIndex> _symNameMap; //name -> data index (sorted on name) private: //line info std::vector<CachedLineInfo> _linesData; std::vector<AddrIndex> _lineAddrMap; //addr -> line std::vector<String> _sourceFiles; // uniqueId + name struct LineIndex { uint32_t line; uint32_t index; bool operator<(const LineIndex & b) const { return line < b.line; } }; std::vector<std::vector<LineIndex>> _sourceLines; //uses index in _sourceFiles private: //general HANDLE _symbolsThread = nullptr; HANDLE _sourceLinesThread = nullptr; std::atomic<bool> _requiresShutdown; std::atomic<duint> _loadCounter; bool _isOpen; std::string _path; std::string _modname; duint _imageBase; duint _imageSize; std::atomic<bool> _symbolsLoaded = false; std::atomic<bool> _linesLoaded = false; private: static int hackicmp(const char* s1, const char* s2) { unsigned char c1, c2; while((c1 = *s1++) == (c2 = *s2++)) if(c1 == '\0') return 0; s1--, s2--; while((c1 = tolower(*s1++)) == (c2 = tolower(*s2++))) if(c1 == '\0') return 0; return c1 - c2; } public: static bool isLibraryAvailable() { return PDBDiaFile::initLibrary(); } public: SymbolSourceDIA(); virtual ~SymbolSourceDIA() override; virtual bool isOpen() const override; virtual bool isLoading() const override; virtual bool cancelLoading() override; virtual void waitUntilLoaded() override; virtual bool findSymbolExact(duint rva, SymbolInfo & symInfo) override; virtual bool findSymbolExactOrLower(duint rva, SymbolInfo & symInfo) override; virtual void enumSymbols(const CbEnumSymbol & cbEnum, duint beginRva, duint endRva) override; virtual bool findSourceLineInfo(duint rva, LineInfo & lineInfo) override; virtual bool findSourceLineInfo(const std::string & file, int line, LineInfo & lineInfo) override; virtual bool findSymbolByName(const std::string & name, SymbolInfo & symInfo, bool caseSensitive) override; virtual bool findSymbolsByPrefix(const std::string & prefix, const std::function<bool(const SymbolInfo &)> & cbSymbol, bool caseSensitive) override; virtual std::string loadedSymbolPath() const override; public: bool loadPDB(const std::string & path, const std::string & modname, duint imageBase, duint imageSize, DiaValidationData_t* validationData); private: bool loadSymbolsAsync(); bool loadSourceLinesAsync(); uint32_t findSourceFile(const std::string & fileName) const; static DWORD WINAPI SymbolsThread(void* parameter); static DWORD WINAPI SourceLinesThread(void* parameter); }; #endif // _SYMBOLSOURCEPDB_H_
C/C++
x64dbg-development/src/dbg/symbolundecorator.h
#pragma once /* MIT License Copyright (c) 2018 Duncan Ogilvie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <string> typedef char* pchar_t; typedef const char* pcchar_t; typedef char* (*GetParameter_t)(long n); using Alloc_t = decltype(malloc); using Free_t = decltype(free); enum { X_UNDNAME_COMPLETE = 0x0, //Enables full undecoration. X_UNDNAME_NO_LEADING_UNDERSCORES = 0x1, //Removes leading underscores from Microsoft extended keywords. X_UNDNAME_NO_MS_KEYWORDS = 0x2, //Disables expansion of Microsoft extended keywords. X_UNDNAME_NO_FUNCTION_RETURNS = 0x4, //Disables expansion of return type for primary declaration. X_UNDNAME_NO_ALLOCATION_MODEL = 0x8, //Disables expansion of the declaration model. X_UNDNAME_NO_ALLOCATION_LANGUAGE = 0x10, //Disables expansion of the declaration language specifier. X_UNDNAME_NO_MS_THISTYPE = 0x20, //NYI Disable expansion of MS keywords on the 'this' type for primary declaration. X_UNDNAME_NO_CV_THISTYPE = 0x40, //NYI Disable expansion of CV modifiers on the 'this' type for primary declaration/ X_UNDNAME_NO_THISTYPE = 0x60, //Disables all modifiers on the this type. X_UNDNAME_NO_ACCESS_SPECIFIERS = 0x80, //Disables expansion of access specifiers for members. X_UNDNAME_NO_THROW_SIGNATURES = 0x100, //Disables expansion of "throw-signatures" for functions and pointers to functions. X_UNDNAME_NO_MEMBER_TYPE = 0x200, //Disables expansion of static or virtual members. X_UNDNAME_NO_RETURN_UDT_MODEL = 0x400, //Disables expansion of the Microsoft model for UDT returns. X_UNDNAME_32_BIT_DECODE = 0x800, //Undecorates 32-bit decorated names. X_UNDNAME_NAME_ONLY = 0x1000, //Gets only the name for primary declaration; returns just [scope::]name. Expands template params. X_UNDNAME_TYPE_ONLY = 0x2000, //Input is just a type encoding; composes an abstract declarator. X_UNDNAME_HAVE_PARAMETERS = 0x4000, //The real template parameters are available. X_UNDNAME_NO_ECSU = 0x8000, //Suppresses enum/class/struct/union. X_UNDNAME_NO_IDENT_CHAR_CHECK = 0x10000, //Suppresses check for valid identifier characters. X_UNDNAME_NO_PTR64 = 0x20000, //Does not include ptr64 in output. }; //undname.cxx extern "C" pchar_t __cdecl __unDNameEx(_Out_opt_z_cap_(maxStringLength) pchar_t outputString, pcchar_t name, int maxStringLength, // Note, COMMA is leading following optional arguments Alloc_t pAlloc, Free_t pFree, GetParameter_t pGetParameter, unsigned long disableFlags ); template<size_t MaxSize = 512> inline bool undecorateName(const std::string & decoratedName, std::string & undecoratedName) { //TODO: undocumented hack to have some kind of performance while undecorating names auto mymalloc = [](size_t size) { return emalloc(size, "symbolundecorator::undecoratedName"); }; auto myfree = [](void* ptr) { return efree(ptr, "symbolundecorator::undecoratedName"); }; undecoratedName.resize(max(MaxSize, decoratedName.length() * 2)); if(!__unDNameEx((char*)undecoratedName.data(), decoratedName.c_str(), (int)undecoratedName.size(), mymalloc, myfree, nullptr, X_UNDNAME_COMPLETE | X_UNDNAME_32_BIT_DECODE | X_UNDNAME_NO_PTR64)) { undecoratedName.clear(); return false; } else { undecoratedName.resize(strlen(undecoratedName.c_str())); if(decoratedName == undecoratedName) undecoratedName = ""; //https://stackoverflow.com/a/18299315 return true; } }
C/C++
x64dbg-development/src/dbg/syscalls.h
#pragma once #include <ntdll/ntdll.h> // https://github.com/x64dbg/ScyllaHide/blob/6817d32581b7a420322f34e36b1a1c8c3e4b434c/Scylla/Win32kSyscalls.h /* * The tables below were generated for each OS version using a modified version of wscg64 (https://github.com/hfiref0x/SyscallTables). * They were then converted to the format below to save space. std::map and std::string are banned in this file, they add about 600KB. * The syscalls are sorted by name only, so lookup is O(N) and done with string comparisons. This is okay because lookups are rare. * * All OS versions have separate syscall tables for x86 and x64, except 2600 which only exists as x86. WOW64 processes use the x64 table. * * Versions 14393 and later are not included because they come with win32u.dll, which exports win32k syscalls like ntdll does for ntoskrnl. */ // Space saving hack. The longest name here is 58 chars, so UCHAR is OK typedef struct _WIN32K_SYSCALL_INFO { const char* Name; struct { // Index 0 is x86, index 1 is WOW64 and x64. // None of the syscall numbers exceed 64K, so store them as SHORTs SHORT Index2600; // XP (x86 only) SHORT Index3790[2]; // Server 2003 / XP x64 SHORT Index6000[2]; // Vista SHORT Index7601[2]; // 7 SHORT Index9200[2]; // 8 SHORT Index9600[2]; // 8.1 SHORT Index10240[2]; // 10.0.10240.0 SHORT Index10586[2]; // 10.0.10586.0 } s; // A value of -1 means Win32k does not have the syscall on this OS/bitness combination. int GetSyscallIndex(USHORT osBuildNumber, bool nativeX86) const { return (int)(osBuildNumber == 2600 ? s.Index2600 : ((osBuildNumber >= 3790 && osBuildNumber <= 3800) ? s.Index3790[nativeX86 ? 0 : 1] : ((osBuildNumber >= 6000 && osBuildNumber <= 6002) ? s.Index6000[nativeX86 ? 0 : 1] : ((osBuildNumber == 7600 || osBuildNumber == 7601) ? s.Index7601[nativeX86 ? 0 : 1] : (osBuildNumber == 9200 ? s.Index9200[nativeX86 ? 0 : 1] : (osBuildNumber == 9600 ? s.Index9600[nativeX86 ? 0 : 1] : (osBuildNumber == 10240 ? s.Index10240[nativeX86 ? 0 : 1] : (osBuildNumber == 10586 ? s.Index10586[nativeX86 ? 0 : 1] : -1)))))))); } } WIN32K_SYSCALL_INFO, * PWIN32K_SYSCALL_INFO; #define MIN_WIN32K_SYSCALL_NUM 4096 #define MAX_WIN32K_SYSCALL_NUM 5230 static const WIN32K_SYSCALL_INFO Win32kSyscalls[] = { { "NtBindCompositionSurface", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4994, 4383 }, { 5012, 4384 }, { 5069, 4385 }, { 5071, 4385 } } }, { "NtCompositionInputThread", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5030, 4385 }, { 5093, 4386 }, { 5095, 4386 } } }, { "NtCompositionSetDropTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4387 }, { 5098, 4387 } } }, { "NtCreateCompositionInputSink", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5025, 4386 }, { 5086, 4387 }, { 5088, 4388 } } }, { "NtCreateCompositionSurfaceHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4992, 4384 }, { 5010, 4387 }, { 5067, 4388 }, { 5069, 4389 } } }, { "NtCreateImplicitCompositionInputSink", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5087, 4389 }, { 5089, 4390 } } }, { "NtDCompositionAddCrossDeviceVisualChild", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5033, 4385 }, { 5066, 4388 }, { 5134, 4390 }, { 5137, 4391 } } }, { "NtDCompositionAddVisualChild", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5034, 4386 }, { 5067, 4389 }, { 5135, 4391 }, { 5138, 4392 } } }, { "NtDCompositionAttachMouseWheelToHwnd", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4393 }, { 5168, 4393 } } }, { "NtDCompositionBeginFrame", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5008, 4387 }, { 5037, 4390 }, { 5105, 4392 }, { 5108, 4394 } } }, { "NtDCompositionCapturePointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5162, 4393 }, { 5164, 4395 } } }, { "NtDCompositionCommitChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5023, 4388 }, { 5052, 4391 }, { 5120, 4394 }, { 5123, 4396 } } }, { "NtDCompositionConfirmFrame", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5009, 4389 }, { 5038, 4392 }, { 5106, 4395 }, { 5109, 4397 } } }, { "NtDCompositionConnectPipe", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5050, 4390 }, { 5088, 4393 }, { 5155, 4396 }, { 5157, 4398 } } }, { "NtDCompositionCreateAndBindSharedSection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5085, 4394 }, { 5152, 4397 }, { 5154, 4399 } } }, { "NtDCompositionCreateChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5044, 4391 }, { 5080, 4395 }, { 5148, 4398 }, { 5151, 4400 } } }, { "NtDCompositionCreateConnection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5048, 4396 }, { 5116, 4399 }, { 5119, 4401 } } }, { "NtDCompositionCreateConnectionContext", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5019, 4392 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtDCompositionCreateDwmChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5043, 4393 }, { 5079, 4397 }, { 5147, 4400 }, { 5150, 4402 } } }, { "NtDCompositionCreateResource", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5042, 4394 }, { 5076, 4398 }, { 5144, 4401 }, { 5147, 4403 } } }, { "NtDCompositionCurrentBatchId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5029, 4395 }, { 5062, 4399 }, { 5130, 4402 }, { 5133, 4404 } } }, { "NtDCompositionDestroyChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5020, 4396 }, { 5049, 4400 }, { 5117, 4403 }, { 5120, 4405 } } }, { "NtDCompositionDestroyConnection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5043, 4401 }, { 5111, 4404 }, { 5114, 4406 } } }, { "NtDCompositionDestroyConnectionContext", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5014, 4397 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtDCompositionDiscardFrame", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5011, 4398 }, { 5040, 4402 }, { 5108, 4405 }, { 5111, 4407 } } }, { "NtDCompositionDuplicateHandleToProcess", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5090, 4403 }, { 5158, 4406 }, { 5160, 4408 } } }, { "NtDCompositionDuplicateSwapchainHandleToDwm", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5165, 4407 }, { 5167, 4409 } } }, { "NtDCompositionDwmSyncFlush", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5046, 4399 }, { 5082, 4404 }, { -1, -1 }, { -1, -1 } } }, { "NtDCompositionEnableDDASupport", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5085, 4408 }, { 5087, 4410 } } }, { "NtDCompositionEnableMMCSS", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5083, 4409 }, { 5085, 4411 } } }, { "NtDCompositionGetAnimationTime", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5160, 4410 }, { 5162, 4412 } } }, { "NtDCompositionGetChannels", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5049, 4400 }, { 5087, 4405 }, { 5154, 4411 }, { 5156, 4413 } } }, { "NtDCompositionGetConnectionBatch", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5044, 4406 }, { 5112, 4412 }, { 5115, 4414 } } }, { "NtDCompositionGetConnectionContextBatch", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5015, 4401 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtDCompositionGetDeletedResources", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5017, 4402 }, { 5046, 4407 }, { 5114, 4413 }, { 5117, 4415 } } }, { "NtDCompositionGetFrameLegacyTokens", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5013, 4403 }, { 5042, 4408 }, { 5110, 4414 }, { 5113, 4416 } } }, { "NtDCompositionGetFrameStatistics", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5016, 4404 }, { 5045, 4409 }, { 5113, 4415 }, { 5116, 4417 } } }, { "NtDCompositionGetFrameSurfaceUpdates", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5012, 4405 }, { 5041, 4410 }, { 5109, 4416 }, { 5112, 4418 } } }, { "NtDCompositionOpenSharedResource", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5077, 4411 }, { 5145, 4417 }, { 5148, 4419 } } }, { "NtDCompositionOpenSharedResourceHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5078, 4412 }, { 5146, 4418 }, { 5149, 4420 } } }, { "NtDCompositionReferenceSharedResourceOnDwmChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5083, 4413 }, { 5150, 4419 }, { 5153, 4421 } } }, { "NtDCompositionRegisterThumbnailVisual", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5089, 4414 }, { 5156, 4420 }, { 5158, 4422 } } }, { "NtDCompositionRegisterVirtualDesktopVisual", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5157, 4421 }, { 5159, 4423 } } }, { "NtDCompositionReleaseAllResources", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5021, 4406 }, { 5050, 4415 }, { 5118, 4422 }, { 5121, 4424 } } }, { "NtDCompositionReleaseResource", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5030, 4407 }, { 5063, 4416 }, { 5131, 4423 }, { 5134, 4425 } } }, { "NtDCompositionRemoveCrossDeviceVisualChild", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5031, 4408 }, { 5064, 4417 }, { 5132, 4424 }, { 5135, 4426 } } }, { "NtDCompositionRemoveVisualChild", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5032, 4409 }, { 5065, 4418 }, { 5133, 4425 }, { 5136, 4427 } } }, { "NtDCompositionReplaceVisualChildren", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5035, 4410 }, { 5068, 4419 }, { 5136, 4426 }, { 5139, 4428 } } }, { "NtDCompositionRetireFrame", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5010, 4411 }, { 5039, 4420 }, { 5107, 4427 }, { 5110, 4429 } } }, { "NtDCompositionSetChannelCallbackId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5163, 4428 }, { 5165, 4430 } } }, { "NtDCompositionSetChannelCommitCompletionEvent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5025, 4412 }, { 5054, 4421 }, { 5122, 4429 }, { 5125, 4431 } } }, { "NtDCompositionSetDebugCounter", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5086, 4422 }, { 5153, 4430 }, { 5155, 4432 } } }, { "NtDCompositionSetResourceAnimationProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5036, 4413 }, { 5069, 4423 }, { 5137, 4431 }, { 5140, 4433 } } }, { "NtDCompositionSetResourceBufferProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5039, 4414 }, { 5072, 4424 }, { 5140, 4432 }, { 5143, 4434 } } }, { "NtDCompositionSetResourceCallbackId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5164, 4433 }, { 5166, 4435 } } }, { "NtDCompositionSetResourceDeletedNotificationTag", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5018, 4415 }, { 5047, 4425 }, { 5115, 4434 }, { 5118, 4436 } } }, { "NtDCompositionSetResourceFloatProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5041, 4416 }, { 5074, 4426 }, { 5142, 4435 }, { 5145, 4437 } } }, { "NtDCompositionSetResourceHandleProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5075, 4427 }, { 5143, 4436 }, { 5146, 4438 } } }, { "NtDCompositionSetResourceIntegerProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5040, 4417 }, { 5073, 4428 }, { 5141, 4437 }, { 5144, 4439 } } }, { "NtDCompositionSetResourceReferenceArrayProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5037, 4418 }, { 5070, 4429 }, { 5138, 4438 }, { 5141, 4440 } } }, { "NtDCompositionSetResourceReferenceProperty", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5038, 4419 }, { 5071, 4430 }, { 5139, 4439 }, { 5142, 4441 } } }, { "NtDCompositionSetVisualInputSink", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5159, 4440 }, { 5161, 4442 } } }, { "NtDCompositionSignalGpuFence", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5048, 4420 }, { 5084, 4431 }, { 5151, 4441 }, { -1, -1 } } }, { "NtDCompositionSubmitDWMBatch", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5022, 4421 }, { 5051, 4432 }, { 5119, 4442 }, { 5122, 4443 } } }, { "NtDCompositionSynchronize", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5045, 4422 }, { 5081, 4433 }, { 5149, 4443 }, { 5152, 4444 } } }, { "NtDCompositionTelemetryAnimationScenarioBegin", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5059, 4434 }, { 5127, 4444 }, { 5130, 4445 } } }, { "NtDCompositionTelemetryAnimationScenarioReference", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5060, 4435 }, { 5128, 4445 }, { 5131, 4446 } } }, { "NtDCompositionTelemetryAnimationScenarioUnreference", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5061, 4436 }, { 5129, 4446 }, { 5132, 4447 } } }, { "NtDCompositionTelemetrySetApplicationId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5058, 4437 }, { 5126, 4447 }, { 5129, 4448 } } }, { "NtDCompositionTelemetryTouchInteractionBegin", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5026, 4423 }, { 5055, 4438 }, { 5123, 4448 }, { 5126, 4449 } } }, { "NtDCompositionTelemetryTouchInteractionEnd", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5028, 4424 }, { 5057, 4439 }, { 5125, 4449 }, { 5128, 4450 } } }, { "NtDCompositionTelemetryTouchInteractionUpdate", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5027, 4425 }, { 5056, 4440 }, { 5124, 4450 }, { 5127, 4451 } } }, { "NtDCompositionUpdatePointerCapture", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5161, 4451 }, { 5163, 4452 } } }, { "NtDCompositionValidateAndReferenceSystemVisualForHwndTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5047, 4426 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtDCompositionWaitForChannel", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5024, 4427 }, { 5053, 4441 }, { 5121, 4452 }, { 5124, 4453 } } }, { "NtDesktopCaptureBits", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5082, 4453 }, { 5084, 4454 } } }, { "NtDuplicateCompositionInputSink", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5026, 4442 }, { 5088, 4454 }, { 5090, 4455 } } }, { "NtGdiAbortDoc", { 4096, { 4096, 4391 }, { 4096, 4392 }, { 4096, 4383 }, { 4412, 4428 }, { 4414, 4443 }, { 4415, 4455 }, { 4417, 4456 } } }, { "NtGdiAbortPath", { 4097, { 4097, -1 }, { 4097, 4393 }, { 4097, 4384 }, { 4411, 4429 }, { 4413, 4444 }, { 4414, 4456 }, { 4416, 4457 } } }, { "NtGdiAddEmbFontToDC", { 4310, { 4309, 4393 }, { 4318, 4394 }, { 4320, 4385 }, { 4186, 4430 }, { 4187, 4445 }, { 4188, 4457 }, { 4188, 4458 } } }, { "NtGdiAddFontMemResourceEx", { 4100, { 4100, -1 }, { 4100, 4375 }, { 4100, 4368 }, { 4408, 4368 }, { 4410, 4369 }, { 4411, 4370 }, { 4413, 4370 } } }, { "NtGdiAddFontResourceW", { 4098, { 4098, -1 }, { 4098, 4395 }, { 4098, 4386 }, { 4410, 4431 }, { 4412, 4446 }, { 4413, 4458 }, { 4415, 4459 } } }, { "NtGdiAddRemoteFontToDC", { 4099, { 4099, 4395 }, { 4099, 4396 }, { 4099, 4387 }, { 4409, 4432 }, { 4411, 4447 }, { 4412, 4459 }, { 4414, 4460 } } }, { "NtGdiAddRemoteMMInstanceToDC", { 4102, { 4102, 4396 }, { 4102, 4397 }, { 4102, 4388 }, { 4406, 4433 }, { 4408, 4448 }, { 4409, 4460 }, { 4411, 4461 } } }, { "NtGdiAlphaBlend", { 4103, { 4103, -1 }, { 4103, 4222 }, { 4103, 4220 }, { 4405, 4220 }, { 4407, 4221 }, { 4408, 4222 }, { 4410, 4222 } } }, { "NtGdiAngleArc", { 4104, { 4104, -1 }, { 4104, 4398 }, { 4104, 4389 }, { 4404, 4434 }, { 4406, 4449 }, { 4407, 4461 }, { 4409, 4462 } } }, { "NtGdiAnyLinkedFonts", { 4105, { 4105, 4398 }, { 4105, 4399 }, { 4105, 4390 }, { 4403, 4435 }, { 4405, 4450 }, { 4406, 4462 }, { 4408, 4463 } } }, { "NtGdiArcInternal", { 4107, { 4107, -1 }, { 4107, 4400 }, { 4107, 4391 }, { 4401, 4436 }, { 4403, 4451 }, { 4404, 4463 }, { 4406, 4464 } } }, { "NtGdiBeginGdiRendering", { -1, { -1, -1 }, { -1, -1 }, { 4108, 4397 }, { 4400, 4442 }, { 4402, 4457 }, { 4403, 4469 }, { 4405, 4470 } } }, { "NtGdiBeginPath", { 4108, { 4108, 4367 }, { 4108, 4368 }, { 4109, 4361 }, { 4399, 4361 }, { 4401, 4362 }, { 4402, 4363 }, { 4404, 4363 } } }, { "NtGdiBitBlt", { 4109, { 4109, -1 }, { 4109, 4104 }, { 4110, 4104 }, { 4398, 4105 }, { 4400, 4106 }, { 4401, 4107 }, { 4403, 4107 } } }, { "NtGdiBRUSHOBJ_DeleteRbrush", { 4760, { 4756, 4400 }, { 4793, 4401 }, { 4825, 4392 }, { 4865, 4437 }, { 4874, 4452 }, { 4886, 4464 }, { 4887, 4465 } } }, { "NtGdiBRUSHOBJ_hGetColorTransform", { 4733, { 4729, 4401 }, { 4766, 4402 }, { 4798, 4393 }, { 4835, 4438 }, { 4844, 4453 }, { 4856, 4465 }, { 4857, 4466 } } }, { "NtGdiBRUSHOBJ_pvAllocRbrush", { 4731, { 4727, 4402 }, { 4764, 4403 }, { 4796, 4394 }, { 4837, 4439 }, { 4846, 4454 }, { 4858, 4466 }, { 4859, 4467 } } }, { "NtGdiBRUSHOBJ_pvGetRbrush", { 4732, { 4728, 4403 }, { 4765, 4404 }, { 4797, 4395 }, { 4836, 4440 }, { 4845, 4455 }, { 4857, 4467 }, { 4858, 4468 } } }, { "NtGdiBRUSHOBJ_ulGetBrushColor", { 4730, { 4726, -1 }, { 4763, 4405 }, { 4795, 4396 }, { 4838, 4441 }, { 4847, 4456 }, { 4859, 4468 }, { 4860, 4469 } } }, { "NtGdiCancelDC", { 4110, { 4110, 4408 }, { 4110, 4409 }, { 4111, 4401 }, { 4397, 4446 }, { 4399, 4461 }, { 4400, 4473 }, { 4402, 4474 } } }, { "NtGdiChangeGhostFont", { 4309, { 4308, 4409 }, { 4317, 4410 }, { 4319, 4402 }, { 4187, 4447 }, { 4188, 4462 }, { 4189, 4474 }, { 4189, 4475 } } }, { "NtGdiCheckBitmapBits", { 4111, { 4111, -1 }, { 4111, 4411 }, { 4112, 4403 }, { 4396, 4448 }, { 4398, 4463 }, { 4399, 4475 }, { 4401, 4476 } } }, { "NtGdiClearBitmapAttributes", { 4113, { 4113, 4411 }, { 4113, 4412 }, { 4114, 4404 }, { 4394, 4449 }, { 4396, 4464 }, { 4397, 4476 }, { 4399, 4477 } } }, { "NtGdiClearBrushAttributes", { 4114, { 4361, 4412 }, { 4114, 4413 }, { 4405, 4405 }, { 4393, 4450 }, { 4395, 4465 }, { 4396, 4477 }, { 4398, 4478 } } }, { "NtGdiCLIPOBJ_bEnum", { 4724, { 4720, 4405 }, { 4757, 4406 }, { 4789, 4398 }, { 4834, 4443 }, { 4843, 4458 }, { 4855, 4470 }, { 4856, 4471 } } }, { "NtGdiCLIPOBJ_cEnumStart", { 4725, { 4721, -1 }, { 4758, 4407 }, { 4790, 4399 }, { 4833, 4444 }, { 4842, 4459 }, { 4854, 4471 }, { 4855, 4472 } } }, { "NtGdiCLIPOBJ_ppoGetPath", { 4726, { 4722, 4407 }, { 4759, 4408 }, { 4791, 4400 }, { 4832, 4445 }, { 4841, 4460 }, { 4853, 4472 }, { 4854, 4473 } } }, { "NtGdiCloseFigure", { 4112, { 4112, -1 }, { 4112, 4358 }, { 4113, 4352 }, { 4395, 4352 }, { 4397, 4353 }, { 4398, 4354 }, { 4400, 4354 } } }, { "NtGdiColorCorrectPalette", { 4115, { 4115, -1 }, { 4115, 4414 }, { 4116, 4406 }, { 4392, 4451 }, { 4394, 4466 }, { 4395, 4478 }, { 4397, 4479 } } }, { "NtGdiCombineRgn", { 4116, { 4116, 4147 }, { 4116, 4148 }, { 4117, 4148 }, { 4391, 4149 }, { 4393, 4150 }, { 4394, 4151 }, { 4396, 4151 } } }, { "NtGdiCombineTransform", { 4117, { 4117, 4340 }, { 4117, 4341 }, { 4118, 4336 }, { 4390, 4336 }, { 4392, 4337 }, { 4393, 4338 }, { 4395, 4338 } } }, { "NtGdiComputeXformCoefficients", { 4118, { 4118, 4236 }, { 4118, 4237 }, { 4119, 4235 }, { 4389, 4235 }, { 4391, 4236 }, { 4392, 4237 }, { 4394, 4237 } } }, { "NtGdiConfigureOPMProtectedOutput", { -1, { -1, -1 }, { 4119, 4415 }, { 4120, 4407 }, { 4388, 4452 }, { 4390, 4467 }, { 4391, 4479 }, { 4393, 4480 } } }, { "NtGdiConsoleTextOut", { 4119, { 4119, 4205 }, { 4120, 4206 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiConvertMetafileRect", { 4120, { 4120, 4414 }, { 4121, 4416 }, { 4121, 4408 }, { 4387, 4453 }, { 4389, 4468 }, { 4390, 4480 }, { 4392, 4481 } } }, { "NtGdiCreateBitmap", { 4121, { 4121, -1 }, { 4122, 4205 }, { 4122, 4205 }, { 4386, 4205 }, { 4388, 4206 }, { 4389, 4207 }, { 4391, 4207 } } }, { "NtGdiCreateBitmapFromDxSurface", { -1, { -1, -1 }, { -1, -1 }, { 4123, 4409 }, { 4385, 4454 }, { 4387, 4469 }, { 4388, 4481 }, { 4390, 4482 } } }, { "NtGdiCreateBitmapFromDxSurface2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4384, 4455 }, { 4386, 4470 }, { 4387, 4482 }, { 4389, 4483 } } }, { "NtGdiCreateClientObj", { 4122, { 4122, 4286 }, { 4123, 4287 }, { 4124, 4282 }, { 4383, 4282 }, { 4385, 4283 }, { 4386, 4284 }, { 4388, 4284 } } }, { "NtGdiCreateColorSpace", { 4123, { 4123, 4388 }, { 4124, 4389 }, { 4125, 4380 }, { 4382, 4380 }, { 4384, 4381 }, { 4385, 4382 }, { 4387, 4382 } } }, { "NtGdiCreateColorTransform", { 4124, { 4124, -1 }, { 4125, 4417 }, { 4126, 4410 }, { 4381, 4456 }, { 4383, 4471 }, { 4384, 4483 }, { 4386, 4484 } } }, { "NtGdiCreateCompatibleBitmap", { 4125, { 4125, 4170 }, { 4126, 4171 }, { 4127, 4171 }, { 4380, 4172 }, { 4382, 4173 }, { 4383, 4174 }, { 4385, 4174 } } }, { "NtGdiCreateCompatibleDC", { 4126, { 4126, 4180 }, { 4127, 4181 }, { 4128, 4181 }, { 4379, 4181 }, { 4381, 4182 }, { 4382, 4183 }, { 4384, 4183 } } }, { "NtGdiCreateDIBBrush", { 4127, { 4127, -1 }, { 4128, 4214 }, { 4129, 4212 }, { 4378, 4212 }, { 4380, 4213 }, { 4381, 4214 }, { 4383, 4214 } } }, { "NtGdiCreateDIBitmapInternal", { 4128, { 4128, -1 }, { 4129, 4257 }, { 4130, 4255 }, { 4377, 4255 }, { 4379, 4256 }, { 4380, 4257 }, { 4382, 4257 } } }, { "NtGdiCreateDIBSection", { 4129, { 4129, -1 }, { 4130, 4252 }, { 4131, 4250 }, { 4376, 4250 }, { 4378, 4251 }, { 4379, 4252 }, { 4381, 4252 } } }, { "NtGdiCreateEllipticRgn", { 4130, { 4130, 4416 }, { 4131, 4418 }, { 4132, 4411 }, { 4374, 4457 }, { 4376, 4472 }, { 4377, 4484 }, { 4379, 4485 } } }, { "NtGdiCreateHalftonePalette", { 4131, { 4131, 4337 }, { 4132, 4338 }, { 4133, 4333 }, { 4373, 4333 }, { 4375, 4334 }, { 4376, 4335 }, { 4378, 4335 } } }, { "NtGdiCreateHatchBrushInternal", { 4132, { 4132, -1 }, { 4133, 4419 }, { 4134, 4412 }, { 4372, 4458 }, { 4374, 4473 }, { 4375, 4485 }, { 4377, 4486 } } }, { "NtGdiCreateMetafileDC", { 4133, { 4133, -1 }, { 4134, 4420 }, { 4135, 4413 }, { 4371, 4459 }, { 4373, 4474 }, { 4374, 4486 }, { 4376, 4487 } } }, { "NtGdiCreateOPMProtectedOutputs", { -1, { -1, -1 }, { 4135, 4421 }, { 4136, 4414 }, { 4370, 4460 }, { 4372, 4475 }, { 4373, 4487 }, { 4375, 4488 } } }, { "NtGdiCreatePaletteInternal", { 4134, { 4134, 4272 }, { 4136, 4273 }, { 4137, 4268 }, { 4369, 4268 }, { 4371, 4269 }, { 4372, 4270 }, { 4374, 4270 } } }, { "NtGdiCreatePatternBrushInternal", { 4135, { 4135, 4277 }, { 4137, 4278 }, { 4138, 4273 }, { 4368, 4273 }, { 4370, 4274 }, { 4371, 4275 }, { 4373, 4275 } } }, { "NtGdiCreatePen", { 4136, { 4136, 4182 }, { 4138, 4183 }, { 4139, 4183 }, { 4367, 4183 }, { 4369, 4184 }, { 4370, 4185 }, { 4372, 4185 } } }, { "NtGdiCreateRectRgn", { 4137, { 4137, 4229 }, { 4139, 4230 }, { 4140, 4228 }, { 4366, 4228 }, { 4368, 4229 }, { 4369, 4230 }, { 4371, 4230 } } }, { "NtGdiCreateRoundRectRgn", { 4138, { 4138, -1 }, { 4140, 4422 }, { 4141, 4415 }, { 4365, 4461 }, { 4367, 4476 }, { 4368, 4488 }, { 4370, 4489 } } }, { "NtGdiCreateServerMetaFile", { 4139, { 4139, -1 }, { 4141, 4423 }, { 4142, 4416 }, { 4364, 4462 }, { 4366, 4477 }, { 4367, 4489 }, { 4369, 4490 } } }, { "NtGdiCreateSessionMappedDIBSection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4375, 4463 }, { 4377, 4478 }, { 4378, 4490 }, { 4380, 4491 } } }, { "NtGdiCreateSolidBrush", { 4140, { 4140, 4284 }, { 4142, 4285 }, { 4143, 4280 }, { 4363, 4280 }, { 4365, 4281 }, { 4366, 4282 }, { 4368, 4282 } } }, { "NtGdiD3dContextCreate", { 4141, { 4141, 4421 }, { 4143, 4424 }, { 4144, 4417 }, { 4362, 4464 }, { 4364, 4479 }, { 4365, 4491 }, { 4367, 4492 } } }, { "NtGdiD3dContextDestroy", { 4142, { 4142, 4422 }, { 4144, 4425 }, { 4145, 4418 }, { 4339, 4465 }, { 4341, 4480 }, { 4364, 4492 }, { 4366, 4493 } } }, { "NtGdiD3dContextDestroyAll", { 4143, { 4143, 4423 }, { 4145, 4426 }, { 4146, 4419 }, { 4342, 4466 }, { 4344, 4481 }, { 4363, 4493 }, { 4365, 4494 } } }, { "NtGdiD3dDrawPrimitives2", { 4145, { 4145, -1 }, { 4147, 4197 }, { 4148, 4197 }, { 4358, 4197 }, { 4360, 4198 }, { 4361, 4199 }, { 4363, 4199 } } }, { "NtGdiD3dValidateTextureStageState", { 4144, { 4144, 4424 }, { 4146, 4427 }, { 4147, 4420 }, { 4357, 4467 }, { 4359, 4482 }, { 4362, 4494 }, { 4364, 4495 } } }, { "NtGdiDdAddAttachedSurface", { 4147, { 4147, 4425 }, { 4149, 4434 }, { 4150, 4427 }, { 4331, 4474 }, { 4333, 4489 }, { 4359, 4501 }, { 4361, 4502 } } }, { "NtGdiDdAlphaBlt", { 4148, { 4148, 4426 }, { 4150, 4435 }, { 4151, 4428 }, { 4312, 4475 }, { 4314, 4490 }, { 4358, 4502 }, { 4360, 4503 } } }, { "NtGdiDdAttachSurface", { 4149, { 4149, 4427 }, { 4151, 4436 }, { 4152, 4429 }, { 4321, 4476 }, { 4323, 4491 }, { 4357, 4503 }, { 4359, 4504 } } }, { "NtGdiDdBeginMoCompFrame", { 4150, { 4150, 4428 }, { 4152, 4437 }, { 4153, 4430 }, { 4310, 4477 }, { 4312, 4492 }, { 4356, 4504 }, { 4358, 4505 } } }, { "NtGdiDdBlt", { 4151, { 4151, 4222 }, { 4153, 4223 }, { 4154, 4221 }, { 4314, 4221 }, { 4316, 4222 }, { 4355, 4223 }, { 4357, 4223 } } }, { "NtGdiDdCanCreateD3DBuffer", { 4153, { 4153, 4429 }, { 4155, 4438 }, { 4156, 4431 }, { 4334, 4478 }, { 4336, 4493 }, { 4353, 4505 }, { 4355, 4506 } } }, { "NtGdiDdCanCreateSurface", { 4152, { 4152, 4262 }, { 4154, 4263 }, { 4155, 4258 }, { 4353, 4258 }, { 4355, 4259 }, { 4354, 4260 }, { 4356, 4260 } } }, { "NtGdiDDCCIGetCapabilitiesString", { -1, { -1, -1 }, { 4864, 4428 }, { 4908, 4421 }, { 4975, 4468 }, { 4993, 4483 }, { 5050, 4495 }, { 5052, 4496 } } }, { "NtGdiDDCCIGetCapabilitiesStringLength", { -1, { -1, -1 }, { 4863, 4429 }, { 4907, 4422 }, { 4976, 4469 }, { 4994, 4484 }, { 5051, 4496 }, { 5053, 4497 } } }, { "NtGdiDDCCIGetTimingReport", { -1, { -1, -1 }, { 4865, 4430 }, { 4909, 4423 }, { 4974, 4470 }, { 4992, 4485 }, { 5049, 4497 }, { 5051, 4498 } } }, { "NtGdiDDCCIGetVCPFeature", { -1, { -1, -1 }, { 4860, 4431 }, { 4904, 4424 }, { 4979, 4471 }, { 4997, 4486 }, { 5054, 4498 }, { 5056, 4499 } } }, { "NtGdiDDCCISaveCurrentSettings", { -1, { -1, -1 }, { 4862, 4432 }, { 4906, 4425 }, { 4977, 4472 }, { 4995, 4487 }, { 5052, 4499 }, { 5054, 4500 } } }, { "NtGdiDDCCISetVCPFeature", { -1, { -1, -1 }, { 4861, 4433 }, { 4905, 4426 }, { 4978, 4473 }, { 4996, 4488 }, { 5053, 4500 }, { 5055, 4501 } } }, { "NtGdiDdColorControl", { 4154, { 4154, 4430 }, { 4156, 4439 }, { 4157, 4432 }, { 4296, 4479 }, { 4298, 4494 }, { 4352, 4506 }, { 4354, 4507 } } }, { "NtGdiDdCreateD3DBuffer", { 4157, { 4157, -1 }, { 4159, 4440 }, { 4160, 4433 }, { 4346, 4480 }, { 4348, 4495 }, { 4349, 4507 }, { 4351, 4508 } } }, { "NtGdiDdCreateDirectDrawObject", { 4155, { 4155, 4432 }, { 4157, 4441 }, { 4158, 4434 }, { 4361, 4481 }, { 4363, 4496 }, { 4351, 4508 }, { 4353, 4509 } } }, { "NtGdiDdCreateFullscreenSprite", { -1, { -1, -1 }, { -1, -1 }, { 4910, 4435 }, { 4983, 4482 }, { 5001, 4497 }, { 5058, 4509 }, { 5060, 4510 } } }, { "NtGdiDdCreateMoComp", { 4158, { 4158, 4433 }, { 4160, 4442 }, { 4161, 4436 }, { 4305, 4483 }, { 4307, 4498 }, { 4348, 4510 }, { 4350, 4511 } } }, { "NtGdiDdCreateSurface", { 4156, { 4156, -1 }, { 4158, 4264 }, { 4159, 4259 }, { 4347, 4259 }, { 4349, 4260 }, { 4350, 4261 }, { 4352, 4261 } } }, { "NtGdiDdCreateSurfaceEx", { 4190, { 4190, 4294 }, { 4192, 4295 }, { 4193, 4290 }, { 4313, 4290 }, { 4315, 4291 }, { 4316, 4292 }, { 4318, 4292 } } }, { "NtGdiDdCreateSurfaceObject", { 4159, { 4159, -1 }, { 4161, 4296 }, { 4162, 4291 }, { 4344, 4291 }, { 4346, 4292 }, { 4347, 4293 }, { 4349, 4293 } } }, { "NtGdiDdDDIAbandonSwapChain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5032, 4511 }, { 5032, 4512 } } }, { "NtGdiDdDDIAcquireKeyedMutex", { -1, { -1, -1 }, { -1, -1 }, { 4892, 4437 }, { 4947, 4484 }, { 4956, 4499 }, { 4972, 4512 }, { 4973, 4513 } } }, { "NtGdiDdDDIAcquireKeyedMutex2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4932, 4485 }, { 4941, 4500 }, { 4957, 4513 }, { 4958, 4514 } } }, { "NtGdiDdDDIAcquireSwapChain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5030, 4514 }, { 5030, 4515 } } }, { "NtGdiDdDDIAdjustFullscreenGamma", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5040, 4515 }, { 5040, 4516 } } }, { "NtGdiDdDDICacheHybridQueryValue", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4980, 4501 }, { 5017, 4516 }, { 5018, 4517 } } }, { "NtGdiDdDDIChangeVideoMemoryReservation", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5026, 4517 }, { 5026, 4518 } } }, { "NtGdiDdDDICheckExclusiveOwnership", { -1, { -1, -1 }, { 4850, 4443 }, { 4885, 4438 }, { 4954, 4486 }, { 4963, 4502 }, { 4979, 4518 }, { 4980, 4519 } } }, { "NtGdiDdDDICheckMonitorPowerState", { -1, { -1, -1 }, { 4849, 4444 }, { 4884, 4439 }, { 4955, 4487 }, { 4964, 4503 }, { 4980, 4519 }, { 4981, 4520 } } }, { "NtGdiDdDDICheckMultiPlaneOverlaySupport", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4978, 4504 }, { 4996, 4520 }, { 4997, 4521 } } }, { "NtGdiDdDDICheckMultiPlaneOverlaySupport2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5034, 4521 }, { 5034, 4522 } } }, { "NtGdiDdDDICheckOcclusion", { -1, { -1, -1 }, { 4847, 4445 }, { 4882, 4440 }, { 4957, 4488 }, { 4966, 4505 }, { 4982, 4522 }, { 4983, 4523 } } }, { "NtGdiDdDDICheckSharedResourceAccess", { -1, { -1, -1 }, { -1, -1 }, { 4897, 4441 }, { 4942, 4489 }, { 4951, 4506 }, { 4967, 4523 }, { 4968, 4524 } } }, { "NtGdiDdDDICheckVidPnExclusiveOwnership", { -1, { -1, -1 }, { -1, -1 }, { 4896, 4442 }, { 4943, 4490 }, { 4952, 4507 }, { 4968, 4524 }, { 4969, 4525 } } }, { "NtGdiDdDDICloseAdapter", { -1, { -1, -1 }, { 4823, 4446 }, { 4857, 4443 }, { 4894, 4491 }, { 4903, 4508 }, { 4915, 4525 }, { 4916, 4526 } } }, { "NtGdiDdDDIConfigureSharedResource", { -1, { -1, -1 }, { -1, -1 }, { 4894, 4444 }, { 4945, 4492 }, { 4954, 4509 }, { 4970, 4526 }, { 4971, 4527 } } }, { "NtGdiDdDDICreateAllocation", { -1, { -1, -1 }, { 4798, 4447 }, { 4831, 4445 }, { 4927, 4493 }, { 4936, 4510 }, { 4952, 4527 }, { 4953, 4528 } } }, { "NtGdiDdDDICreateContext", { -1, { -1, -1 }, { 4806, 4448 }, { 4839, 4446 }, { 4914, 4494 }, { 4923, 4511 }, { 4936, 4528 }, { 4937, 4529 } } }, { "NtGdiDdDDICreateContextVirtual", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5014, 4529 }, { 5015, 4530 } } }, { "NtGdiDdDDICreateDCFromMemory", { -1, { -1, -1 }, { 4836, 4449 }, { 4871, 4447 }, { 4879, 4495 }, { 4888, 4512 }, { 4900, 4530 }, { 4901, 4531 } } }, { "NtGdiDdDDICreateDevice", { -1, { -1, -1 }, { 4804, 4450 }, { 4837, 4448 }, { 4916, 4496 }, { 4925, 4513 }, { 4938, 4531 }, { 4939, 4532 } } }, { "NtGdiDdDDICreateKeyedMutex", { -1, { -1, -1 }, { -1, -1 }, { 4889, 4449 }, { 4950, 4497 }, { 4959, 4514 }, { 4975, 4532 }, { 4976, 4533 } } }, { "NtGdiDdDDICreateKeyedMutex2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4934, 4498 }, { 4943, 4515 }, { 4959, 4533 }, { 4960, 4534 } } }, { "NtGdiDdDDICreateOutputDupl", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4939, 4499 }, { 4948, 4516 }, { 4964, 4534 }, { 4965, 4535 } } }, { "NtGdiDdDDICreateOverlay", { -1, { -1, -1 }, { 4829, 4451 }, { 4864, 4450 }, { 4886, 4500 }, { 4895, 4517 }, { 4907, 4535 }, { 4908, 4536 } } }, { "NtGdiDdDDICreatePagingQueue", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5004, 4536 }, { 5005, 4537 } } }, { "NtGdiDdDDICreateSwapChain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5027, 4537 }, { 5027, 4538 } } }, { "NtGdiDdDDICreateSynchronizationObject", { -1, { -1, -1 }, { 4808, 4452 }, { 4841, 4451 }, { 4912, 4501 }, { 4921, 4518 }, { 4934, 4538 }, { 4935, 4539 } } }, { "NtGdiDdDDIDestroyAllocation", { -1, { -1, -1 }, { 4801, 4453 }, { 4834, 4452 }, { 4919, 4502 }, { 4928, 4519 }, { 4941, 4539 }, { 4942, 4540 } } }, { "NtGdiDdDDIDestroyAllocation2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4942, 4540 }, { 4943, 4541 } } }, { "NtGdiDdDDIDestroyContext", { -1, { -1, -1 }, { 4807, 4454 }, { 4840, 4453 }, { 4913, 4503 }, { 4922, 4520 }, { 4935, 4541 }, { 4936, 4542 } } }, { "NtGdiDdDDIDestroyDCFromMemory", { -1, { -1, -1 }, { 4837, 4455 }, { 4872, 4454 }, { 4878, 4504 }, { 4887, 4521 }, { 4899, 4542 }, { 4900, 4543 } } }, { "NtGdiDdDDIDestroyDevice", { -1, { -1, -1 }, { 4805, 4456 }, { 4838, 4455 }, { 4915, 4505 }, { 4924, 4522 }, { 4937, 4543 }, { 4938, 4544 } } }, { "NtGdiDdDDIDestroyKeyedMutex", { -1, { -1, -1 }, { -1, -1 }, { 4891, 4456 }, { 4948, 4506 }, { 4957, 4523 }, { 4973, 4544 }, { 4974, 4545 } } }, { "NtGdiDdDDIDestroyOutputDupl", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4938, 4507 }, { 4947, 4524 }, { 4963, 4545 }, { 4964, 4546 } } }, { "NtGdiDdDDIDestroyOverlay", { -1, { -1, -1 }, { 4832, 4457 }, { 4867, 4457 }, { 4883, 4508 }, { 4892, 4525 }, { 4904, 4546 }, { 4905, 4547 } } }, { "NtGdiDdDDIDestroyPagingQueue", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5005, 4547 }, { 5006, 4548 } } }, { "NtGdiDdDDIDestroySynchronizationObject", { -1, { -1, -1 }, { 4809, 4458 }, { 4843, 4458 }, { 4910, 4509 }, { 4919, 4526 }, { 4932, 4548 }, { 4933, 4549 } } }, { "NtGdiDdDDIEnumAdapters", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4896, 4510 }, { 4905, 4527 }, { 4917, 4549 }, { 4918, 4550 } } }, { "NtGdiDdDDIEnumAdapters2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4918, 4550 }, { 4919, 4551 } } }, { "NtGdiDdDDIEscape", { -1, { -1, -1 }, { 4825, 4459 }, { 4859, 4459 }, { 4892, 4511 }, { 4901, 4528 }, { 4913, 4551 }, { 4914, 4552 } } }, { "NtGdiDdDDIEvict", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4998, 4552 }, { 4999, 4553 } } }, { "NtGdiDdDDIFlipOverlay", { -1, { -1, -1 }, { 4831, 4460 }, { 4866, 4460 }, { 4884, 4512 }, { 4893, 4529 }, { 4905, 4553 }, { 4906, 4554 } } }, { "NtGdiDdDDIFlushHeapTransitions", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4555 }, { 5043, 4555 } } }, { "NtGdiDdDDIFreeGpuVirtualAddress", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5012, 4554 }, { 5013, 4556 } } }, { "NtGdiDdDDIGetCachedHybridQueryValue", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4979, 4530 }, { 5016, 4555 }, { 5017, 4557 } } }, { "NtGdiDdDDIGetContextInProcessSchedulingPriority", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4965, 4513 }, { 4974, 4531 }, { 4992, 4556 }, { 4993, 4558 } } }, { "NtGdiDdDDIGetContextSchedulingPriority", { -1, { -1, -1 }, { 4839, 4461 }, { 4874, 4461 }, { 4876, 4514 }, { 4885, 4532 }, { 4897, 4557 }, { 4898, 4559 } } }, { "NtGdiDdDDIGetDeviceState", { -1, { -1, -1 }, { 4835, 4462 }, { 4870, 4462 }, { 4880, 4515 }, { 4889, 4533 }, { 4901, 4559 }, { 4902, 4561 } } }, { "NtGdiDdDDIGetDisplayModeList", { -1, { -1, -1 }, { 4816, 4463 }, { 4850, 4463 }, { 4903, 4516 }, { 4912, 4534 }, { 4925, 4560 }, { 4926, 4562 } } }, { "NtGdiDdDDIGetDWMVerticalBlankEvent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4989, 4558 }, { 4990, 4560 } } }, { "NtGdiDdDDIGetMultisampleMethodList", { -1, { -1, -1 }, { 4818, 4464 }, { 4852, 4464 }, { 4901, 4517 }, { 4910, 4535 }, { 4923, 4561 }, { 4924, 4563 } } }, { "NtGdiDdDDIGetOverlayState", { -1, { -1, -1 }, { -1, -1 }, { 4895, 4465 }, { 4944, 4518 }, { 4953, 4536 }, { 4969, 4562 }, { 4970, 4564 } } }, { "NtGdiDdDDIGetPresentHistory", { -1, { -1, -1 }, { 4828, 4465 }, { 4862, 4466 }, { 4888, 4519 }, { 4897, 4537 }, { 4909, 4563 }, { 4910, 4565 } } }, { "NtGdiDdDDIGetPresentQueueEvent", { -1, { -1, -1 }, { -1, -1 }, { 4863, 4467 }, { 4887, 4520 }, { 4896, 4538 }, { 4908, 4564 }, { 4909, 4566 } } }, { "NtGdiDdDDIGetProcessSchedulingPriorityClass", { -1, { -1, -1 }, { 4841, 4466 }, { 4876, 4468 }, { 4874, 4521 }, { 4883, 4539 }, { 4895, 4565 }, { 4896, 4567 } } }, { "NtGdiDdDDIGetResourcePresentPrivateDriverData", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5009, 4566 }, { 5010, 4568 } } }, { "NtGdiDdDDIGetRuntimeData", { -1, { -1, -1 }, { 4812, 4467 }, { 4846, 4469 }, { 4907, 4522 }, { 4916, 4540 }, { 4929, 4567 }, { 4930, 4569 } } }, { "NtGdiDdDDIGetScanLine", { -1, { -1, -1 }, { 4843, 4468 }, { 4878, 4470 }, { 4872, 4523 }, { 4881, 4541 }, { 4893, 4568 }, { 4894, 4570 } } }, { "NtGdiDdDDIGetSetSwapChainMetadata", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5029, 4569 }, { 5029, 4571 } } }, { "NtGdiDdDDIGetSharedPrimaryHandle", { -1, { -1, -1 }, { 4824, 4469 }, { 4858, 4471 }, { 4893, 4524 }, { 4902, 4542 }, { 4914, 4570 }, { 4915, 4572 } } }, { "NtGdiDdDDIGetSharedResourceAdapterLuid", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4966, 4525 }, { 4975, 4543 }, { 4993, 4571 }, { 4994, 4573 } } }, { "NtGdiDdDDIInvalidateActiveVidPn", { -1, { -1, -1 }, { 4846, 4470 }, { 4881, 4472 }, { 4958, 4526 }, { 4967, 4544 }, { 4983, 4572 }, { 4984, 4574 } } }, { "NtGdiDdDDIInvalidateCache", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5008, 4573 }, { 5009, 4575 } } }, { "NtGdiDdDDILock", { -1, { -1, -1 }, { 4814, 4471 }, { 4848, 4473 }, { 4905, 4527 }, { 4914, 4545 }, { 4927, 4574 }, { 4928, 4576 } } }, { "NtGdiDdDDILock2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5006, 4575 }, { 5007, 4577 } } }, { "NtGdiDdDDIMakeResident", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4997, 4576 }, { 4998, 4578 } } }, { "NtGdiDdDDIMapGpuVirtualAddress", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5010, 4577 }, { 5011, 4579 } } }, { "NtGdiDdDDIMarkDeviceAsError", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5042, 4578 }, { 5042, 4580 } } }, { "NtGdiDdDDINetDispGetNextChunkInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4981, 4546 }, { 5018, 4579 }, { 5019, 4581 } } }, { "NtGdiDdDDINetDispQueryMiracastDisplayDeviceStatus", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4985, 4547 }, { 5023, 4580 }, { 5023, 4582 } } }, { "NtGdiDdDDINetDispQueryMiracastDisplayDeviceSupport", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4982, 4548 }, { 5019, 4581 }, { 5020, 4583 } } }, { "NtGdiDdDDINetDispStartMiracastDisplayDevice", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4983, 4549 }, { 5020, 4582 }, { 5021, 4584 } } }, { "NtGdiDdDDINetDispStartMiracastDisplayDeviceEx", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5021, 4583 }, { -1, -1 } } }, { "NtGdiDdDDINetDispStopMiracastDisplayDevice", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4984, 4550 }, { 5022, 4584 }, { 5022, 4585 } } }, { "NtGdiDdDDINetDispStopSessions", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5024, 4585 }, { 5024, 4586 } } }, { "NtGdiDdDDIOfferAllocations", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4941, 4528 }, { 4950, 4551 }, { 4966, 4586 }, { 4967, 4587 } } }, { "NtGdiDdDDIOpenAdapterFromDeviceName", { -1, { -1, -1 }, { 4821, 4472 }, { 4855, 4474 }, { 4898, 4529 }, { 4907, 4552 }, { 4920, 4587 }, { 4921, 4588 } } }, { "NtGdiDdDDIOpenAdapterFromHdc", { -1, { -1, -1 }, { 4822, 4473 }, { 4856, 4475 }, { 4897, 4530 }, { 4906, 4553 }, { 4919, 4588 }, { 4920, 4589 } } }, { "NtGdiDdDDIOpenAdapterFromLuid", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4895, 4531 }, { 4904, 4554 }, { 4916, 4589 }, { 4917, 4590 } } }, { "NtGdiDdDDIOpenKeyedMutex", { -1, { -1, -1 }, { -1, -1 }, { 4890, 4476 }, { 4949, 4532 }, { 4958, 4555 }, { 4974, 4590 }, { 4975, 4591 } } }, { "NtGdiDdDDIOpenKeyedMutex2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4933, 4533 }, { 4942, 4556 }, { 4958, 4591 }, { 4959, 4592 } } }, { "NtGdiDdDDIOpenNtHandleFromName", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4923, 4534 }, { 4932, 4557 }, { 4947, 4592 }, { 4948, 4593 } } }, { "NtGdiDdDDIOpenResource", { -1, { -1, -1 }, { 4800, 4474 }, { 4833, 4477 }, { 4922, 4535 }, { 4931, 4558 }, { 4946, 4593 }, { 4947, 4594 } } }, { "NtGdiDdDDIOpenResourceFromNtHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4920, 4536 }, { 4929, 4559 }, { 4943, 4594 }, { 4944, 4595 } } }, { "NtGdiDdDDIOpenSwapChain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5028, 4595 }, { 5028, 4596 } } }, { "NtGdiDdDDIOpenSynchronizationObject", { -1, { -1, -1 }, { -1, -1 }, { 4842, 4478 }, { 4911, 4538 }, { 4920, 4561 }, { 4933, 4599 }, { 4934, 4600 } } }, { "NtGdiDdDDIOpenSyncObjectFromNtHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4921, 4537 }, { 4930, 4560 }, { 4944, 4596 }, { 4945, 4597 } } }, { "NtGdiDdDDIOpenSyncObjectFromNtHandle2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4945, 4597 }, { 4946, 4598 } } }, { "NtGdiDdDDIOpenSyncObjectNtHandleFromName", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4948, 4598 }, { 4949, 4599 } } }, { "NtGdiDdDDIOutputDuplGetFrameInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4937, 4539 }, { 4946, 4562 }, { 4962, 4600 }, { 4963, 4601 } } }, { "NtGdiDdDDIOutputDuplGetMetaData", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4936, 4540 }, { 4945, 4563 }, { 4961, 4601 }, { 4962, 4602 } } }, { "NtGdiDdDDIOutputDuplGetPointerShapeData", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4935, 4541 }, { 4944, 4564 }, { 4960, 4602 }, { 4961, 4603 } } }, { "NtGdiDdDDIOutputDuplPresent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4930, 4542 }, { 4939, 4565 }, { 4955, 4603 }, { 4956, 4604 } } }, { "NtGdiDdDDIOutputDuplReleaseFrame", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4928, 4543 }, { 4937, 4566 }, { 4953, 4604 }, { 4954, 4605 } } }, { "NtGdiDdDDIPinDirectFlipResources", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4961, 4544 }, { 4970, 4567 }, { 4986, 4605 }, { 4987, 4606 } } }, { "NtGdiDdDDIPollDisplayChildren", { -1, { -1, -1 }, { 4845, 4475 }, { 4880, 4479 }, { 4959, 4545 }, { 4968, 4568 }, { 4984, 4606 }, { 4985, 4607 } } }, { "NtGdiDdDDIPresent", { -1, { -1, -1 }, { 4819, 4476 }, { 4853, 4480 }, { 4900, 4546 }, { 4909, 4569 }, { 4922, 4607 }, { 4923, 4608 } } }, { "NtGdiDdDDIPresentMultiPlaneOverlay", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4977, 4570 }, { 4995, 4608 }, { 4996, 4609 } } }, { "NtGdiDdDDIPresentMultiPlaneOverlay2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5035, 4609 }, { 5035, 4610 } } }, { "NtGdiDdDDIQueryAdapterInfo", { -1, { -1, -1 }, { 4813, 4477 }, { 4847, 4481 }, { 4906, 4547 }, { 4915, 4571 }, { 4928, 4610 }, { 4929, 4611 } } }, { "NtGdiDdDDIQueryAllocationResidency", { -1, { -1, -1 }, { 4803, 4478 }, { 4836, 4482 }, { 4917, 4548 }, { 4926, 4572 }, { 4939, 4611 }, { 4940, 4612 } } }, { "NtGdiDdDDIQueryClockCalibration", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5038, 4612 }, { 5038, 4613 } } }, { "NtGdiDdDDIQueryRemoteVidPnSourceFromGdiDisplayName", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4929, 4549 }, { 4938, 4573 }, { 4954, 4613 }, { 4955, 4614 } } }, { "NtGdiDdDDIQueryResourceInfo", { -1, { -1, -1 }, { 4799, 4479 }, { 4832, 4483 }, { 4926, 4550 }, { 4935, 4574 }, { 4951, 4614 }, { 4952, 4615 } } }, { "NtGdiDdDDIQueryResourceInfoFromNtHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4925, 4551 }, { 4934, 4575 }, { 4950, 4615 }, { 4951, 4616 } } }, { "NtGdiDdDDIQueryStatistics", { -1, { -1, -1 }, { 4826, 4480 }, { 4860, 4484 }, { 4891, 4552 }, { 4900, 4576 }, { 4912, 4616 }, { 4913, 4617 } } }, { "NtGdiDdDDIQueryVideoMemoryInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5025, 4618 }, { 5025, 4619 } } }, { "NtGdiDdDDIQueryVidPnExclusiveOwnership", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5039, 4617 }, { 5039, 4618 } } }, { "NtGdiDdDDIReclaimAllocations", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4940, 4553 }, { 4949, 4577 }, { 4965, 4619 }, { 4966, 4620 } } }, { "NtGdiDdDDIReclaimAllocations2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5036, 4620 }, { 5036, 4621 } } }, { "NtGdiDdDDIReleaseKeyedMutex", { -1, { -1, -1 }, { -1, -1 }, { 4893, 4485 }, { 4946, 4554 }, { 4955, 4578 }, { 4971, 4621 }, { 4972, 4622 } } }, { "NtGdiDdDDIReleaseKeyedMutex2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4931, 4555 }, { 4940, 4579 }, { 4956, 4622 }, { 4957, 4623 } } }, { "NtGdiDdDDIReleaseProcessVidPnSourceOwners", { -1, { -1, -1 }, { 4842, 4481 }, { 4877, 4486 }, { 4873, 4556 }, { 4882, 4580 }, { 4894, 4623 }, { 4895, 4624 } } }, { "NtGdiDdDDIReleaseSwapChain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5031, 4624 }, { 5031, 4625 } } }, { "NtGdiDdDDIRender", { -1, { -1, -1 }, { 4820, 4482 }, { 4854, 4487 }, { 4899, 4557 }, { 4908, 4581 }, { 4921, 4625 }, { 4922, 4626 } } }, { "NtGdiDdDDIReserveGpuVirtualAddress", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5011, 4626 }, { 5012, 4627 } } }, { "NtGdiDdDDISetAllocationPriority", { -1, { -1, -1 }, { 4802, 4483 }, { 4835, 4488 }, { 4918, 4558 }, { 4927, 4582 }, { 4940, 4627 }, { 4941, 4628 } } }, { "NtGdiDdDDISetContextInProcessSchedulingPriority", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4964, 4559 }, { 4973, 4583 }, { 4991, 4628 }, { 4992, 4629 } } }, { "NtGdiDdDDISetContextSchedulingPriority", { -1, { -1, -1 }, { 4838, 4484 }, { 4873, 4489 }, { 4877, 4560 }, { 4886, 4584 }, { 4898, 4629 }, { 4899, 4630 } } }, { "NtGdiDdDDISetDisplayMode", { -1, { -1, -1 }, { 4817, 4485 }, { 4851, 4490 }, { 4902, 4561 }, { 4911, 4585 }, { 4924, 4630 }, { 4925, 4631 } } }, { "NtGdiDdDDISetDisplayPrivateDriverFormat", { -1, { -1, -1 }, { 4851, 4486 }, { 4886, 4491 }, { 4953, 4562 }, { 4962, 4586 }, { 4978, 4631 }, { 4979, 4632 } } }, { "NtGdiDdDDISetDodIndirectSwapchain", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5033, 4632 }, { 5033, 4633 } } }, { "NtGdiDdDDISetGammaRamp", { -1, { -1, -1 }, { 4834, 4487 }, { 4869, 4492 }, { 4881, 4563 }, { 4890, 4587 }, { 4902, 4633 }, { 4903, 4634 } } }, { "NtGdiDdDDISetHwProtectionTeardownRecovery", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4635 }, { 5044, 4635 } } }, { "NtGdiDdDDISetProcessSchedulingPriorityClass", { -1, { -1, -1 }, { 4840, 4488 }, { 4875, 4493 }, { 4875, 4564 }, { 4884, 4588 }, { 4896, 4634 }, { 4897, 4636 } } }, { "NtGdiDdDDISetQueuedLimit", { -1, { -1, -1 }, { 4844, 4489 }, { 4879, 4494 }, { 4960, 4565 }, { 4969, 4589 }, { 4985, 4635 }, { 4986, 4637 } } }, { "NtGdiDdDDISetStablePowerState", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5037, 4636 }, { 5037, 4638 } } }, { "NtGdiDdDDISetStereoEnabled", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4967, 4566 }, { 4976, 4590 }, { 4994, 4637 }, { 4995, 4639 } } }, { "NtGdiDdDDISetSyncRefreshCountWaitTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4990, 4638 }, { 4991, 4640 } } }, { "NtGdiDdDDISetVidPnSourceHwProtection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5041, 4639 }, { 5041, 4641 } } }, { "NtGdiDdDDISetVidPnSourceOwner", { -1, { -1, -1 }, { 4827, 4490 }, { 4861, 4495 }, { 4890, 4567 }, { 4899, 4591 }, { 4911, 4640 }, { 4912, 4642 } } }, { "NtGdiDdDDISetVidPnSourceOwner1", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4889, 4568 }, { 4898, 4592 }, { 4910, 4641 }, { 4911, 4643 } } }, { "NtGdiDdDDISharedPrimaryLockNotification", { -1, { -1, -1 }, { 4852, 4491 }, { 4887, 4496 }, { 4952, 4570 }, { 4961, 4594 }, { 4977, 4643 }, { 4978, 4645 } } }, { "NtGdiDdDDISharedPrimaryUnLockNotification", { -1, { -1, -1 }, { 4853, 4492 }, { 4888, 4497 }, { 4951, 4571 }, { 4960, 4595 }, { 4976, 4644 }, { 4977, 4646 } } }, { "NtGdiDdDDIShareObjects", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4924, 4569 }, { 4933, 4593 }, { 4949, 4642 }, { 4950, 4644 } } }, { "NtGdiDdDDISignalSynchronizationObject", { -1, { -1, -1 }, { 4811, 4493 }, { 4845, 4498 }, { 4908, 4572 }, { 4917, 4596 }, { 4930, 4645 }, { 4931, 4647 } } }, { "NtGdiDdDDISignalSynchronizationObjectFromCpu", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5000, 4646 }, { 5001, 4648 } } }, { "NtGdiDdDDISignalSynchronizationObjectFromGpu", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5002, 4647 }, { 5003, 4649 } } }, { "NtGdiDdDDISignalSynchronizationObjectFromGpu2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5003, 4648 }, { 5004, 4650 } } }, { "NtGdiDdDDISubmitCommand", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5015, 4649 }, { 5016, 4651 } } }, { "NtGdiDdDDIUnlock", { -1, { -1, -1 }, { 4815, 4494 }, { 4849, 4499 }, { 4904, 4573 }, { 4913, 4597 }, { 4926, 4650 }, { 4927, 4652 } } }, { "NtGdiDdDDIUnlock2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5007, 4651 }, { 5008, 4653 } } }, { "NtGdiDdDDIUnpinDirectFlipResources", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4962, 4574 }, { 4971, 4598 }, { 4987, 4652 }, { 4988, 4654 } } }, { "NtGdiDdDDIUpdateGpuVirtualAddress", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5013, 4653 }, { 5014, 4655 } } }, { "NtGdiDdDDIUpdateOverlay", { -1, { -1, -1 }, { 4830, 4495 }, { 4865, 4500 }, { 4885, 4575 }, { 4894, 4599 }, { 4906, 4654 }, { 4907, 4656 } } }, { "NtGdiDdDDIWaitForIdle", { -1, { -1, -1 }, { 4848, 4496 }, { 4883, 4501 }, { 4956, 4576 }, { 4965, 4600 }, { 4981, 4655 }, { 4982, 4657 } } }, { "NtGdiDdDDIWaitForSynchronizationObject", { -1, { -1, -1 }, { 4810, 4497 }, { 4844, 4502 }, { 4909, 4577 }, { 4918, 4601 }, { 4931, 4656 }, { 4932, 4658 } } }, { "NtGdiDdDDIWaitForSynchronizationObjectFromCpu", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4999, 4657 }, { 5000, 4659 } } }, { "NtGdiDdDDIWaitForSynchronizationObjectFromGpu", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5001, 4658 }, { 5002, 4660 } } }, { "NtGdiDdDDIWaitForVerticalBlankEvent", { -1, { -1, -1 }, { 4833, 4498 }, { 4868, 4503 }, { 4882, 4578 }, { 4891, 4602 }, { 4903, 4659 }, { 4904, 4661 } } }, { "NtGdiDdDDIWaitForVerticalBlankEvent2", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4963, 4579 }, { 4972, 4603 }, { 4988, 4660 }, { 4989, 4662 } } }, { "NtGdiDdDeleteDirectDrawObject", { 4160, { 4160, 4434 }, { 4162, 4499 }, { 4163, 4504 }, { 4359, 4580 }, { 4361, 4604 }, { 4346, 4661 }, { 4348, 4663 } } }, { "NtGdiDdDeleteSurfaceObject", { 4161, { 4161, 4258 }, { 4163, 4259 }, { 4164, 4257 }, { 4343, 4257 }, { 4345, 4258 }, { 4345, 4259 }, { 4347, 4259 } } }, { "NtGdiDdDestroyD3DBuffer", { 4164, { 4164, 4435 }, { 4166, 4500 }, { 4167, 4505 }, { 4348, 4581 }, { 4350, 4605 }, { 4342, 4662 }, { 4344, 4664 } } }, { "NtGdiDdDestroyFullscreenSprite", { -1, { -1, -1 }, { -1, -1 }, { 4912, 4506 }, { 4981, 4582 }, { 4999, 4606 }, { 5056, 4663 }, { 5058, 4665 } } }, { "NtGdiDdDestroyMoComp", { 4162, { 4162, 4436 }, { 4164, 4501 }, { 4165, 4507 }, { 4323, 4583 }, { 4325, 4607 }, { 4344, 4664 }, { 4346, 4666 } } }, { "NtGdiDdDestroySurface", { 4163, { 4163, 4265 }, { 4165, 4266 }, { 4166, 4261 }, { 4292, 4261 }, { 4294, 4262 }, { 4343, 4263 }, { 4345, 4263 } } }, { "NtGdiDdEndMoCompFrame", { 4165, { 4165, 4437 }, { 4167, 4502 }, { 4168, 4508 }, { 4316, 4584 }, { 4318, 4608 }, { 4341, 4665 }, { 4343, 4667 } } }, { "NtGdiDdFlip", { 4166, { 4166, -1 }, { 4168, 4503 }, { 4169, 4509 }, { 4337, 4585 }, { 4339, 4609 }, { 4340, 4666 }, { 4342, 4668 } } }, { "NtGdiDdFlipToGDISurface", { 4167, { 4167, 4439 }, { 4169, 4504 }, { 4170, 4510 }, { 4336, 4586 }, { 4338, 4610 }, { 4339, 4667 }, { 4341, 4669 } } }, { "NtGdiDdGetAvailDriverMemory", { 4168, { 4168, 4440 }, { 4170, 4505 }, { 4171, 4511 }, { 4350, 4587 }, { 4352, 4611 }, { 4338, 4668 }, { 4340, 4670 } } }, { "NtGdiDdGetBltStatus", { 4169, { 4169, 4441 }, { 4171, 4506 }, { 4172, 4512 }, { 4290, 4588 }, { 4292, 4612 }, { 4337, 4669 }, { 4339, 4671 } } }, { "NtGdiDdGetDC", { 4170, { 4170, 4442 }, { 4172, 4507 }, { 4173, 4513 }, { 4326, 4589 }, { 4328, 4613 }, { 4336, 4670 }, { 4338, 4672 } } }, { "NtGdiDdGetDriverInfo", { 4171, { 4171, 4443 }, { 4173, 4508 }, { 4174, 4514 }, { 4327, 4590 }, { 4329, 4614 }, { 4335, 4671 }, { 4337, 4673 } } }, { "NtGdiDdGetDriverState", { 4146, { 4146, 4444 }, { 4148, 4509 }, { 4149, 4515 }, { 4360, 4591 }, { 4362, 4615 }, { 4360, 4672 }, { 4362, 4674 } } }, { "NtGdiDdGetDxHandle", { 4172, { 4172, 4445 }, { 4174, 4510 }, { 4175, 4516 }, { 4308, 4592 }, { 4310, 4616 }, { 4334, 4673 }, { 4336, 4675 } } }, { "NtGdiDdGetFlipStatus", { 4173, { 4173, 4446 }, { 4175, 4511 }, { 4176, 4517 }, { 4306, 4593 }, { 4308, 4617 }, { 4333, 4674 }, { 4335, 4676 } } }, { "NtGdiDdGetInternalMoCompInfo", { 4174, { 4174, 4447 }, { 4176, 4512 }, { 4177, 4518 }, { 4349, 4594 }, { 4351, 4618 }, { 4332, 4675 }, { 4334, 4677 } } }, { "NtGdiDdGetMoCompBuffInfo", { 4175, { 4175, 4448 }, { 4177, 4513 }, { 4178, 4519 }, { 4351, 4595 }, { 4353, 4619 }, { 4331, 4676 }, { 4333, 4678 } } }, { "NtGdiDdGetMoCompFormats", { 4177, { 4177, 4449 }, { 4179, 4514 }, { 4180, 4520 }, { 4330, 4596 }, { 4332, 4620 }, { 4329, 4677 }, { 4331, 4679 } } }, { "NtGdiDdGetMoCompGuids", { 4176, { 4176, 4450 }, { 4178, 4515 }, { 4179, 4521 }, { 4297, 4597 }, { 4299, 4621 }, { 4330, 4678 }, { 4332, 4680 } } }, { "NtGdiDdGetScanLine", { 4178, { 4178, 4451 }, { 4180, 4516 }, { 4181, 4522 }, { 4341, 4598 }, { 4343, 4622 }, { 4328, 4679 }, { 4330, 4681 } } }, { "NtGdiDdLock", { 4179, { 4179, 4452 }, { 4181, 4517 }, { 4182, 4523 }, { 4356, 4599 }, { 4358, 4623 }, { 4327, 4680 }, { 4329, 4682 } } }, { "NtGdiDdLockD3D", { 4180, { 4180, 4297 }, { 4182, 4298 }, { 4183, 4293 }, { 4315, 4293 }, { 4317, 4294 }, { 4326, 4295 }, { 4328, 4295 } } }, { "NtGdiDdNotifyFullscreenSpriteUpdate", { -1, { -1, -1 }, { -1, -1 }, { 4911, 4524 }, { 4982, 4600 }, { 5000, 4624 }, { 5057, 4681 }, { 5059, 4683 } } }, { "NtGdiDdQueryDirectDrawObject", { 4181, { 4181, -1 }, { 4183, 4518 }, { 4184, 4525 }, { 4322, 4601 }, { 4324, 4625 }, { 4325, 4682 }, { 4327, 4684 } } }, { "NtGdiDdQueryMoCompStatus", { 4182, { 4182, 4454 }, { 4184, 4519 }, { 4185, 4526 }, { 4295, 4602 }, { 4297, 4626 }, { 4324, 4683 }, { 4326, 4685 } } }, { "NtGdiDdQueryVisRgnUniqueness", { -1, { -1, -1 }, { -1, -1 }, { 4913, 4527 }, { 4980, 4603 }, { 4998, 4627 }, { 5055, 4684 }, { 5057, 4686 } } }, { "NtGdiDdReenableDirectDrawObject", { 4183, { 4183, 4455 }, { 4185, 4520 }, { 4186, 4528 }, { 4328, 4604 }, { 4330, 4628 }, { 4323, 4685 }, { 4325, 4687 } } }, { "NtGdiDdReleaseDC", { 4184, { 4184, 4456 }, { 4186, 4521 }, { 4187, 4529 }, { 4319, 4605 }, { 4321, 4629 }, { 4322, 4686 }, { 4324, 4688 } } }, { "NtGdiDdRenderMoComp", { 4185, { 4185, 4457 }, { 4187, 4522 }, { 4188, 4530 }, { 4294, 4606 }, { 4296, 4630 }, { 4321, 4687 }, { 4323, 4689 } } }, { "NtGdiDdResetVisrgn", { 4186, { 4186, 4270 }, { 4188, 4271 }, { 4189, 4266 }, { 4332, 4266 }, { 4334, 4267 }, { 4320, 4268 }, { 4322, 4268 } } }, { "NtGdiDdSetColorKey", { 4187, { 4187, 4458 }, { 4189, 4523 }, { 4190, 4531 }, { 4318, 4607 }, { 4320, 4631 }, { 4319, 4688 }, { 4321, 4690 } } }, { "NtGdiDdSetExclusiveMode", { 4188, { 4188, 4459 }, { 4190, 4524 }, { 4191, 4532 }, { 4335, 4608 }, { 4337, 4632 }, { 4318, 4689 }, { 4320, 4691 } } }, { "NtGdiDdSetGammaRamp", { 4189, { 4189, 4460 }, { 4191, 4525 }, { 4192, 4533 }, { 4324, 4609 }, { 4326, 4633 }, { 4317, 4690 }, { 4319, 4692 } } }, { "NtGdiDdSetOverlayPosition", { 4191, { 4191, 4461 }, { 4193, 4526 }, { 4194, 4534 }, { 4291, 4610 }, { 4293, 4634 }, { 4315, 4691 }, { 4317, 4693 } } }, { "NtGdiDdUnattachSurface", { 4192, { 4192, 4462 }, { 4194, 4527 }, { 4195, 4535 }, { 4311, 4611 }, { 4313, 4635 }, { 4314, 4692 }, { 4316, 4694 } } }, { "NtGdiDdUnlock", { 4193, { 4193, 4463 }, { 4195, 4528 }, { 4196, 4536 }, { 4298, 4612 }, { 4300, 4636 }, { 4313, 4693 }, { 4315, 4695 } } }, { "NtGdiDdUnlockD3D", { 4194, { 4194, 4298 }, { 4196, 4299 }, { 4197, 4294 }, { 4329, 4294 }, { 4331, 4295 }, { 4312, 4296 }, { 4314, 4296 } } }, { "NtGdiDdUpdateOverlay", { 4195, { 4195, 4464 }, { 4197, 4529 }, { 4198, 4537 }, { 4352, 4613 }, { 4354, 4637 }, { 4311, 4694 }, { 4313, 4696 } } }, { "NtGdiDdWaitForVerticalBlank", { 4196, { 4196, 4465 }, { 4198, 4530 }, { 4199, 4538 }, { 4345, 4614 }, { 4347, 4638 }, { 4310, 4695 }, { 4312, 4697 } } }, { "NtGdiDeleteClientObj", { 4215, { 4215, 4232 }, { 4217, 4233 }, { 4218, 4231 }, { 4288, 4231 }, { 4290, 4232 }, { 4291, 4233 }, { 4293, 4233 } } }, { "NtGdiDeleteColorSpace", { 4216, { 4216, 4389 }, { 4218, 4390 }, { 4219, 4381 }, { 4287, 4381 }, { 4289, 4382 }, { 4290, 4383 }, { 4292, 4383 } } }, { "NtGdiDeleteColorTransform", { 4217, { 4217, 4466 }, { 4219, 4531 }, { 4220, 4539 }, { 4286, 4615 }, { 4288, 4639 }, { 4289, 4696 }, { 4291, 4698 } } }, { "NtGdiDeleteObjectApp", { 4218, { 4218, 4130 }, { 4220, 4131 }, { 4221, 4131 }, { 4285, 4132 }, { 4287, 4133 }, { 4288, 4134 }, { 4290, 4134 } } }, { "NtGdiDescribePixelFormat", { 4219, { 4219, 4467 }, { 4221, 4532 }, { 4222, 4540 }, { 4284, 4616 }, { 4286, 4640 }, { 4287, 4697 }, { 4289, 4699 } } }, { "NtGdiDestroyOPMProtectedOutput", { -1, { -1, -1 }, { 4222, 4533 }, { 4223, 4541 }, { 4283, 4617 }, { 4285, 4641 }, { 4286, 4698 }, { 4288, 4700 } } }, { "NtGdiDestroyPhysicalMonitor", { -1, { -1, -1 }, { 4859, 4534 }, { 4903, 4542 }, { 4970, 4618 }, { 4988, 4642 }, { 5045, 4699 }, { 5047, 4701 } } }, { "NtGdiDoBanding", { 4221, { 4221, 4468 }, { 4224, 4535 }, { 4225, 4543 }, { 4281, 4619 }, { 4283, 4643 }, { 4284, 4700 }, { 4286, 4702 } } }, { "NtGdiDoPalette", { 4222, { 4222, -1 }, { 4225, 4167 }, { 4226, 4167 }, { 4280, 4168 }, { 4282, 4169 }, { 4283, 4170 }, { 4285, 4170 } } }, { "NtGdiDrawEscape", { 4223, { 4223, 4469 }, { 4226, 4536 }, { 4227, 4544 }, { 4279, 4620 }, { 4281, 4644 }, { 4282, 4701 }, { 4284, 4703 } } }, { "NtGdiDrawStream", { 4762, { 4758, 4193 }, { 4795, 4194 }, { 4827, 4194 }, { 4868, 4194 }, { 4877, 4195 }, { 4889, 4196 }, { 4890, 4196 } } }, { "NtGdiDvpAcquireNotification", { 4212, { 4212, 4470 }, { 4214, 4537 }, { 4215, 4545 }, { 4355, 4621 }, { 4357, 4645 }, { 4294, 4702 }, { 4296, 4704 } } }, { "NtGdiDvpCanCreateVideoPort", { 4197, { 4197, 4471 }, { 4199, 4538 }, { 4200, 4546 }, { 4338, 4622 }, { 4340, 4646 }, { 4309, 4703 }, { 4311, 4705 } } }, { "NtGdiDvpColorControl", { 4198, { 4198, 4472 }, { 4200, 4539 }, { 4201, 4547 }, { 4301, 4623 }, { 4303, 4647 }, { 4308, 4704 }, { 4310, 4706 } } }, { "NtGdiDvpCreateVideoPort", { 4199, { 4199, 4473 }, { 4201, 4540 }, { 4202, 4548 }, { 4340, 4624 }, { 4342, 4648 }, { 4307, 4705 }, { 4309, 4707 } } }, { "NtGdiDvpDestroyVideoPort", { 4200, { 4200, 4474 }, { 4202, 4541 }, { 4203, 4549 }, { 4299, 4625 }, { 4301, 4649 }, { 4306, 4706 }, { 4308, 4708 } } }, { "NtGdiDvpFlipVideoPort", { 4201, { 4201, 4475 }, { 4203, 4542 }, { 4204, 4550 }, { 4302, 4626 }, { 4304, 4650 }, { 4305, 4707 }, { 4307, 4709 } } }, { "NtGdiDvpGetVideoPortBandwidth", { 4202, { 4202, 4476 }, { 4204, 4543 }, { 4205, 4551 }, { 4303, 4627 }, { 4305, 4651 }, { 4304, 4708 }, { 4306, 4710 } } }, { "NtGdiDvpGetVideoPortConnectInfo", { 4208, { 4208, 4477 }, { 4210, 4544 }, { 4211, 4552 }, { 4325, 4628 }, { 4327, 4652 }, { 4298, 4709 }, { 4300, 4711 } } }, { "NtGdiDvpGetVideoPortField", { 4203, { 4203, 4478 }, { 4205, 4545 }, { 4206, 4553 }, { 4333, 4629 }, { 4335, 4653 }, { 4303, 4710 }, { 4305, 4712 } } }, { "NtGdiDvpGetVideoPortFlipStatus", { 4204, { 4204, 4479 }, { 4206, 4546 }, { 4207, 4554 }, { 4309, 4630 }, { 4311, 4654 }, { 4302, 4711 }, { 4304, 4713 } } }, { "NtGdiDvpGetVideoPortInputFormats", { 4205, { 4205, 4480 }, { 4207, 4547 }, { 4208, 4555 }, { 4317, 4631 }, { 4319, 4655 }, { 4301, 4712 }, { 4303, 4714 } } }, { "NtGdiDvpGetVideoPortLine", { 4206, { 4206, 4481 }, { 4208, 4548 }, { 4209, 4556 }, { 4354, 4632 }, { 4356, 4656 }, { 4300, 4713 }, { 4302, 4715 } } }, { "NtGdiDvpGetVideoPortOutputFormats", { 4207, { 4207, 4482 }, { 4209, 4549 }, { 4210, 4557 }, { 4307, 4633 }, { 4309, 4657 }, { 4299, 4714 }, { 4301, 4716 } } }, { "NtGdiDvpGetVideoSignalStatus", { 4209, { 4209, 4483 }, { 4211, 4550 }, { 4212, 4558 }, { 4320, 4634 }, { 4322, 4658 }, { 4297, 4715 }, { 4299, 4717 } } }, { "NtGdiDvpReleaseNotification", { 4213, { 4213, 4484 }, { 4215, 4551 }, { 4216, 4559 }, { 4300, 4635 }, { 4302, 4659 }, { 4293, 4716 }, { 4295, 4718 } } }, { "NtGdiDvpUpdateVideoPort", { 4210, { 4210, 4485 }, { 4212, 4552 }, { 4213, 4560 }, { 4293, 4636 }, { 4295, 4660 }, { 4296, 4717 }, { 4298, 4719 } } }, { "NtGdiDvpWaitForVideoPortSync", { 4211, { 4211, 4486 }, { 4213, 4553 }, { 4214, 4561 }, { 4304, 4637 }, { 4306, 4661 }, { 4295, 4718 }, { 4297, 4720 } } }, { "NtGdiDwmCreatedBitmapRemotingOutput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4871, 4638 }, { 4880, 4662 }, { 4892, 4719 }, { 4893, 4721 } } }, { "NtGdiDwmGetDirtyRgn", { -1, { -1, -1 }, { 4796, 4554 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiDwmGetSurfaceData", { -1, { -1, -1 }, { 4797, 4555 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiDxgGenericThunk", { 4214, { 4214, -1 }, { 4216, 4556 }, { 4217, 4562 }, { 4289, 4639 }, { 4291, 4663 }, { 4292, 4720 }, { 4294, 4722 } } }, { "NtGdiEllipse", { 4224, { 4224, -1 }, { 4227, 4557 }, { 4228, 4563 }, { 4278, 4640 }, { 4280, 4664 }, { 4281, 4721 }, { 4283, 4723 } } }, { "NtGdiEnableEudc", { 4225, { 4225, -1 }, { 4228, 4558 }, { 4229, 4564 }, { 4277, 4641 }, { 4279, 4665 }, { 4280, 4722 }, { 4282, 4724 } } }, { "NtGdiEndDoc", { 4226, { 4226, 4490 }, { 4229, 4559 }, { 4230, 4565 }, { 4276, 4642 }, { 4278, 4666 }, { 4279, 4723 }, { 4281, 4725 } } }, { "NtGdiEndGdiRendering", { -1, { -1, -1 }, { -1, -1 }, { 4231, 4566 }, { 4275, 4643 }, { 4277, 4667 }, { 4278, 4724 }, { 4280, 4726 } } }, { "NtGdiEndPage", { 4227, { 4227, 4491 }, { 4230, 4560 }, { 4232, 4567 }, { 4274, 4644 }, { 4276, 4668 }, { 4277, 4725 }, { 4279, 4727 } } }, { "NtGdiEndPath", { 4228, { 4228, -1 }, { 4231, 4369 }, { 4233, 4362 }, { 4273, 4362 }, { 4275, 4363 }, { 4276, 4364 }, { 4278, 4364 } } }, { "NtGdiEngAlphaBlend", { 4716, { 4712, -1 }, { 4749, 4561 }, { 4781, 4568 }, { 4775, 4645 }, { 4778, 4669 }, { 4788, 4726 }, { 4789, 4728 } } }, { "NtGdiEngAssociateSurface", { 4695, { 4691, 4493 }, { 4728, 4562 }, { 4760, 4569 }, { 4796, 4646 }, { 4799, 4670 }, { 4809, 4727 }, { 4810, 4729 } } }, { "NtGdiEngBitBlt", { 4707, { 4703, -1 }, { 4740, 4563 }, { 4772, 4570 }, { 4784, 4647 }, { 4787, 4671 }, { 4797, 4728 }, { 4798, 4730 } } }, { "NtGdiEngCheckAbort", { 4755, { 4751, 4495 }, { 4788, 4564 }, { 4820, 4571 }, { 4859, 4648 }, { 4868, 4672 }, { 4880, 4729 }, { 4881, 4731 } } }, { "NtGdiEngComputeGlyphSet", { 4700, { 4696, 4496 }, { 4733, 4565 }, { 4765, 4572 }, { 4791, 4649 }, { 4794, 4673 }, { 4804, 4730 }, { 4805, 4732 } } }, { "NtGdiEngCopyBits", { 4701, { 4697, -1 }, { 4734, 4566 }, { 4766, 4573 }, { 4790, 4650 }, { 4793, 4674 }, { 4803, 4731 }, { 4804, 4733 } } }, { "NtGdiEngCreateBitmap", { 4696, { 4692, -1 }, { 4729, 4567 }, { 4761, 4574 }, { 4795, 4651 }, { 4798, 4675 }, { 4808, 4732 }, { 4809, 4734 } } }, { "NtGdiEngCreateClip", { 4728, { 4724, 4499 }, { 4761, 4568 }, { 4793, 4575 }, { 4830, 4652 }, { 4839, 4676 }, { 4851, 4733 }, { 4852, 4735 } } }, { "NtGdiEngCreateDeviceBitmap", { 4698, { 4694, 4500 }, { 4731, 4569 }, { 4763, 4576 }, { 4793, 4653 }, { 4796, 4677 }, { 4806, 4734 }, { 4807, 4736 } } }, { "NtGdiEngCreateDeviceSurface", { 4697, { 4693, 4501 }, { 4730, 4570 }, { 4762, 4577 }, { 4794, 4654 }, { 4797, 4678 }, { 4807, 4735 }, { 4808, 4737 } } }, { "NtGdiEngCreatePalette", { 4699, { 4695, -1 }, { 4732, 4571 }, { 4764, 4578 }, { 4792, 4655 }, { 4795, 4679 }, { 4805, 4736 }, { 4806, 4738 } } }, { "NtGdiEngDeleteClip", { 4729, { 4725, 4503 }, { 4762, 4572 }, { 4794, 4579 }, { 4829, 4656 }, { 4838, 4680 }, { 4850, 4737 }, { 4851, 4739 } } }, { "NtGdiEngDeletePalette", { 4702, { 4698, -1 }, { 4735, 4573 }, { 4767, 4580 }, { 4789, 4657 }, { 4792, 4681 }, { 4802, 4738 }, { 4803, 4740 } } }, { "NtGdiEngDeletePath", { 4727, { 4723, 4505 }, { 4760, 4574 }, { 4792, 4581 }, { 4831, 4658 }, { 4840, 4682 }, { 4852, 4739 }, { 4853, 4741 } } }, { "NtGdiEngDeleteSurface", { 4703, { 4699, 4506 }, { 4736, 4575 }, { 4768, 4582 }, { 4788, 4659 }, { 4791, 4683 }, { 4801, 4740 }, { 4802, 4742 } } }, { "NtGdiEngEraseSurface", { 4704, { 4700, 4507 }, { 4737, 4576 }, { 4769, 4583 }, { 4787, 4660 }, { 4790, 4684 }, { 4800, 4741 }, { 4801, 4743 } } }, { "NtGdiEngFillPath", { 4712, { 4708, -1 }, { 4745, 4577 }, { 4777, 4584 }, { 4779, 4661 }, { 4782, 4685 }, { 4792, 4742 }, { 4793, 4744 } } }, { "NtGdiEngGradientFill", { 4717, { 4713, -1 }, { 4750, 4578 }, { 4782, 4585 }, { 4774, 4662 }, { 4777, 4686 }, { 4787, 4743 }, { 4788, 4745 } } }, { "NtGdiEngLineTo", { 4715, { 4711, -1 }, { 4748, 4579 }, { 4780, 4586 }, { 4776, 4663 }, { 4779, 4687 }, { 4789, 4744 }, { 4790, 4746 } } }, { "NtGdiEngLockSurface", { 4706, { 4702, 4511 }, { 4739, 4580 }, { 4771, 4587 }, { 4785, 4664 }, { 4788, 4688 }, { 4798, 4745 }, { 4799, 4747 } } }, { "NtGdiEngMarkBandingSurface", { 4710, { 4706, 4512 }, { 4743, 4581 }, { 4775, 4588 }, { 4781, 4665 }, { 4784, 4689 }, { 4794, 4746 }, { 4795, 4748 } } }, { "NtGdiEngPaint", { 4714, { 4710, -1 }, { 4747, 4582 }, { 4779, 4589 }, { 4777, 4666 }, { 4780, 4690 }, { 4790, 4747 }, { 4791, 4749 } } }, { "NtGdiEngPlgBlt", { 4709, { 4705, -1 }, { 4742, 4583 }, { 4774, 4590 }, { 4782, 4667 }, { 4785, 4691 }, { 4795, 4748 }, { 4796, 4750 } } }, { "NtGdiEngStretchBlt", { 4708, { 4704, -1 }, { 4741, 4584 }, { 4773, 4591 }, { 4783, 4668 }, { 4786, 4692 }, { 4796, 4749 }, { 4797, 4751 } } }, { "NtGdiEngStretchBltROP", { 4720, { 4716, -1 }, { 4753, 4585 }, { 4785, 4592 }, { 4771, 4669 }, { 4774, 4693 }, { 4784, 4750 }, { 4785, 4752 } } }, { "NtGdiEngStrokeAndFillPath", { 4713, { 4709, -1 }, { 4746, 4586 }, { 4778, 4593 }, { 4778, 4670 }, { 4781, 4694 }, { 4791, 4751 }, { 4792, 4753 } } }, { "NtGdiEngStrokePath", { 4711, { 4707, -1 }, { 4744, 4587 }, { 4776, 4594 }, { 4780, 4671 }, { 4783, 4695 }, { 4793, 4752 }, { 4794, 4754 } } }, { "NtGdiEngTextOut", { 4719, { 4715, -1 }, { 4752, 4588 }, { 4784, 4595 }, { 4772, 4672 }, { 4775, 4696 }, { 4785, 4753 }, { 4786, 4755 } } }, { "NtGdiEngTransparentBlt", { 4718, { 4714, -1 }, { 4751, 4589 }, { 4783, 4596 }, { 4773, 4673 }, { 4776, 4697 }, { 4786, 4754 }, { 4787, 4756 } } }, { "NtGdiEngUnlockSurface", { 4705, { 4701, 4521 }, { 4738, 4590 }, { 4770, 4597 }, { 4786, 4674 }, { 4789, 4698 }, { 4799, 4755 }, { 4800, 4757 } } }, { "NtGdiEnumFontChunk", { 4229, { 4229, -1 }, { 4232, 4262 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiEnumFontClose", { 4230, { 4230, 4259 }, { 4233, 4260 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiEnumFontOpen", { 4231, { 4231, -1 }, { 4234, 4261 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiEnumFonts", { -1, { -1, -1 }, { -1, -1 }, { 4234, 4598 }, { 4272, 4675 }, { 4274, 4699 }, { 4275, 4756 }, { 4277, 4758 } } }, { "NtGdiEnumObjects", { 4232, { 4232, 4522 }, { 4235, 4591 }, { 4235, 4599 }, { 4271, 4676 }, { 4273, 4700 }, { 4274, 4757 }, { 4276, 4759 } } }, { "NtGdiEqualRgn", { 4233, { 4233, 4375 }, { 4236, 4376 }, { 4236, 4369 }, { 4270, 4369 }, { 4272, 4370 }, { 4273, 4371 }, { 4275, 4371 } } }, { "NtGdiEudcLoadUnloadLink", { 4234, { 4234, -1 }, { 4237, 4592 }, { 4237, 4600 }, { 4269, 4677 }, { 4271, 4701 }, { 4272, 4758 }, { 4274, 4760 } } }, { "NtGdiExcludeClipRect", { 4235, { 4235, -1 }, { 4238, 4251 }, { 4238, 4249 }, { 4268, 4249 }, { 4270, 4250 }, { 4271, 4251 }, { 4273, 4251 } } }, { "NtGdiExtCreatePen", { 4236, { 4236, -1 }, { 4239, 4272 }, { 4239, 4267 }, { 4267, 4267 }, { 4269, 4268 }, { 4270, 4269 }, { 4272, 4269 } } }, { "NtGdiExtCreateRegion", { 4237, { 4237, 4235 }, { 4240, 4236 }, { 4240, 4234 }, { 4266, 4234 }, { 4268, 4235 }, { 4269, 4236 }, { 4271, 4236 } } }, { "NtGdiExtEscape", { 4238, { 4238, -1 }, { 4241, 4381 }, { 4241, 4374 }, { 4265, 4374 }, { 4267, 4375 }, { 4268, 4376 }, { 4270, 4376 } } }, { "NtGdiExtFloodFill", { 4239, { 4239, -1 }, { 4242, 4593 }, { 4242, 4601 }, { 4264, 4678 }, { 4266, 4702 }, { 4267, 4759 }, { 4269, 4761 } } }, { "NtGdiExtGetObjectW", { 4240, { 4240, 4177 }, { 4243, 4178 }, { 4243, 4178 }, { 4263, 4179 }, { 4265, 4180 }, { 4266, 4181 }, { 4268, 4181 } } }, { "NtGdiExtSelectClipRgn", { 4241, { 4241, 4141 }, { 4244, 4142 }, { 4244, 4142 }, { 4262, 4143 }, { 4264, 4144 }, { 4265, 4145 }, { 4267, 4145 } } }, { "NtGdiExtTextOutW", { 4242, { 4242, -1 }, { 4245, 4152 }, { 4245, 4152 }, { 4261, 4153 }, { 4263, 4154 }, { 4264, 4155 }, { 4266, 4155 } } }, { "NtGdiFillPath", { 4243, { 4243, 4369 }, { 4246, 4370 }, { 4246, 4363 }, { 4260, 4363 }, { 4262, 4364 }, { 4263, 4365 }, { 4265, 4365 } } }, { "NtGdiFillRgn", { 4244, { 4244, 4312 }, { 4247, 4313 }, { 4247, 4308 }, { 4259, 4308 }, { 4261, 4309 }, { 4262, 4310 }, { 4264, 4310 } } }, { "NtGdiFlattenPath", { 4245, { 4245, -1 }, { 4248, 4602 }, { 4248, 4610 }, { 4258, 4687 }, { 4260, 4711 }, { 4261, 4768 }, { 4263, 4770 } } }, { "NtGdiFlush", { 4247, { 4246, 4113 }, { 4249, 4114 }, { 4249, 4114 }, { 4257, 4115 }, { 4259, 4116 }, { 4260, 4117 }, { 4262, 4117 } } }, { "NtGdiFlushUserBatch", { 4246, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiFontIsLinked", { 4106, { 4106, 4534 }, { 4106, 4603 }, { 4106, 4611 }, { 4402, 4688 }, { 4404, 4712 }, { 4405, 4769 }, { 4407, 4771 } } }, { "NtGdiFONTOBJ_cGetAllGlyphHandles", { 4743, { 4739, 4525 }, { 4776, 4594 }, { 4808, 4602 }, { 4847, 4679 }, { 4856, 4703 }, { 4868, 4760 }, { 4869, 4762 } } }, { "NtGdiFONTOBJ_cGetGlyphs", { 4738, { 4734, -1 }, { 4771, 4595 }, { 4803, 4603 }, { 4844, 4680 }, { 4853, 4704 }, { 4865, 4761 }, { 4866, 4763 } } }, { "NtGdiFONTOBJ_pfdg", { 4740, { 4736, 4528 }, { 4773, 4597 }, { 4805, 4605 }, { 4842, 4682 }, { 4851, 4706 }, { 4863, 4763 }, { 4864, 4765 } } }, { "NtGdiFONTOBJ_pifi", { 4739, { 4735, 4529 }, { 4772, 4598 }, { 4804, 4606 }, { 4843, 4683 }, { 4852, 4707 }, { 4864, 4764 }, { 4865, 4766 } } }, { "NtGdiFONTOBJ_pQueryGlyphAttrs", { 4741, { 4737, 4527 }, { 4774, 4596 }, { 4806, 4604 }, { 4841, 4681 }, { 4850, 4705 }, { 4862, 4762 }, { 4863, 4764 } } }, { "NtGdiFONTOBJ_pvTrueTypeFontFile", { 4742, { 4738, 4530 }, { 4775, 4599 }, { 4807, 4607 }, { 4848, 4684 }, { 4857, 4708 }, { 4869, 4765 }, { 4870, 4767 } } }, { "NtGdiFONTOBJ_pxoGetXform", { 4737, { 4733, 4531 }, { 4770, 4600 }, { 4802, 4608 }, { 4845, 4685 }, { 4854, 4709 }, { 4866, 4766 }, { 4867, 4768 } } }, { "NtGdiFONTOBJ_vGetInfo", { 4736, { 4732, 4532 }, { 4769, 4601 }, { 4801, 4609 }, { 4846, 4686 }, { 4855, 4710 }, { 4867, 4767 }, { 4868, 4769 } } }, { "NtGdiForceUFIMapping", { 4248, { 4247, 4535 }, { 4250, 4604 }, { 4250, 4612 }, { 4256, 4689 }, { 4258, 4713 }, { 4259, 4770 }, { 4261, 4772 } } }, { "NtGdiFrameRgn", { 4249, { 4248, -1 }, { 4251, 4605 }, { 4251, 4613 }, { 4255, 4690 }, { 4257, 4714 }, { 4258, 4771 }, { 4260, 4773 } } }, { "NtGdiFullscreenControl", { 4250, { 4249, -1 }, { 4252, 4606 }, { 4252, 4614 }, { 4254, 4691 }, { 4256, 4715 }, { 4257, 4772 }, { 4259, 4774 } } }, { "NtGdiGetAndSetDCDword", { 4251, { 4250, 4199 }, { 4253, 4200 }, { 4253, 4200 }, { 4253, 4200 }, { 4255, 4201 }, { 4256, 4202 }, { 4258, 4202 } } }, { "NtGdiGetAppClipBox", { 4252, { 4251, -1 }, { 4254, 4163 }, { 4254, 4163 }, { 4252, 4164 }, { 4254, 4165 }, { 4255, 4166 }, { 4257, 4166 } } }, { "NtGdiGetBitmapBits", { 4253, { 4252, 4322 }, { 4255, 4323 }, { 4255, 4318 }, { 4251, 4318 }, { 4253, 4319 }, { 4254, 4320 }, { 4256, 4320 } } }, { "NtGdiGetBitmapDimension", { 4254, { 4253, -1 }, { 4256, 4354 }, { 4256, 4348 }, { 4250, 4348 }, { 4252, 4349 }, { 4253, 4350 }, { 4255, 4350 } } }, { "NtGdiGetBoundsRect", { 4255, { 4254, -1 }, { 4257, 4607 }, { 4257, 4615 }, { 4249, 4692 }, { 4251, 4716 }, { 4252, 4773 }, { 4254, 4775 } } }, { "NtGdiGetCertificate", { -1, { -1, -1 }, { 4258, 4609 }, { 4258, 4617 }, { 4248, 4694 }, { 4250, 4718 }, { 4251, 4775 }, { 4251, 4777 } } }, { "NtGdiGetCertificateByHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4778 }, { 4253, 4778 } } }, { "NtGdiGetCertificateSize", { -1, { -1, -1 }, { 4259, 4610 }, { 4259, 4618 }, { 4247, 4695 }, { 4249, 4719 }, { 4250, 4776 }, { 4250, 4779 } } }, { "NtGdiGetCertificateSizeByHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4780 }, { 4252, 4780 } } }, { "NtGdiGetCharABCWidthsW", { 4256, { 4255, -1 }, { 4260, 4611 }, { 4260, 4619 }, { 4246, 4696 }, { 4248, 4720 }, { 4249, 4777 }, { 4249, 4781 } } }, { "NtGdiGetCharacterPlacementW", { 4257, { 4256, -1 }, { 4261, 4612 }, { 4261, 4620 }, { 4245, 4697 }, { 4247, 4721 }, { 4248, 4778 }, { 4248, 4782 } } }, { "NtGdiGetCharSet", { 4258, { 4257, 4105 }, { 4262, 4105 }, { 4262, 4105 }, { 4244, 4106 }, { 4246, 4107 }, { 4247, 4108 }, { 4247, 4108 } } }, { "NtGdiGetCharWidthInfo", { 4260, { 4259, -1 }, { 4264, 4305 }, { 4264, 4300 }, { 4242, 4300 }, { 4244, 4301 }, { 4245, 4302 }, { 4245, 4302 } } }, { "NtGdiGetCharWidthW", { 4259, { 4258, -1 }, { 4263, 4300 }, { 4263, 4295 }, { 4243, 4295 }, { 4245, 4296 }, { 4246, 4297 }, { 4246, 4297 } } }, { "NtGdiGetColorAdjustment", { 4261, { 4260, -1 }, { 4265, 4613 }, { 4265, 4621 }, { 4241, 4698 }, { 4243, 4722 }, { 4244, 4779 }, { 4244, 4783 } } }, { "NtGdiGetColorSpaceforBitmap", { 4262, { 4261, -1 }, { 4266, 4614 }, { 4266, 4622 }, { 4240, 4699 }, { 4242, 4723 }, { 4243, 4780 }, { 4243, 4784 } } }, { "NtGdiGetCOPPCompatibleOPMInformation", { -1, { -1, -1 }, { 4267, 4608 }, { 4267, 4616 }, { 4239, 4693 }, { 4241, 4717 }, { 4242, 4774 }, { 4242, 4776 } } }, { "NtGdiGetCurrentDpiInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4240, 4724 }, { 4241, 4781 }, { 4241, 4785 } } }, { "NtGdiGetDCDword", { 4263, { 4262, 4158 }, { 4268, 4159 }, { 4268, 4159 }, { 4238, 4160 }, { 4239, 4161 }, { 4240, 4162 }, { 4240, 4162 } } }, { "NtGdiGetDCforBitmap", { 4264, { 4263, -1 }, { 4269, 4253 }, { 4269, 4251 }, { 4237, 4251 }, { 4238, 4252 }, { 4239, 4253 }, { 4239, 4253 } } }, { "NtGdiGetDCObject", { 4265, { 4264, 4148 }, { 4270, 4149 }, { 4270, 4149 }, { 4236, 4150 }, { 4237, 4151 }, { 4238, 4152 }, { 4238, 4152 } } }, { "NtGdiGetDCPoint", { 4266, { 4265, -1 }, { 4271, 4212 }, { 4271, 4211 }, { 4235, 4211 }, { 4236, 4212 }, { 4237, 4213 }, { 4237, 4213 } } }, { "NtGdiGetDeviceCaps", { 4267, { 4266, 4543 }, { 4272, 4615 }, { 4272, 4623 }, { 4234, 4700 }, { 4235, 4725 }, { 4236, 4782 }, { 4236, 4786 } } }, { "NtGdiGetDeviceCapsAll", { 4269, { 4268, 4544 }, { 4274, 4616 }, { 4274, 4624 }, { 4232, 4701 }, { 4233, 4726 }, { 4234, 4783 }, { 4234, 4787 } } }, { "NtGdiGetDeviceGammaRamp", { 4268, { 4267, 4545 }, { 4273, 4617 }, { 4273, 4625 }, { 4233, 4702 }, { 4234, 4727 }, { 4235, 4784 }, { 4235, 4788 } } }, { "NtGdiGetDeviceWidth", { 4375, { 4374, -1 }, { 4383, 4618 }, { 4385, 4626 }, { 4121, 4703 }, { 4122, 4728 }, { 4123, 4785 }, { 4123, 4789 } } }, { "NtGdiGetDhpdev", { 4754, { 4750, 4547 }, { 4787, 4619 }, { 4819, 4627 }, { 4860, 4704 }, { 4869, 4729 }, { 4881, 4786 }, { 4882, 4790 } } }, { "NtGdiGetDIBitsInternal", { 4270, { 4269, -1 }, { 4275, 4231 }, { 4275, 4229 }, { 4231, 4229 }, { 4232, 4230 }, { 4233, 4231 }, { 4233, 4231 } } }, { "NtGdiGetEmbedFonts", { 4308, { 4307, 4550 }, { 4316, 4622 }, { 4318, 4630 }, { 4188, 4707 }, { 4189, 4732 }, { 4190, 4789 }, { 4190, 4793 } } }, { "NtGdiGetEmbUFI", { 4306, { 4305, -1 }, { 4314, 4621 }, { 4316, 4629 }, { 4190, 4706 }, { 4191, 4731 }, { 4192, 4788 }, { 4192, 4792 } } }, { "NtGdiGetETM", { 4271, { 4270, 4548 }, { 4276, 4620 }, { 4276, 4628 }, { 4230, 4705 }, { 4231, 4730 }, { 4232, 4787 }, { 4232, 4791 } } }, { "NtGdiGetEudcTimeStampEx", { 4272, { 4271, -1 }, { 4277, 4623 }, { 4277, 4631 }, { 4229, 4708 }, { 4230, 4733 }, { 4231, 4790 }, { 4231, 4794 } } }, { "NtGdiGetFontData", { 4273, { 4272, -1 }, { 4278, 4316 }, { 4278, 4311 }, { 4228, 4311 }, { 4229, 4312 }, { 4230, 4313 }, { 4230, 4313 } } }, { "NtGdiGetFontFileData", { -1, { -1, -1 }, { -1, -1 }, { 4279, 4632 }, { 4227, 4709 }, { 4228, 4734 }, { 4229, 4791 }, { 4229, 4795 } } }, { "NtGdiGetFontFileInfo", { -1, { -1, -1 }, { -1, -1 }, { 4280, 4633 }, { 4226, 4710 }, { 4227, 4735 }, { 4228, 4792 }, { 4228, 4796 } } }, { "NtGdiGetFontResourceInfoInternalW", { 4274, { 4273, -1 }, { 4279, 4624 }, { 4281, 4634 }, { 4225, 4711 }, { 4226, 4736 }, { 4227, 4793 }, { 4227, 4797 } } }, { "NtGdiGetFontUnicodeRanges", { 4311, { 4310, 4553 }, { 4319, 4625 }, { 4321, 4635 }, { 4185, 4712 }, { 4186, 4737 }, { 4187, 4794 }, { 4187, 4798 } } }, { "NtGdiGetGlyphIndicesW", { 4275, { 4274, -1 }, { 4280, 4626 }, { 4282, 4636 }, { 4224, 4713 }, { 4225, 4738 }, { 4226, 4795 }, { 4226, 4799 } } }, { "NtGdiGetGlyphIndicesWInternal", { 4276, { 4275, -1 }, { 4281, 4627 }, { 4283, 4637 }, { 4223, 4714 }, { 4224, 4739 }, { 4225, 4796 }, { 4225, 4800 } } }, { "NtGdiGetGlyphOutline", { 4277, { 4276, -1 }, { 4282, 4628 }, { 4284, 4638 }, { 4222, 4715 }, { 4223, 4740 }, { 4224, 4797 }, { 4224, 4801 } } }, { "NtGdiGetKerningPairs", { 4278, { 4277, 4557 }, { 4284, 4629 }, { 4286, 4639 }, { 4220, 4716 }, { 4221, 4741 }, { 4222, 4798 }, { 4222, 4802 } } }, { "NtGdiGetLinkedUFIs", { 4279, { 4278, 4558 }, { 4285, 4630 }, { 4287, 4640 }, { 4219, 4717 }, { 4220, 4742 }, { 4221, 4799 }, { 4221, 4803 } } }, { "NtGdiGetMiterLimit", { 4280, { 4279, -1 }, { 4286, 4631 }, { 4288, 4641 }, { 4218, 4718 }, { 4219, 4743 }, { 4220, 4800 }, { 4220, 4804 } } }, { "NtGdiGetMonitorID", { 4281, { 4280, 4560 }, { 4287, 4632 }, { 4289, 4642 }, { 4217, 4719 }, { 4218, 4744 }, { 4219, 4801 }, { 4219, 4805 } } }, { "NtGdiGetNearestColor", { 4282, { 4281, 4209 }, { 4288, 4210 }, { 4290, 4209 }, { 4216, 4209 }, { 4217, 4210 }, { 4218, 4211 }, { 4218, 4211 } } }, { "NtGdiGetNearestPaletteIndex", { 4283, { 4282, 4296 }, { 4289, 4297 }, { 4291, 4292 }, { 4215, 4292 }, { 4216, 4293 }, { 4217, 4294 }, { 4217, 4294 } } }, { "NtGdiGetNumberOfPhysicalMonitors", { -1, { -1, -1 }, { 4856, 4633 }, { 4900, 4643 }, { 4973, 4720 }, { 4991, 4745 }, { 5048, 4802 }, { 5050, 4806 } } }, { "NtGdiGetObjectBitmapHandle", { 4284, { 4283, -1 }, { 4290, 4636 }, { 4292, 4646 }, { 4214, 4723 }, { 4215, 4748 }, { 4216, 4805 }, { 4216, 4809 } } }, { "NtGdiGetOPMInformation", { -1, { -1, -1 }, { 4283, 4634 }, { 4285, 4644 }, { 4221, 4721 }, { 4222, 4746 }, { 4223, 4803 }, { 4223, 4807 } } }, { "NtGdiGetOPMRandomNumber", { -1, { -1, -1 }, { 4291, 4635 }, { 4293, 4645 }, { 4213, 4722 }, { 4214, 4747 }, { 4215, 4804 }, { 4215, 4808 } } }, { "NtGdiGetOutlineTextMetricsInternalW", { 4285, { 4284, 4279 }, { 4292, 4280 }, { 4294, 4275 }, { 4212, 4275 }, { 4213, 4276 }, { 4214, 4277 }, { 4214, 4277 } } }, { "NtGdiGetPath", { 4286, { 4285, 4562 }, { 4293, 4637 }, { 4295, 4647 }, { 4211, 4724 }, { 4212, 4749 }, { 4213, 4806 }, { 4213, 4810 } } }, { "NtGdiGetPerBandInfo", { 4220, { 4220, -1 }, { 4223, 4638 }, { 4224, 4648 }, { 4282, 4725 }, { 4284, 4750 }, { 4285, 4807 }, { 4287, 4811 } } }, { "NtGdiGetPhysicalMonitorDescription", { -1, { -1, -1 }, { 4858, 4639 }, { 4902, 4649 }, { 4971, 4726 }, { 4989, 4751 }, { 5046, 4808 }, { 5048, 4812 } } }, { "NtGdiGetPhysicalMonitors", { -1, { -1, -1 }, { 4857, 4640 }, { 4901, 4650 }, { 4972, 4727 }, { 4990, 4752 }, { 5047, 4809 }, { 5049, 4813 } } }, { "NtGdiGetPixel", { 4287, { 4286, 4291 }, { 4294, 4292 }, { 4296, 4287 }, { 4210, 4287 }, { 4211, 4288 }, { 4212, 4289 }, { 4212, 4289 } } }, { "NtGdiGetRandomRgn", { 4288, { 4287, 4138 }, { 4295, 4139 }, { 4297, 4139 }, { 4209, 4140 }, { 4210, 4141 }, { 4211, 4142 }, { 4211, 4142 } } }, { "NtGdiGetRasterizerCaps", { 4289, { 4288, 4331 }, { 4296, 4332 }, { 4298, 4327 }, { 4208, 4327 }, { 4209, 4328 }, { 4210, 4329 }, { 4210, 4329 } } }, { "NtGdiGetRealizationInfo", { 4290, { 4289, 4564 }, { 4297, 4641 }, { 4299, 4651 }, { 4207, 4728 }, { 4208, 4753 }, { 4209, 4810 }, { 4209, 4814 } } }, { "NtGdiGetRegionData", { 4291, { 4290, 4159 }, { 4298, 4160 }, { 4300, 4160 }, { 4206, 4161 }, { 4207, 4162 }, { 4208, 4163 }, { 4208, 4163 } } }, { "NtGdiGetRgnBox", { 4292, { 4291, -1 }, { 4299, 4199 }, { 4301, 4199 }, { 4205, 4199 }, { 4206, 4200 }, { 4207, 4201 }, { 4207, 4201 } } }, { "NtGdiGetServerMetaFileBits", { 4293, { 4292, -1 }, { 4300, 4642 }, { 4302, 4652 }, { 4204, 4729 }, { 4205, 4754 }, { 4206, 4811 }, { 4206, 4815 } } }, { "NtGdiGetSpoolMessage", { 4294, { 4293, 4566 }, { 4301, 4643 }, { 4303, 4653 }, { 4203, 4730 }, { 4204, 4755 }, { 4205, 4812 }, { 4205, 4816 } } }, { "NtGdiGetStats", { 4295, { 4294, -1 }, { 4302, 4644 }, { 4304, 4654 }, { 4202, 4731 }, { 4203, 4756 }, { 4204, 4813 }, { 4204, 4817 } } }, { "NtGdiGetStockObject", { 4296, { 4295, 4308 }, { 4303, 4309 }, { 4305, 4304 }, { 4201, 4304 }, { 4202, 4305 }, { 4203, 4306 }, { 4203, 4306 } } }, { "NtGdiGetStringBitmapW", { 4297, { 4296, -1 }, { 4304, 4645 }, { 4306, 4655 }, { 4200, 4732 }, { 4201, 4757 }, { 4202, 4814 }, { 4202, 4818 } } }, { "NtGdiGetSuggestedOPMProtectedOutputArraySize", { -1, { -1, -1 }, { 4305, 4646 }, { 4307, 4656 }, { 4199, 4733 }, { 4200, 4758 }, { 4201, 4815 }, { 4201, 4819 } } }, { "NtGdiGetSystemPaletteUse", { 4298, { 4297, 4376 }, { 4306, 4377 }, { 4308, 4370 }, { 4198, 4370 }, { 4199, 4371 }, { 4200, 4372 }, { 4200, 4372 } } }, { "NtGdiGetTextCharsetInfo", { 4299, { 4298, -1 }, { 4307, 4173 }, { 4309, 4173 }, { 4197, 4174 }, { 4198, 4175 }, { 4199, 4176 }, { 4199, 4176 } } }, { "NtGdiGetTextExtent", { 4300, { 4299, -1 }, { 4308, 4246 }, { 4310, 4244 }, { 4196, 4244 }, { 4197, 4245 }, { 4198, 4246 }, { 4198, 4246 } } }, { "NtGdiGetTextExtentExW", { 4301, { 4300, -1 }, { 4309, 4647 }, { 4311, 4657 }, { 4195, 4734 }, { 4196, 4759 }, { 4197, 4816 }, { 4197, 4820 } } }, { "NtGdiGetTextFaceW", { 4302, { 4301, 4225 }, { 4310, 4226 }, { 4312, 4224 }, { 4194, 4224 }, { 4195, 4225 }, { 4196, 4226 }, { 4196, 4226 } } }, { "NtGdiGetTextMetricsW", { 4303, { 4302, 4214 }, { 4311, 4215 }, { 4313, 4213 }, { 4193, 4213 }, { 4194, 4214 }, { 4195, 4215 }, { 4195, 4215 } } }, { "NtGdiGetTransform", { 4304, { 4303, -1 }, { 4312, 4321 }, { 4314, 4316 }, { 4192, 4316 }, { 4193, 4317 }, { 4194, 4318 }, { 4194, 4318 } } }, { "NtGdiGetUFI", { 4305, { 4304, -1 }, { 4313, 4648 }, { 4315, 4658 }, { 4191, 4735 }, { 4192, 4760 }, { 4193, 4817 }, { 4193, 4821 } } }, { "NtGdiGetUFIPathname", { 4307, { 4306, -1 }, { 4315, 4649 }, { 4317, 4659 }, { 4189, 4736 }, { 4190, 4761 }, { 4191, 4818 }, { 4191, 4822 } } }, { "NtGdiGetWidthTable", { 4312, { 4311, -1 }, { 4320, 4202 }, { 4322, 4202 }, { 4184, 4202 }, { 4185, 4203 }, { 4186, 4204 }, { 4186, 4204 } } }, { "NtGdiGradientFill", { 4313, { 4312, -1 }, { 4321, 4650 }, { 4323, 4660 }, { 4183, 4737 }, { 4184, 4762 }, { 4185, 4819 }, { 4185, 4823 } } }, { "NtGdiHfontCreate", { 4314, { 4313, -1 }, { 4322, 4189 }, { 4324, 4189 }, { 4182, 4189 }, { 4183, 4190 }, { 4184, 4191 }, { 4184, 4191 } } }, { "NtGdiHLSurfGetInformation", { -1, { -1, -1 }, { -1, -1 }, { 4829, 4661 }, { 4870, 4738 }, { 4879, 4763 }, { 4891, 4820 }, { 4892, 4824 } } }, { "NtGdiHLSurfSetInformation", { -1, { -1, -1 }, { -1, -1 }, { 4830, 4662 }, { 4869, 4739 }, { 4878, 4764 }, { 4890, 4821 }, { 4891, 4825 } } }, { "NtGdiHT_Get8BPPFormatPalette", { 4756, { 4752, 4573 }, { 4789, 4651 }, { 4821, 4663 }, { 4862, 4740 }, { 4871, 4765 }, { 4883, 4822 }, { 4884, 4826 } } }, { "NtGdiHT_Get8BPPMaskPalette", { 4757, { 4753, -1 }, { 4790, 4652 }, { 4822, 4664 }, { 4861, 4741 }, { 4870, 4766 }, { 4882, 4823 }, { 4883, 4827 } } }, { "NtGdiIcmBrushInfo", { 4315, { 4314, -1 }, { 4323, 4653 }, { 4325, 4665 }, { 4181, 4742 }, { 4182, 4767 }, { 4183, 4824 }, { 4183, 4828 } } }, { "NtGdiInit", { 4316, { 4315, 4636 }, { 4324, 4654 }, { 4326, 4666 }, { 4180, 4743 }, { 4181, 4768 }, { 4182, 4825 }, { 4182, 4829 } } }, { "NtGdiInitSpool", { 4317, { 4316, 4577 }, { 4325, 4655 }, { 4327, 4667 }, { 4179, 4744 }, { 4180, 4769 }, { 4181, 4826 }, { 4181, 4830 } } }, { "NtGdiIntersectClipRect", { 4318, { 4317, -1 }, { 4326, 4128 }, { 4328, 4128 }, { 4178, 4129 }, { 4179, 4130 }, { 4180, 4131 }, { 4180, 4131 } } }, { "NtGdiInvertRgn", { 4319, { 4318, 4197 }, { 4327, 4198 }, { 4329, 4198 }, { 4177, 4198 }, { 4178, 4199 }, { 4179, 4200 }, { 4179, 4200 } } }, { "NtGdiLineTo", { 4320, { 4319, 4160 }, { 4328, 4161 }, { 4330, 4161 }, { 4176, 4162 }, { 4177, 4163 }, { 4178, 4164 }, { 4178, 4164 } } }, { "NtGdiMakeFontDir", { 4321, { 4320, -1 }, { 4329, 4656 }, { 4331, 4668 }, { 4175, 4745 }, { 4176, 4770 }, { 4177, 4827 }, { 4177, 4831 } } }, { "NtGdiMakeInfoDC", { 4322, { 4321, -1 }, { 4330, 4657 }, { 4332, 4669 }, { 4174, 4746 }, { 4175, 4771 }, { 4176, 4828 }, { 4176, 4832 } } }, { "NtGdiMakeObjectUnXferable", { -1, { 4760, 4580 }, { 4855, 4658 }, { 4899, 4670 }, { 4968, 4747 }, { 4986, 4772 }, { 5043, 4829 }, { 5045, 4833 } } }, { "NtGdiMakeObjectXferable", { -1, { 4759, 4581 }, { 4854, 4659 }, { 4898, 4671 }, { 4969, 4748 }, { 4987, 4773 }, { 5044, 4830 }, { 5046, 4834 } } }, { "NtGdiMaskBlt", { 4323, { 4322, -1 }, { 4331, 4201 }, { 4333, 4201 }, { 4173, 4201 }, { 4174, 4202 }, { 4175, 4203 }, { 4175, 4203 } } }, { "NtGdiMirrorWindowOrg", { 4376, { 4375, 4582 }, { 4384, 4660 }, { 4386, 4672 }, { 4120, 4749 }, { 4121, 4774 }, { 4122, 4831 }, { 4122, 4835 } } }, { "NtGdiModifyWorldTransform", { 4324, { 4323, 4314 }, { 4332, 4315 }, { 4334, 4310 }, { 4172, 4310 }, { 4173, 4311 }, { 4174, 4312 }, { 4174, 4312 } } }, { "NtGdiMonoBitmap", { 4325, { 4324, -1 }, { 4333, 4661 }, { 4335, 4673 }, { 4171, 4750 }, { 4172, 4775 }, { 4173, 4832 }, { 4173, 4836 } } }, { "NtGdiMoveTo", { 4326, { 4325, -1 }, { 4334, 4662 }, { 4336, 4674 }, { 4170, 4751 }, { 4171, 4776 }, { 4172, 4833 }, { 4172, 4837 } } }, { "NtGdiOffsetClipRgn", { 4327, { 4326, 4585 }, { 4335, 4663 }, { 4337, 4675 }, { 4169, 4752 }, { 4170, 4777 }, { 4171, 4834 }, { 4171, 4838 } } }, { "NtGdiOffsetRgn", { 4328, { 4327, 4223 }, { 4336, 4224 }, { 4338, 4222 }, { 4168, 4222 }, { 4169, 4223 }, { 4170, 4224 }, { 4170, 4224 } } }, { "NtGdiOpenDCW", { 4329, { 4328, -1 }, { 4337, 4319 }, { 4339, 4314 }, { 4167, 4314 }, { 4168, 4315 }, { 4169, 4316 }, { 4169, 4316 } } }, { "NtGdiPatBlt", { 4330, { 4329, -1 }, { 4338, 4186 }, { 4340, 4186 }, { 4166, 4186 }, { 4167, 4187 }, { 4168, 4188 }, { 4168, 4188 } } }, { "NtGdiPATHOBJ_bEnum", { 4750, { 4746, 4586 }, { 4783, 4664 }, { 4815, 4676 }, { 4857, 4753 }, { 4866, 4778 }, { 4878, 4835 }, { 4879, 4839 } } }, { "NtGdiPATHOBJ_bEnumClipLines", { 4753, { 4749, 4587 }, { 4786, 4665 }, { 4818, 4677 }, { 4854, 4754 }, { 4863, 4779 }, { 4875, 4836 }, { 4876, 4840 } } }, { "NtGdiPATHOBJ_vEnumStart", { 4751, { 4747, -1 }, { 4784, 4666 }, { 4816, 4678 }, { 4856, 4755 }, { 4865, 4780 }, { 4877, 4837 }, { 4878, 4841 } } }, { "NtGdiPATHOBJ_vEnumStartClipLines", { 4752, { 4748, 4589 }, { 4785, 4667 }, { 4817, 4679 }, { 4855, 4756 }, { 4864, 4781 }, { 4876, 4838 }, { 4877, 4842 } } }, { "NtGdiPATHOBJ_vGetBounds", { 4749, { 4745, 4590 }, { 4782, 4668 }, { 4814, 4680 }, { 4858, 4757 }, { 4867, 4782 }, { 4879, 4839 }, { 4880, 4843 } } }, { "NtGdiPathToRegion", { 4332, { 4331, 4591 }, { 4340, 4669 }, { 4342, 4681 }, { 4164, 4758 }, { 4165, 4783 }, { 4166, 4840 }, { 4166, 4844 } } }, { "NtGdiPlgBlt", { 4333, { 4332, -1 }, { 4341, 4670 }, { 4343, 4682 }, { 4163, 4759 }, { 4164, 4784 }, { 4165, 4841 }, { 4165, 4845 } } }, { "NtGdiPolyDraw", { 4334, { 4333, 4593 }, { 4342, 4671 }, { 4344, 4683 }, { 4162, 4760 }, { 4163, 4785 }, { 4164, 4842 }, { 4164, 4846 } } }, { "NtGdiPolyPatBlt", { 4331, { 4330, -1 }, { 4339, 4208 }, { 4341, 4207 }, { 4165, 4207 }, { 4166, 4208 }, { 4167, 4209 }, { 4167, 4209 } } }, { "NtGdiPolyPolyDraw", { 4335, { 4334, -1 }, { 4343, 4168 }, { 4345, 4168 }, { 4161, 4169 }, { 4162, 4170 }, { 4163, 4171 }, { 4163, 4171 } } }, { "NtGdiPolyTextOutW", { 4336, { 4335, 4594 }, { 4344, 4672 }, { 4346, 4684 }, { 4160, 4761 }, { 4161, 4786 }, { 4162, 4843 }, { 4162, 4847 } } }, { "NtGdiPtInRegion", { 4337, { 4336, 4595 }, { 4345, 4673 }, { 4347, 4685 }, { 4159, 4762 }, { 4160, 4787 }, { 4161, 4844 }, { 4161, 4848 } } }, { "NtGdiPtVisible", { 4338, { 4337, 4596 }, { 4346, 4674 }, { 4348, 4686 }, { 4158, 4763 }, { 4159, 4788 }, { 4160, 4845 }, { 4160, 4849 } } }, { "NtGdiQueryFontAssocInfo", { 4340, { 4339, 4345 }, { 4348, 4346 }, { 4350, 4341 }, { 4156, 4341 }, { 4157, 4342 }, { 4158, 4343 }, { 4158, 4343 } } }, { "NtGdiQueryFonts", { 4339, { 4338, 4597 }, { 4347, 4675 }, { 4349, 4687 }, { 4157, 4764 }, { 4158, 4789 }, { 4159, 4846 }, { 4159, 4850 } } }, { "NtGdiRectangle", { 4341, { 4340, -1 }, { 4349, 4242 }, { 4351, 4240 }, { 4155, 4240 }, { 4156, 4241 }, { 4157, 4242 }, { 4157, 4242 } } }, { "NtGdiRectInRegion", { 4342, { 4341, 4289 }, { 4350, 4290 }, { 4352, 4285 }, { 4154, 4285 }, { 4155, 4286 }, { 4156, 4287 }, { 4156, 4287 } } }, { "NtGdiRectVisible", { 4343, { 4342, 4146 }, { 4351, 4147 }, { 4353, 4147 }, { 4153, 4148 }, { 4154, 4149 }, { 4155, 4150 }, { 4155, 4150 } } }, { "NtGdiRemoveFontMemResourceEx", { 4345, { 4344, 4377 }, { 4353, 4378 }, { 4355, 4371 }, { 4151, 4371 }, { 4152, 4372 }, { 4153, 4373 }, { 4153, 4373 } } }, { "NtGdiRemoveFontResourceW", { 4344, { 4343, -1 }, { 4352, 4676 }, { 4354, 4688 }, { 4152, 4765 }, { 4153, 4790 }, { 4154, 4847 }, { 4154, 4851 } } }, { "NtGdiRemoveMergeFont", { 4101, { 4101, 4599 }, { 4101, 4677 }, { 4101, 4689 }, { 4407, 4766 }, { 4409, 4791 }, { 4410, 4848 }, { 4412, 4852 } } }, { "NtGdiResetDC", { 4346, { 4345, -1 }, { 4354, 4678 }, { 4356, 4690 }, { 4150, 4767 }, { 4151, 4792 }, { 4152, 4849 }, { 4152, 4853 } } }, { "NtGdiResizePalette", { 4347, { 4346, 4601 }, { 4355, 4679 }, { 4357, 4691 }, { 4149, 4768 }, { 4150, 4793 }, { 4151, 4850 }, { 4151, 4854 } } }, { "NtGdiRestoreDC", { 4348, { 4347, 4153 }, { 4356, 4154 }, { 4358, 4154 }, { 4148, 4155 }, { 4149, 4156 }, { 4150, 4157 }, { 4150, 4157 } } }, { "NtGdiRoundRect", { 4349, { 4348, -1 }, { 4357, 4680 }, { 4359, 4692 }, { 4147, 4769 }, { 4148, 4794 }, { 4149, 4851 }, { 4149, 4855 } } }, { "NtGdiSaveDC", { 4350, { 4349, 4154 }, { 4358, 4155 }, { 4360, 4155 }, { 4146, 4156 }, { 4147, 4157 }, { 4148, 4158 }, { 4148, 4158 } } }, { "NtGdiScaleViewportExtEx", { 4351, { 4350, -1 }, { 4359, 4686 }, { 4361, 4698 }, { 4145, 4775 }, { 4146, 4800 }, { 4147, 4857 }, { 4147, 4861 } } }, { "NtGdiScaleWindowExtEx", { 4352, { 4351, -1 }, { 4360, 4687 }, { 4362, 4699 }, { 4144, 4776 }, { 4145, 4801 }, { 4146, 4858 }, { 4146, 4862 } } }, { "NtGdiSelectBitmap", { 4353, { 4352, 4107 }, { 4361, 4107 }, { 4363, 4107 }, { 4143, 4108 }, { 4144, 4109 }, { 4145, 4110 }, { 4145, 4110 } } }, { "NtGdiSelectBrush", { 4354, { 4353, -1 }, { 4362, 4688 }, { 4364, 4700 }, { 4142, 4777 }, { 4143, 4802 }, { 4144, 4859 }, { 4144, 4863 } } }, { "NtGdiSelectClipPath", { 4355, { 4354, 4611 }, { 4363, 4689 }, { 4365, 4701 }, { 4141, 4778 }, { 4142, 4803 }, { 4143, 4860 }, { 4143, 4864 } } }, { "NtGdiSelectFont", { 4356, { 4355, 4152 }, { 4364, 4153 }, { 4366, 4153 }, { 4140, 4154 }, { 4141, 4155 }, { 4142, 4156 }, { 4142, 4156 } } }, { "NtGdiSelectPen", { 4357, { 4356, -1 }, { 4365, 4690 }, { 4367, 4702 }, { 4139, 4779 }, { 4140, 4804 }, { 4141, 4861 }, { 4141, 4865 } } }, { "NtGdiSetBitmapAttributes", { 4358, { 4357, 4613 }, { 4366, 4691 }, { 4368, 4703 }, { 4138, 4780 }, { 4139, 4805 }, { 4140, 4862 }, { 4140, 4866 } } }, { "NtGdiSetBitmapBits", { 4359, { 4358, 4280 }, { 4367, 4281 }, { 4369, 4276 }, { 4137, 4276 }, { 4138, 4277 }, { 4139, 4278 }, { 4139, 4278 } } }, { "NtGdiSetBitmapDimension", { 4360, { 4359, -1 }, { 4368, 4382 }, { 4370, 4375 }, { 4136, 4375 }, { 4137, 4376 }, { 4138, 4377 }, { 4138, 4377 } } }, { "NtGdiSetBoundsRect", { 4361, { 4360, 4351 }, { 4369, 4352 }, { 4371, 4347 }, { 4135, 4347 }, { 4136, 4348 }, { 4137, 4349 }, { 4137, 4349 } } }, { "NtGdiSetBrushAttributes", { 4362, { 4114, 4614 }, { 4370, 4692 }, { 4372, 4704 }, { 4134, 4781 }, { 4135, 4806 }, { 4136, 4863 }, { 4136, 4867 } } }, { "NtGdiSetBrushOrg", { 4363, { 4362, -1 }, { 4371, 4274 }, { 4373, 4269 }, { 4133, 4269 }, { 4134, 4270 }, { 4135, 4271 }, { 4135, 4271 } } }, { "NtGdiSetColorAdjustment", { 4364, { 4363, 4615 }, { 4372, 4693 }, { 4374, 4705 }, { 4132, 4782 }, { 4133, 4807 }, { 4134, 4864 }, { 4134, 4868 } } }, { "NtGdiSetColorSpace", { 4365, { 4364, 4616 }, { 4373, 4694 }, { 4375, 4706 }, { 4131, 4783 }, { 4132, 4808 }, { 4133, 4865 }, { 4133, 4869 } } }, { "NtGdiSetDeviceGammaRamp", { 4366, { 4365, 4617 }, { 4374, 4695 }, { 4376, 4707 }, { 4130, 4784 }, { 4131, 4809 }, { 4132, 4866 }, { 4132, 4870 } } }, { "NtGdiSetDIBitsToDeviceInternal", { 4367, { 4366, -1 }, { 4375, 4137 }, { 4377, 4137 }, { 4129, 4138 }, { 4130, 4139 }, { 4131, 4140 }, { 4131, 4140 } } }, { "NtGdiSetFontEnumeration", { 4368, { 4367, 4382 }, { 4376, 4383 }, { 4378, 4376 }, { 4128, 4376 }, { 4129, 4377 }, { 4130, 4378 }, { 4130, 4378 } } }, { "NtGdiSetFontXform", { 4369, { 4368, 4618 }, { 4377, 4696 }, { 4379, 4708 }, { 4127, 4785 }, { 4128, 4810 }, { 4129, 4867 }, { 4129, 4871 } } }, { "NtGdiSetIcmMode", { 4370, { 4369, 4619 }, { 4378, 4697 }, { 4380, 4709 }, { 4126, 4786 }, { 4127, 4811 }, { 4128, 4868 }, { 4128, 4872 } } }, { "NtGdiSetLayout", { 4377, { 4376, 4247 }, { 4385, 4248 }, { 4387, 4246 }, { 4119, 4246 }, { 4120, 4247 }, { 4121, 4248 }, { 4121, 4248 } } }, { "NtGdiSetLinkedUFIs", { 4371, { 4370, 4620 }, { 4379, 4698 }, { 4381, 4710 }, { 4125, 4787 }, { 4126, 4812 }, { 4127, 4869 }, { 4127, 4873 } } }, { "NtGdiSetMagicColors", { 4372, { 4371, 4621 }, { 4380, 4699 }, { 4382, 4711 }, { 4124, 4788 }, { 4125, 4813 }, { 4126, 4870 }, { 4126, 4874 } } }, { "NtGdiSetMetaRgn", { 4373, { 4372, -1 }, { 4381, 4329 }, { 4383, 4324 }, { 4123, 4324 }, { 4124, 4325 }, { 4125, 4326 }, { 4125, 4326 } } }, { "NtGdiSetMiterLimit", { 4374, { 4373, 4329 }, { 4382, 4330 }, { 4384, 4325 }, { 4122, 4325 }, { 4123, 4326 }, { 4124, 4327 }, { 4124, 4327 } } }, { "NtGdiSetOPMSigningKeyAndSequenceNumbers", { -1, { -1, -1 }, { 4386, 4700 }, { 4388, 4712 }, { 4118, 4789 }, { 4119, 4814 }, { 4120, 4871 }, { 4120, 4875 } } }, { "NtGdiSetPixel", { 4378, { 4377, 4275 }, { 4387, 4276 }, { 4389, 4271 }, { 4117, 4271 }, { 4118, 4272 }, { 4119, 4273 }, { 4119, 4273 } } }, { "NtGdiSetPixelFormat", { 4379, { 4378, 4623 }, { 4388, 4702 }, { 4390, 4714 }, { 4116, 4791 }, { 4117, 4816 }, { 4118, 4873 }, { 4118, 4877 } } }, { "NtGdiSetPUMPDOBJ", { 4759, { 4755, 4622 }, { 4792, 4701 }, { 4824, 4713 }, { 4866, 4790 }, { 4875, 4815 }, { 4887, 4872 }, { 4888, 4876 } } }, { "NtGdiSetRectRgn", { 4380, { 4379, -1 }, { 4389, 4703 }, { 4391, 4715 }, { 4115, 4792 }, { 4116, 4817 }, { 4117, 4874 }, { 4117, 4878 } } }, { "NtGdiSetSizeDevice", { 4385, { 4384, 4625 }, { 4394, 4704 }, { 4395, 4716 }, { 4111, 4793 }, { 4112, 4818 }, { 4113, 4875 }, { 4113, 4879 } } }, { "NtGdiSetSystemPaletteUse", { 4381, { 4380, 4626 }, { 4390, 4705 }, { 4392, 4717 }, { 4114, 4794 }, { 4115, 4819 }, { 4116, 4876 }, { 4116, 4880 } } }, { "NtGdiSetTextJustification", { 4382, { 4381, 4627 }, { 4391, 4706 }, { 4393, 4718 }, { 4113, 4795 }, { 4114, 4820 }, { 4115, 4877 }, { 4115, 4881 } } }, { "NtGdiSetUMPDSandboxState", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4867, 4796 }, { 4876, 4821 }, { 4888, 4878 }, { 4889, 4882 } } }, { "NtGdiSetupPublicCFONT", { 4383, { 4382, 4363 }, { 4392, 4364 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiSetVirtualResolution", { 4384, { 4383, -1 }, { 4393, 4331 }, { 4394, 4326 }, { 4112, 4326 }, { 4113, 4327 }, { 4114, 4328 }, { 4114, 4328 } } }, { "NtGdiSfmGetNotificationTokens", { -1, { -1, -1 }, { -1, -1 }, { 4828, 4719 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtGdiStartDoc", { 4386, { 4385, 4628 }, { 4395, 4707 }, { 4396, 4720 }, { 4110, 4797 }, { 4111, 4822 }, { 4112, 4879 }, { 4112, 4883 } } }, { "NtGdiStartPage", { 4387, { 4386, 4629 }, { 4396, 4708 }, { 4397, 4721 }, { 4109, 4798 }, { 4110, 4823 }, { 4111, 4880 }, { 4111, 4884 } } }, { "NtGdiStretchBlt", { 4388, { 4387, -1 }, { 4397, 4145 }, { 4398, 4145 }, { 4108, 4146 }, { 4109, 4147 }, { 4110, 4148 }, { 4110, 4148 } } }, { "NtGdiStretchDIBitsInternal", { 4389, { 4388, -1 }, { 4398, 4227 }, { 4399, 4225 }, { 4107, 4225 }, { 4108, 4226 }, { 4109, 4227 }, { 4109, 4227 } } }, { "NtGdiSTROBJ_bEnum", { 4744, { 4740, 4603 }, { 4777, 4681 }, { 4809, 4693 }, { 4853, 4770 }, { 4862, 4795 }, { 4874, 4852 }, { 4875, 4856 } } }, { "NtGdiSTROBJ_bEnumPositionsOnly", { 4745, { 4741, 4604 }, { 4778, 4682 }, { 4810, 4694 }, { 4852, 4771 }, { 4861, 4796 }, { 4873, 4853 }, { 4874, 4857 } } }, { "NtGdiSTROBJ_bGetAdvanceWidths", { 4746, { 4742, 4605 }, { 4779, 4683 }, { 4811, 4695 }, { 4851, 4772 }, { 4860, 4797 }, { 4872, 4854 }, { 4873, 4858 } } }, { "NtGdiSTROBJ_dwGetCodePage", { 4748, { 4744, -1 }, { 4781, 4684 }, { 4813, 4696 }, { 4849, 4773 }, { 4858, 4798 }, { 4870, 4855 }, { 4871, 4859 } } }, { "NtGdiSTROBJ_vEnumStart", { 4747, { 4743, -1 }, { 4780, 4685 }, { 4812, 4697 }, { 4850, 4774 }, { 4859, 4799 }, { 4871, 4856 }, { 4872, 4860 } } }, { "NtGdiStrokeAndFillPath", { 4390, { 4389, 4630 }, { 4399, 4709 }, { 4400, 4722 }, { 4106, 4799 }, { 4107, 4824 }, { 4108, 4881 }, { 4108, 4885 } } }, { "NtGdiStrokePath", { 4391, { 4390, 4631 }, { 4400, 4710 }, { 4401, 4723 }, { 4105, 4800 }, { 4106, 4825 }, { 4107, 4882 }, { 4107, 4886 } } }, { "NtGdiSwapBuffers", { 4392, { 4391, 4632 }, { 4401, 4711 }, { 4402, 4724 }, { 4104, 4801 }, { 4105, 4826 }, { 4106, 4883 }, { 4106, 4887 } } }, { "NtGdiTransformPoints", { 4393, { 4392, -1 }, { 4402, 4211 }, { 4403, 4210 }, { 4103, 4210 }, { 4104, 4211 }, { 4105, 4212 }, { 4105, 4212 } } }, { "NtGdiTransparentBlt", { 4394, { 4393, -1 }, { 4403, 4712 }, { 4404, 4725 }, { 4102, 4802 }, { 4103, 4827 }, { 4104, 4884 }, { 4104, 4888 } } }, { "NtGdiUMPDEngFreeUserMem", { 4396, { 4395, 4634 }, { 4405, 4713 }, { 4406, 4726 }, { 4864, 4803 }, { 4873, 4828 }, { 4885, 4885 }, { 4886, 4889 } } }, { "NtGdiUnloadPrinterDriver", { 4395, { 4394, 4635 }, { 4404, 4714 }, { 4115, 4727 }, { 4101, 4804 }, { 4102, 4829 }, { 4103, 4886 }, { 4103, 4890 } } }, { "NtGdiUnmapMemFont", { 4761, { 4757, 4576 }, { 4794, 4715 }, { 4826, 4728 }, { 4100, 4805 }, { 4101, 4830 }, { 4102, 4887 }, { 4102, 4891 } } }, { "NtGdiUnrealizeObject", { 4397, { 4396, 4239 }, { 4406, 4240 }, { 4407, 4238 }, { 4099, 4238 }, { 4100, 4239 }, { 4101, 4240 }, { 4101, 4240 } } }, { "NtGdiUpdateColors", { 4398, { 4397, 4637 }, { 4407, 4716 }, { 4408, 4729 }, { 4098, 4806 }, { 4099, 4831 }, { 4100, 4888 }, { 4100, 4892 } } }, { "NtGdiUpdateTransform", { 4758, { 4754, 4638 }, { 4791, 4717 }, { 4823, 4730 }, { 4863, 4807 }, { 4872, 4832 }, { 4884, 4889 }, { 4885, 4893 } } }, { "NtGdiWidenPath", { 4399, { 4398, 4639 }, { 4408, 4718 }, { 4409, 4731 }, { 4097, 4808 }, { 4098, 4833 }, { 4099, 4890 }, { 4099, 4894 } } }, { "NtGdiXFORMOBJ_bApplyXform", { 4734, { 4730, -1 }, { 4767, 4719 }, { 4799, 4732 }, { 4840, 4809 }, { 4849, 4834 }, { 4861, 4891 }, { 4862, 4895 } } }, { "NtGdiXFORMOBJ_iGetXform", { 4735, { 4731, 4641 }, { 4768, 4720 }, { 4800, 4733 }, { 4839, 4810 }, { 4848, 4835 }, { 4860, 4892 }, { 4861, 4896 } } }, { "NtGdiXLATEOBJ_cGetPalette", { 4721, { 4717, 4642 }, { 4754, 4721 }, { 4786, 4734 }, { 4828, 4811 }, { 4837, 4836 }, { 4849, 4893 }, { 4850, 4897 } } }, { "NtGdiXLATEOBJ_hGetColorTransform", { 4723, { 4719, 4643 }, { 4756, 4722 }, { 4788, 4735 }, { 4826, 4812 }, { 4835, 4837 }, { 4847, 4894 }, { 4848, 4898 } } }, { "NtGdiXLATEOBJ_iXlate", { 4722, { 4718, 4644 }, { 4755, 4723 }, { 4787, 4736 }, { 4827, 4813 }, { 4836, 4838 }, { 4848, 4895 }, { 4849, 4899 } } }, { "NtHWCursorUpdatePointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5223, 4896 }, { 5228, 4900 } } }, { "NtNotifyPresentToCompositionSurface", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4997, 4814 }, { 5015, 4839 }, { 5072, 4897 }, { 5074, 4901 } } }, { "NtOpenCompositionSurfaceDirtyRegion", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5002, 4815 }, { 5020, 4840 }, { 5077, 4898 }, { 5079, 4902 } } }, { "NtOpenCompositionSurfaceSectionInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4999, 4816 }, { 5017, 4841 }, { 5074, 4899 }, { 5076, 4903 } } }, { "NtOpenCompositionSurfaceSwapChainHandleInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5000, 4817 }, { 5018, 4842 }, { 5075, 4900 }, { 5077, 4904 } } }, { "NtQueryCompositionInputIsImplicit", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5095, 4901 }, { 5097, 4905 } } }, { "NtQueryCompositionInputQueueAndTransform", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5094, 4902 }, { 5096, 4906 } } }, { "NtQueryCompositionInputSink", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5027, 4843 }, { 5089, 4903 }, { 5091, 4907 } } }, { "NtQueryCompositionInputSinkLuid", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5028, 4844 }, { 5090, 4904 }, { 5092, 4908 } } }, { "NtQueryCompositionInputSinkViewId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5091, 4905 }, { 5093, 4909 } } }, { "NtQueryCompositionSurfaceBinding", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4996, 4818 }, { 5014, 4845 }, { 5071, 4906 }, { 5073, 4910 } } }, { "NtQueryCompositionSurfaceRenderingRealization", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5001, 4819 }, { 5019, 4846 }, { 5076, 4907 }, { 5078, 4911 } } }, { "NtQueryCompositionSurfaceStatistics", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4998, 4820 }, { 5016, 4847 }, { 5073, 4908 }, { 5075, 4912 } } }, { "NtRIMAddInputObserver", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5215, 4909 }, { 5220, 4913 } } }, { "NtRIMGetDevicePreparsedDataLockfree", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5219, 4910 }, { 5224, 4914 } } }, { "NtRIMObserveNextInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5218, 4911 }, { 5223, 4915 } } }, { "NtRIMRemoveInputObserver", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5216, 4912 }, { 5221, 4916 } } }, { "NtRIMUpdateInputObserverRegistration", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5217, 4913 }, { 5222, 4917 } } }, { "NtSetCompositionSurfaceAnalogExclusive", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5104, 4914 }, { 5107, 4918 } } }, { "NtSetCompositionSurfaceBufferCompositionMode", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5023, 4848 }, { 5080, 4915 }, { -1, -1 } } }, { "NtSetCompositionSurfaceBufferCompositionModeAndOrientation", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 4919 }, { 5082, 4919 } } }, { "NtSetCompositionSurfaceIndependentFlipInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5024, 4849 }, { 5081, 4916 }, { 5083, 4920 } } }, { "NtSetCompositionSurfaceOutOfFrameDirectFlipNotification", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5003, 4821 }, { 5021, 4850 }, { 5078, 4917 }, { 5080, 4921 } } }, { "NtSetCompositionSurfaceStatistics", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5004, 4822 }, { 5022, 4851 }, { 5079, 4918 }, { 5081, 4922 } } }, { "NtTokenManagerConfirmOutstandingAnalogToken", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5103, 4919 }, { 5106, 4923 } } }, { "NtTokenManagerCreateCompositionTokenHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5036, 4852 }, { 5100, 4920 }, { 5103, 4924 } } }, { "NtTokenManagerDeleteOutstandingDirectFlipTokens", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5035, 4853 }, { 5099, 4921 }, { 5102, 4925 } } }, { "NtTokenManagerGetAnalogExclusiveSurfaceUpdates", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5102, 4922 }, { 5105, 4926 } } }, { "NtTokenManagerGetAnalogExclusiveTokenEvent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5101, 4923 }, { 5104, 4927 } } }, { "NtTokenManagerGetOutOfFrameDirectFlipSurfaceUpdates", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5007, 4823 }, { 5034, 4854 }, { 5098, 4924 }, { 5101, 4928 } } }, { "NtTokenManagerOpenEvent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5005, 4824 }, { 5032, 4855 }, { -1, -1 }, { -1, -1 } } }, { "NtTokenManagerOpenSection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5031, 4856 }, { -1, -1 }, { -1, -1 } } }, { "NtTokenManagerOpenSectionAndEvents", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5096, 4925 }, { 5099, 4929 } } }, { "NtTokenManagerThread", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5006, 4825 }, { 5033, 4857 }, { 5097, 4926 }, { 5100, 4930 } } }, { "NtUnBindCompositionSurface", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4995, 4826 }, { 5013, 4858 }, { 5070, 4927 }, { 5072, 4931 } } }, { "NtUpdateInputSinkTransforms", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5029, 4859 }, { 5092, 4928 }, { 5094, 4932 } } }, { "NtUserAcquireIAMKey", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5063, 4827 }, { 5102, 4860 }, { 5177, 4929 }, { 5180, 4933 } } }, { "NtUserActivateKeyboardLayout", { 4400, { 4399, 4390 }, { 4409, 4391 }, { 4410, 4382 }, { 4465, 4382 }, { 4467, 4383 }, { 4468, 4384 }, { 4470, 4384 } } }, { "NtUserAddClipboardFormatListener", { -1, { -1, -1 }, { 4410, 4724 }, { 4411, 4737 }, { 4464, 4828 }, { 4466, 4861 }, { 4467, 4930 }, { 4469, 4934 } } }, { "NtUserAlterWindowStyle", { 4401, { 4400, 4311 }, { 4411, 4312 }, { 4412, 4307 }, { 4463, 4307 }, { 4465, 4308 }, { 4466, 4309 }, { 4468, 4309 } } }, { "NtUserAssociateInputContext", { 4402, { 4401, 4645 }, { 4412, 4725 }, { 4413, 4738 }, { 4462, 4829 }, { 4464, 4862 }, { 4465, 4931 }, { 4467, 4935 } } }, { "NtUserAttachThreadInput", { 4403, { 4402, 4336 }, { 4413, 4337 }, { 4414, 4332 }, { 4461, 4332 }, { 4463, 4333 }, { 4464, 4334 }, { 4466, 4334 } } }, { "NtUserAutoPromoteMouseInPointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5073, 4830 }, { 5114, 4863 }, { 5191, 4932 }, { 5195, 4936 } } }, { "NtUserAutoRotateScreen", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5061, 4831 }, { 5101, 4864 }, { 5176, 4933 }, { 5179, 4937 } } }, { "NtUserBeginPaint", { 4404, { 4403, 4118 }, { 4414, 4119 }, { 4415, 4119 }, { 4460, 4120 }, { 4462, 4121 }, { 4463, 4122 }, { 4465, 4122 } } }, { "NtUserBitBltSysBmp", { 4405, { 4404, 4303 }, { 4415, 4304 }, { 4416, 4299 }, { 4459, 4299 }, { 4461, 4300 }, { 4462, 4301 }, { 4464, 4301 } } }, { "NtUserBlockInput", { 4406, { 4405, 4646 }, { 4416, 4726 }, { 4417, 4739 }, { 4458, 4832 }, { 4460, 4865 }, { 4461, 4934 }, { 4463, 4938 } } }, { "NtUserBuildHimcList", { 4407, { 4406, 4647 }, { 4417, 4727 }, { 4418, 4740 }, { 4457, 4833 }, { 4459, 4866 }, { 4460, 4935 }, { 4462, 4939 } } }, { "NtUserBuildHwndList", { 4408, { 4407, 4123 }, { 4418, 4124 }, { 4419, 4124 }, { 4456, 4125 }, { 4458, 4126 }, { 4459, 4127 }, { 4461, 4127 } } }, { "NtUserBuildNameList", { 4409, { 4408, 4274 }, { 4419, 4275 }, { 4420, 4270 }, { 4455, 4270 }, { 4457, 4271 }, { 4458, 4272 }, { 4460, 4272 } } }, { "NtUserBuildPropList", { 4410, { 4409, 4648 }, { 4420, 4728 }, { 4421, 4741 }, { 4454, 4834 }, { 4456, 4867 }, { 4457, 4936 }, { 4459, 4940 } } }, { "NtUserCalcMenuBar", { 4662, { 4658, 4248 }, { 4686, 4249 }, { 4699, 4247 }, { 4633, 4247 }, { 4636, 4248 }, { 4639, 4249 }, { 4641, 4249 } } }, { "NtUserCalculatePopupWindowPosition", { -1, { -1, -1 }, { -1, -1 }, { 4698, 4742 }, { 4634, 4835 }, { 4637, 4868 }, { 4640, 4937 }, { 4642, 4941 } } }, { "NtUserCallHwnd", { 4411, { 4410, 4370 }, { 4421, 4371 }, { 4422, 4364 }, { 4453, 4364 }, { 4455, 4365 }, { 4456, 4366 }, { 4458, 4366 } } }, { "NtUserCallHwndLock", { 4412, { 4411, 4128 }, { 4422, 4129 }, { 4423, 4129 }, { 4452, 4130 }, { 4454, 4131 }, { 4455, 4132 }, { 4457, 4132 } } }, { "NtUserCallHwndOpt", { 4413, { 4412, 4649 }, { 4423, 4729 }, { 4424, 4743 }, { 4451, 4836 }, { 4453, 4869 }, { 4454, 4938 }, { 4456, 4942 } } }, { "NtUserCallHwndParam", { 4414, { 4413, 4255 }, { 4424, 4256 }, { 4425, 4254 }, { 4450, 4254 }, { 4452, 4255 }, { 4453, 4256 }, { 4455, 4256 } } }, { "NtUserCallHwndParamLock", { 4415, { 4414, 4134 }, { 4425, 4135 }, { 4426, 4135 }, { 4449, 4136 }, { 4451, 4137 }, { 4452, 4138 }, { 4454, 4138 } } }, { "NtUserCallMsgFilter", { 4416, { 4415, 4116 }, { 4426, 4117 }, { 4427, 4117 }, { 4448, 4118 }, { 4450, 4119 }, { 4451, 4120 }, { 4453, 4120 } } }, { "NtUserCallNextHookEx", { 4417, { 4416, 4125 }, { 4427, 4126 }, { 4428, 4126 }, { 4447, 4127 }, { 4449, 4128 }, { 4450, 4129 }, { 4452, 4129 } } }, { "NtUserCallNoParam", { 4418, { 4417, 4101 }, { 4428, 4101 }, { 4429, 4101 }, { 4446, 4102 }, { 4448, 4103 }, { 4449, 4104 }, { 4451, 4104 } } }, { "NtUserCallOneParam", { 4419, { 4418, 4098 }, { 4429, 4098 }, { 4430, 4098 }, { 4445, 4099 }, { 4447, 4100 }, { 4448, 4101 }, { 4450, 4101 } } }, { "NtUserCallTwoParam", { 4420, { 4419, 4137 }, { 4430, 4138 }, { 4431, 4138 }, { 4444, 4139 }, { 4446, 4140 }, { 4447, 4141 }, { 4449, 4141 } } }, { "NtUserCanBrokerForceForeground", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4416, 4837 }, { 4418, 4870 }, { 4419, 4939 }, { 4421, 4943 } } }, { "NtUserChangeClipboardChain", { 4421, { 4420, 4383 }, { 4431, 4384 }, { 4432, 4377 }, { 4443, 4377 }, { 4445, 4378 }, { 4446, 4379 }, { 4448, 4379 } } }, { "NtUserChangeDisplaySettings", { 4422, { 4421, 4650 }, { 4432, 4730 }, { 4433, 4744 }, { 4442, 4838 }, { 4444, 4871 }, { 4445, 4940 }, { 4447, 4944 } } }, { "NtUserChangeWindowMessageFilterEx", { -1, { -1, -1 }, { -1, -1 }, { 4753, 4745 }, { 4825, 4839 }, { 4834, 4872 }, { 4846, 4941 }, { 4847, 4945 } } }, { "NtUserCheckAccessForIntegrityLevel", { -1, { -1, -1 }, { 4433, 4731 }, { 4439, 4746 }, { 4436, 4840 }, { 4438, 4873 }, { 4439, 4942 }, { 4441, 4946 } } }, { "NtUserCheckDesktopByThreadId", { -1, { -1, -1 }, { 4434, 4732 }, { 4440, 4747 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserCheckImeHotKey", { 4423, { 4422, 4212 }, { 4436, 4213 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserCheckMenuItem", { 4424, { 4423, 4360 }, { 4437, 4361 }, { 4442, 4355 }, { 4433, 4355 }, { 4435, 4356 }, { 4436, 4357 }, { 4438, 4357 } } }, { "NtUserCheckProcessForClipboardAccess", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5077, 4841 }, { 5118, 4874 }, { 5195, 4943 }, { 5199, 4947 } } }, { "NtUserCheckProcessSession", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4736, 4842 }, { 4739, 4875 }, { 4749, 4944 }, { 4750, 4948 } } }, { "NtUserCheckWindowThreadDesktop", { -1, { -1, -1 }, { 4435, 4733 }, { 4441, 4748 }, { 4434, 4843 }, { 4436, 4876 }, { 4437, 4945 }, { 4439, 4949 } } }, { "NtUserChildWindowFromPointEx", { 4425, { 4424, 4651 }, { 4438, 4734 }, { 4443, 4749 }, { 4432, 4844 }, { 4434, 4877 }, { 4435, 4946 }, { 4437, 4950 } } }, { "NtUserClearForeground", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5107, 4878 }, { 5182, 4947 }, { 5185, 4951 } } }, { "NtUserClipCursor", { 4426, { 4425, 4652 }, { 4439, 4735 }, { 4444, 4750 }, { 4431, 4845 }, { 4433, 4879 }, { 4434, 4948 }, { 4436, 4952 } } }, { "NtUserCloseClipboard", { 4427, { 4426, 4306 }, { 4440, 4307 }, { 4445, 4302 }, { 4430, 4302 }, { 4432, 4303 }, { 4433, 4304 }, { 4435, 4304 } } }, { "NtUserCloseDesktop", { 4428, { 4427, 4266 }, { 4441, 4267 }, { 4446, 4262 }, { 4429, 4262 }, { 4431, 4263 }, { 4432, 4264 }, { 4434, 4264 } } }, { "NtUserCloseWindowStation", { 4429, { 4428, 4281 }, { 4442, 4282 }, { 4447, 4277 }, { 4428, 4277 }, { 4430, 4278 }, { 4431, 4279 }, { 4433, 4279 } } }, { "NtUserCompositionInputSinkLuidFromPoint", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5121, 4880 }, { 5198, 4949 }, { 5202, 4953 } } }, { "NtUserConsoleControl", { 4430, { 4429, 4323 }, { 4443, 4324 }, { 4448, 4319 }, { 4427, 4319 }, { 4429, 4320 }, { 4430, 4321 }, { 4432, 4321 } } }, { "NtUserConvertMemHandle", { 4431, { 4430, 4354 }, { 4444, 4355 }, { 4449, 4349 }, { 4426, 4349 }, { 4428, 4350 }, { 4429, 4351 }, { 4431, 4351 } } }, { "NtUserCopyAcceleratorTable", { 4432, { 4431, 4139 }, { 4445, 4140 }, { 4450, 4140 }, { 4425, 4141 }, { 4427, 4142 }, { 4428, 4143 }, { 4430, 4143 } } }, { "NtUserCountClipboardFormats", { 4433, { 4432, 4373 }, { 4446, 4374 }, { 4451, 4367 }, { 4424, 4367 }, { 4426, 4368 }, { 4427, 4369 }, { 4429, 4369 } } }, { "NtUserCreateAcceleratorTable", { 4434, { 4433, 4341 }, { 4447, 4342 }, { 4452, 4337 }, { 4423, 4337 }, { 4425, 4338 }, { 4426, 4339 }, { 4428, 4339 } } }, { "NtUserCreateCaret", { 4435, { 4434, 4145 }, { 4448, 4146 }, { 4453, 4146 }, { 4422, 4147 }, { 4424, 4148 }, { 4425, 4149 }, { 4427, 4149 } } }, { "NtUserCreateDCompositionHwndTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5052, 4846 }, { 5092, 4881 }, { 5167, 4950 }, { 5170, 4954 } } }, { "NtUserCreateDesktop", { 4436, { 4435, 4653 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserCreateDesktopEx", { -1, { -1, -1 }, { 4449, 4736 }, { 4454, 4751 }, { 4421, 4847 }, { 4423, 4882 }, { 4424, 4951 }, { 4426, 4955 } } }, { "NtUserCreateInputContext", { 4437, { 4436, -1 }, { 4450, 4737 }, { 4455, 4752 }, { 4420, 4848 }, { 4422, 4883 }, { 4423, 4952 }, { 4425, 4956 } } }, { "NtUserCreateLocalMemHandle", { 4438, { 4437, 4335 }, { 4451, 4336 }, { 4456, 4331 }, { 4419, 4331 }, { 4421, 4332 }, { 4422, 4333 }, { 4424, 4333 } } }, { "NtUserCreateWindowEx", { 4439, { 4438, 4215 }, { 4452, 4216 }, { 4457, 4214 }, { 4418, 4214 }, { 4420, 4215 }, { 4421, 4216 }, { 4423, 4216 } } }, { "NtUserCreateWindowStation", { 4440, { 4439, 4655 }, { 4453, 4738 }, { 4458, 4753 }, { 4417, 4849 }, { 4419, 4884 }, { 4420, 4953 }, { 4422, 4957 } } }, { "NtUserCtxDisplayIOCtl", { 4694, { 4690, 4656 }, { 4719, 4739 }, { 4731, 4754 }, { 4739, 4850 }, { 4742, 4885 }, { 4752, 4954 }, { 4753, 4958 } } }, { "NtUserDdeGetQualityOfService", { 4441, { 4440, 4657 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDdeInitialize", { 4442, { 4441, 4371 }, { 4454, 4372 }, { 4459, 4365 }, { 4415, 4365 }, { 4417, 4366 }, { 4418, 4367 }, { 4420, 4367 } } }, { "NtUserDdeSetQualityOfService", { 4443, { 4442, 4658 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDeferWindowPos", { 4444, { 4443, 4178 }, { 4455, 4179 }, { 4460, 4179 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDeferWindowPosAndBand", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4414, 4851 }, { 4416, 4886 }, { 4417, 4955 }, { 4419, 4959 } } }, { "NtUserDefSetText", { 4445, { 4444, 4224 }, { 4456, 4225 }, { 4461, 4223 }, { 4413, 4223 }, { 4415, 4224 }, { 4416, 4225 }, { 4418, 4225 } } }, { "NtUserDelegateCapturePointers", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4466, 4852 }, { 4468, 4887 }, { 4469, 4956 }, { 4471, 4960 } } }, { "NtUserDelegateInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4467, 4853 }, { 4469, 4888 }, { 4470, 4957 }, { 4472, 4961 } } }, { "NtUserDeleteMenu", { 4446, { 4445, 4288 }, { 4457, 4289 }, { 4462, 4284 }, { 4476, 4284 }, { 4478, 4285 }, { 4479, 4286 }, { 4481, 4286 } } }, { "NtUserDestroyAcceleratorTable", { 4447, { 4446, 4355 }, { 4458, 4356 }, { 4463, 4350 }, { 4475, 4350 }, { 4477, 4351 }, { 4478, 4352 }, { 4480, 4352 } } }, { "NtUserDestroyCursor", { 4448, { 4447, 4253 }, { 4459, 4254 }, { 4464, 4252 }, { 4474, 4252 }, { 4476, 4253 }, { 4477, 4254 }, { 4479, 4254 } } }, { "NtUserDestroyDCompositionHwndTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5051, 4854 }, { 5091, 4889 }, { 5166, 4958 }, { 5169, 4962 } } }, { "NtUserDestroyInputContext", { 4449, { 4448, -1 }, { 4460, 4740 }, { 4465, 4755 }, { 4473, 4855 }, { 4475, 4890 }, { 4476, 4959 }, { 4478, 4963 } } }, { "NtUserDestroyMenu", { 4450, { 4449, 4321 }, { 4461, 4322 }, { 4466, 4317 }, { 4472, 4317 }, { 4474, 4318 }, { 4475, 4319 }, { 4477, 4319 } } }, { "NtUserDestroyWindow", { 4451, { 4450, 4254 }, { 4462, 4255 }, { 4467, 4253 }, { 4471, 4253 }, { 4473, 4254 }, { 4474, 4255 }, { 4476, 4255 } } }, { "NtUserDisableImmersiveOwner", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5066, 4856 }, { 5106, 4891 }, { 5181, 4960 }, { 5184, 4964 } } }, { "NtUserDisableProcessWindowFiltering", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4469, 4857 }, { 4471, 4892 }, { 4472, 4961 }, { 4474, 4965 } } }, { "NtUserDisableThreadIme", { 4452, { 4451, 4660 }, { 4463, 4741 }, { 4468, 4756 }, { 4470, 4858 }, { 4472, 4893 }, { 4473, 4962 }, { 4475, 4966 } } }, { "NtUserDiscardPointerFrameMessages", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4815, 4859 }, { 4823, 4894 }, { 4834, 4963 }, { 4835, 4967 } } }, { "NtUserDispatchMessage", { 4453, { 4452, 4149 }, { 4464, 4150 }, { 4469, 4150 }, { 4468, 4151 }, { 4470, 4152 }, { 4471, 4153 }, { 4473, 4153 } } }, { "NtUserDisplayConfigGetDeviceInfo", { -1, { -1, -1 }, { -1, -1 }, { 4437, 4757 }, { 4438, 4860 }, { 4440, 4895 }, { 4441, 4964 }, { 4443, 4968 } } }, { "NtUserDisplayConfigSetDeviceInfo", { -1, { -1, -1 }, { -1, -1 }, { 4438, 4758 }, { 4437, 4861 }, { 4439, 4896 }, { 4440, 4965 }, { 4442, 4969 } } }, { "NtUserDoSoundConnect", { -1, { -1, -1 }, { 4465, 4742 }, { 4470, 4759 }, { 4478, 4862 }, { 4480, 4897 }, { 4481, 4966 }, { 4483, 4970 } } }, { "NtUserDoSoundDisconnect", { -1, { -1, -1 }, { 4466, 4743 }, { 4471, 4760 }, { 4477, 4863 }, { 4479, 4898 }, { 4480, 4967 }, { 4482, 4971 } } }, { "NtUserDragDetect", { 4454, { 4453, 4661 }, { 4467, 4744 }, { 4472, 4761 }, { 4575, 4864 }, { 4576, 4899 }, { 4578, 4968 }, { 4580, 4972 } } }, { "NtUserDragObject", { 4455, { 4454, 4662 }, { 4468, 4745 }, { 4473, 4762 }, { 4574, 4865 }, { 4575, 4900 }, { 4577, 4969 }, { 4579, 4973 } } }, { "NtUserDrawAnimatedRects", { 4456, { 4455, 4663 }, { 4469, 4746 }, { 4474, 4763 }, { 4573, 4866 }, { 4574, 4901 }, { 4576, 4970 }, { 4578, 4974 } } }, { "NtUserDrawCaption", { 4457, { 4456, 4664 }, { 4470, 4747 }, { 4475, 4764 }, { 4572, 4867 }, { 4573, 4902 }, { 4575, 4971 }, { 4577, 4975 } } }, { "NtUserDrawCaptionTemp", { 4458, { 4457, 4665 }, { 4471, 4748 }, { 4476, 4765 }, { 4571, 4868 }, { 4572, 4903 }, { 4574, 4972 }, { 4576, 4976 } } }, { "NtUserDrawIconEx", { 4459, { 4458, 4191 }, { 4472, 4192 }, { 4477, 4192 }, { 4570, 4192 }, { 4571, 4193 }, { 4573, 4194 }, { 4575, 4194 } } }, { "NtUserDrawMenuBarTemp", { 4460, { 4459, 4666 }, { 4473, 4749 }, { 4478, 4766 }, { 4569, 4869 }, { 4570, 4904 }, { 4572, 4973 }, { 4574, 4977 } } }, { "NtUserDwmGetDxRgn", { -1, { -1, -1 }, { 4726, 4750 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDwmGetRemoteSessionOcclusionEvent", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4733, 4870 }, { 4736, 4905 }, { 4744, 4974 }, { 4745, 4978 } } }, { "NtUserDwmGetRemoteSessionOcclusionState", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4734, 4871 }, { 4737, 4906 }, { 4745, 4975 }, { 4746, 4979 } } }, { "NtUserDwmHintDxUpdate", { -1, { -1, -1 }, { 4725, 4751 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDwmKernelShutdown", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4746, 4976 }, { 4747, 4980 } } }, { "NtUserDwmKernelStartup", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4747, 4977 }, { 4748, 4981 } } }, { "NtUserDwmStartRedirection", { -1, { -1, -1 }, { 4723, 4752 }, { 4735, 4767 }, { 4732, 4872 }, { 4735, 4907 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDwmStopRedirection", { -1, { -1, -1 }, { 4724, 4753 }, { 4736, 4768 }, { 4731, 4873 }, { 4734, 4908 }, { -1, -1 }, { -1, -1 } } }, { "NtUserDwmValidateWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4435, 4874 }, { 4437, 4909 }, { 4438, 4978 }, { 4440, 4982 } } }, { "NtUserEmptyClipboard", { 4461, { 4460, 4348 }, { 4474, 4349 }, { 4479, 4344 }, { 4568, 4344 }, { 4569, 4345 }, { 4571, 4346 }, { 4573, 4346 } } }, { "NtUserEnableChildWindowDpiMessage", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4677, 4979 }, { 4679, 4983 } } }, { "NtUserEnableIAMAccess", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5067, 4875 }, { 5108, 4910 }, { 5183, 4980 }, { 5186, 4984 } } }, { "NtUserEnableMenuItem", { 4462, { 4461, 4310 }, { 4475, 4311 }, { 4480, 4306 }, { 4567, 4306 }, { 4568, 4307 }, { 4570, 4308 }, { 4572, 4308 } } }, { "NtUserEnableMouseInPointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5070, 4876 }, { 5111, 4911 }, { 5188, 4981 }, { 5192, 4985 } } }, { "NtUserEnableMouseInputForCursorSuppression", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5074, 4877 }, { 5115, 4912 }, { 5192, 4982 }, { 5196, 4986 } } }, { "NtUserEnableScrollBar", { 4463, { 4462, 4283 }, { 4476, 4284 }, { 4481, 4279 }, { 4566, 4279 }, { 4567, 4280 }, { 4569, 4281 }, { 4571, 4281 } } }, { "NtUserEnableTouchPad", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4819, 4913 }, { 4830, 4983 }, { 4831, 4987 } } }, { "NtUserEndDeferWindowPosEx", { 4464, { 4463, 4133 }, { 4477, 4134 }, { 4482, 4134 }, { 4565, 4135 }, { 4566, 4136 }, { 4568, 4137 }, { 4570, 4137 } } }, { "NtUserEndMenu", { 4465, { 4464, 4667 }, { 4478, 4754 }, { 4483, 4769 }, { 4564, 4878 }, { 4565, 4914 }, { 4567, 4984 }, { 4569, 4988 } } }, { "NtUserEndPaint", { 4466, { 4465, 4120 }, { 4479, 4121 }, { 4484, 4121 }, { 4563, 4122 }, { 4564, 4123 }, { 4566, 4124 }, { 4568, 4124 } } }, { "NtUserEndTouchOperation", { -1, { -1, -1 }, { -1, -1 }, { 4751, 4770 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserEnumDisplayDevices", { 4467, { 4466, 4347 }, { 4480, 4348 }, { 4485, 4343 }, { 4562, 4343 }, { 4563, 4344 }, { 4565, 4345 }, { 4567, 4345 } } }, { "NtUserEnumDisplayMonitors", { 4468, { 4467, 4169 }, { 4481, 4170 }, { 4486, 4170 }, { 4561, 4171 }, { 4562, 4172 }, { 4564, 4173 }, { 4566, 4173 } } }, { "NtUserEnumDisplaySettings", { 4469, { 4468, 4378 }, { 4482, 4379 }, { 4487, 4372 }, { 4560, 4372 }, { 4561, 4373 }, { 4563, 4374 }, { 4565, 4374 } } }, { "NtUserEvent", { 4470, { 4469, 4668 }, { 4483, 4755 }, { 4488, 4771 }, { 4559, 4879 }, { 4560, 4915 }, { 4562, 4985 }, { 4564, 4989 } } }, { "NtUserExcludeUpdateRgn", { 4471, { 4470, 4175 }, { 4484, 4176 }, { 4489, 4176 }, { 4558, 4177 }, { 4559, 4178 }, { 4561, 4179 }, { 4563, 4179 } } }, { "NtUserFillWindow", { 4472, { 4471, 4234 }, { 4485, 4235 }, { 4490, 4233 }, { 4557, 4233 }, { 4558, 4234 }, { 4560, 4235 }, { 4562, 4235 } } }, { "NtUserFindExistingCursorIcon", { 4473, { 4472, 4157 }, { 4486, 4158 }, { 4491, 4158 }, { 4556, 4159 }, { 4557, 4160 }, { 4559, 4161 }, { 4561, 4161 } } }, { "NtUserFindWindowEx", { 4474, { 4473, 4206 }, { 4487, 4207 }, { 4492, 4206 }, { 4555, 4206 }, { 4556, 4207 }, { 4558, 4208 }, { 4560, 4208 } } }, { "NtUserFlashWindowEx", { 4475, { 4474, 4669 }, { 4488, 4756 }, { 4493, 4772 }, { 4554, 4880 }, { 4555, 4916 }, { 4557, 4986 }, { 4559, 4990 } } }, { "NtUserFrostCrashedWindow", { -1, { -1, -1 }, { 4489, 4757 }, { 4494, 4773 }, { 4553, 4881 }, { 4554, 4917 }, { 4556, 4987 }, { 4558, 4991 } } }, { "NtUserGetAltTabInfo", { 4476, { 4475, 4343 }, { 4490, 4344 }, { 4495, 4339 }, { 4552, 4339 }, { 4553, 4340 }, { 4555, 4341 }, { 4557, 4341 } } }, { "NtUserGetAncestor", { 4477, { 4476, 4278 }, { 4491, 4279 }, { 4496, 4274 }, { 4551, 4274 }, { 4552, 4275 }, { 4554, 4276 }, { 4556, 4276 } } }, { "NtUserGetAppImeLevel", { 4478, { 4477, -1 }, { 4492, 4758 }, { 4497, 4774 }, { 4550, 4882 }, { 4551, 4918 }, { 4553, 4988 }, { 4555, 4992 } } }, { "NtUserGetAsyncKeyState", { 4479, { 4478, 4163 }, { 4493, 4164 }, { 4498, 4164 }, { 4549, 4165 }, { 4550, 4166 }, { 4552, 4167 }, { 4554, 4167 } } }, { "NtUserGetAtomName", { 4480, { 4479, 4269 }, { 4494, 4270 }, { 4499, 4265 }, { 4548, 4265 }, { 4549, 4266 }, { 4551, 4267 }, { 4553, 4267 } } }, { "NtUserGetAutoRotationState", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5060, 4883 }, { 5100, 4919 }, { 5175, 4989 }, { 5178, 4993 } } }, { "NtUserGetCaretBlinkTime", { 4481, { 4480, 4344 }, { 4495, 4345 }, { 4500, 4340 }, { 4547, 4340 }, { 4548, 4341 }, { 4550, 4342 }, { 4552, 4342 } } }, { "NtUserGetCaretPos", { 4482, { 4481, 4671 }, { 4496, 4759 }, { 4501, 4775 }, { 4546, 4885 }, { 4547, 4921 }, { 4549, 4991 }, { 4551, 4995 } } }, { "NtUserGetCIMSSM", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4533, 4884 }, { 4534, 4920 }, { 4536, 4990 }, { 4538, 4994 } } }, { "NtUserGetClassInfo", { 4483, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserGetClassInfoEx", { -1, { 4482, 4285 }, { 4497, 4286 }, { 4502, 4281 }, { 4545, 4281 }, { 4546, 4282 }, { 4548, 4283 }, { 4550, 4283 } } }, { "NtUserGetClassName", { 4484, { 4483, 4220 }, { 4498, 4221 }, { 4503, 4219 }, { 4544, 4219 }, { 4545, 4220 }, { 4547, 4221 }, { 4549, 4221 } } }, { "NtUserGetClipboardAccessToken", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5078, 4887 }, { 5119, 4923 }, { 5196, 4993 }, { 5200, 4997 } } }, { "NtUserGetClipboardData", { 4485, { 4484, 4349 }, { 4499, 4350 }, { 4504, 4345 }, { 4543, 4345 }, { 4544, 4346 }, { 4546, 4347 }, { 4548, 4347 } } }, { "NtUserGetClipboardFormatName", { 4486, { 4485, 4333 }, { 4500, 4334 }, { 4505, 4329 }, { 4542, 4329 }, { 4543, 4330 }, { 4545, 4331 }, { 4547, 4331 } } }, { "NtUserGetClipboardOwner", { 4487, { 4486, 4301 }, { 4501, 4302 }, { 4506, 4297 }, { 4541, 4297 }, { 4542, 4298 }, { 4544, 4299 }, { 4546, 4299 } } }, { "NtUserGetClipboardSequenceNumber", { 4488, { 4487, 4181 }, { 4502, 4182 }, { 4507, 4182 }, { 4540, 4182 }, { 4541, 4183 }, { 4543, 4184 }, { 4545, 4184 } } }, { "NtUserGetClipboardViewer", { 4489, { 4488, 4673 }, { 4503, 4761 }, { 4508, 4777 }, { 4539, 4888 }, { 4540, 4924 }, { 4542, 4994 }, { 4544, 4998 } } }, { "NtUserGetClipCursor", { 4490, { 4489, 4672 }, { 4504, 4760 }, { 4509, 4776 }, { 4538, 4886 }, { 4539, 4922 }, { 4541, 4992 }, { 4543, 4996 } } }, { "NtUserGetComboBoxInfo", { 4491, { 4490, 4674 }, { 4505, 4762 }, { 4510, 4778 }, { 4537, 4889 }, { 4538, 4925 }, { 4540, 4995 }, { 4542, 4999 } } }, { "NtUserGetControlBrush", { 4492, { 4491, 4219 }, { 4506, 4220 }, { 4511, 4218 }, { 4536, 4218 }, { 4537, 4219 }, { 4539, 4220 }, { 4541, 4220 } } }, { "NtUserGetControlColor", { 4493, { 4492, 4327 }, { 4507, 4328 }, { 4512, 4323 }, { 4535, 4323 }, { 4536, 4324 }, { 4538, 4325 }, { 4540, 4325 } } }, { "NtUserGetCPD", { 4494, { 4493, 4164 }, { 4508, 4165 }, { 4513, 4165 }, { 4534, 4166 }, { 4535, 4167 }, { 4537, 4168 }, { 4539, 4168 } } }, { "NtUserGetCurrentInputMessageSource", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4532, 4890 }, { 4533, 4926 }, { 4535, 4996 }, { 4537, 5000 } } }, { "NtUserGetCursorDims", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5130, 4927 }, { 5207, 4997 }, { 5211, 5001 } } }, { "NtUserGetCursorFrameInfo", { 4495, { 4494, 4342 }, { 4509, 4343 }, { 4514, 4338 }, { 4531, 4338 }, { 4532, 4339 }, { 4534, 4340 }, { 4536, 4340 } } }, { "NtUserGetCursorInfo", { 4496, { 4495, 4675 }, { 4510, 4763 }, { 4515, 4779 }, { 4530, 4891 }, { 4531, 4928 }, { 4533, 4998 }, { 4535, 5002 } } }, { "NtUserGetDC", { 4497, { 4496, 4106 }, { 4511, 4106 }, { 4516, 4106 }, { 4529, 4107 }, { 4530, 4108 }, { 4532, 4109 }, { 4534, 4109 } } }, { "NtUserGetDCEx", { 4498, { 4497, 4243 }, { 4512, 4244 }, { 4517, 4242 }, { 4528, 4242 }, { 4529, 4243 }, { 4531, 4244 }, { 4533, 4244 } } }, { "NtUserGetDesktopID", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4527, 4892 }, { 4528, 4929 }, { 4530, 5000 }, { 4532, 5004 } } }, { "NtUserGetDisplayAutoRotationPreferences", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5057, 4893 }, { 5097, 4930 }, { 5172, 5001 }, { 5175, 5005 } } }, { "NtUserGetDisplayAutoRotationPreferencesByProcessId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5056, 4894 }, { 5096, 4931 }, { 5171, 5002 }, { 5174, 5006 } } }, { "NtUserGetDisplayConfigBufferSizes", { -1, { -1, -1 }, { -1, -1 }, { 4434, 4780 }, { 4441, 4895 }, { 4443, 4932 }, { 4444, 5003 }, { 4446, 5007 } } }, { "NtUserGetDManipHookInitFunction", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4734, 4999 }, { 4735, 5003 } } }, { "NtUserGetDoubleClickTime", { 4499, { 4498, 4282 }, { 4513, 4283 }, { 4518, 4278 }, { 4526, 4278 }, { 4527, 4279 }, { 4529, 4280 }, { 4531, 4280 } } }, { "NtUserGetDpiForMonitor", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5127, 4933 }, { 5204, 5004 }, { 5208, 5008 } } }, { "NtUserGetDpiSystemMetrics", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4528, 5005 }, { 4530, 5009 } } }, { "NtUserGetForegroundWindow", { 4500, { 4499, 4155 }, { 4514, 4156 }, { 4519, 4156 }, { 4525, 4157 }, { 4526, 4158 }, { 4527, 4159 }, { 4529, 4159 } } }, { "NtUserGetGestureConfig", { -1, { -1, -1 }, { -1, -1 }, { 4759, 4781 }, { 4820, 4896 }, { 4829, 4934 }, { 4841, 5006 }, { 4842, 5010 } } }, { "NtUserGetGestureExtArgs", { -1, { -1, -1 }, { -1, -1 }, { 4756, 4782 }, { 4822, 4897 }, { 4831, 4935 }, { 4843, 5007 }, { 4844, 5011 } } }, { "NtUserGetGestureInfo", { -1, { -1, -1 }, { -1, -1 }, { 4755, 4783 }, { 4823, 4898 }, { 4832, 4936 }, { 4844, 5008 }, { 4845, 5012 } } }, { "NtUserGetGlobalIMEStatus", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4524, 4899 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserGetGuiResources", { 4501, { 4500, 4676 }, { 4515, 4764 }, { 4520, 4784 }, { 4523, 4900 }, { 4525, 4937 }, { 4526, 5009 }, { 4528, 5013 } } }, { "NtUserGetGUIThreadInfo", { 4502, { 4501, 4356 }, { 4516, 4357 }, { 4521, 4351 }, { 4522, 4351 }, { 4524, 4352 }, { 4525, 4353 }, { 4527, 4353 } } }, { "NtUserGetHimetricScaleFactorFromPixelLocation", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5125, 4938 }, { 5202, 5010 }, { 5206, 5014 } } }, { "NtUserGetIconInfo", { 4503, { 4502, 4174 }, { 4517, 4175 }, { 4522, 4175 }, { 4521, 4176 }, { 4523, 4177 }, { 4524, 4178 }, { 4526, 4178 } } }, { "NtUserGetIconSize", { 4504, { 4503, 4233 }, { 4518, 4234 }, { 4523, 4232 }, { 4520, 4232 }, { 4522, 4233 }, { 4523, 4234 }, { 4525, 4234 } } }, { "NtUserGetImeHotKey", { 4505, { 4504, 4677 }, { 4519, 4765 }, { 4524, 4785 }, { 4519, 4901 }, { 4521, 4939 }, { 4522, 5011 }, { 4524, 5015 } } }, { "NtUserGetImeInfoEx", { 4506, { 4505, 4678 }, { 4520, 4766 }, { 4525, 4786 }, { 4518, 4902 }, { 4520, 4940 }, { 4521, 5012 }, { 4523, 5016 } } }, { "NtUserGetInputLocaleInfo", { -1, { -1, -1 }, { -1, -1 }, { 4526, 4787 }, { 4517, 4903 }, { 4519, 4941 }, { 4520, 5013 }, { 4522, 5017 } } }, { "NtUserGetInternalWindowPos", { 4507, { 4506, 4679 }, { 4521, 4767 }, { 4527, 4788 }, { 4516, 4904 }, { 4518, 4942 }, { 4519, 5014 }, { 4521, 5018 } } }, { "NtUserGetKeyboardLayoutList", { 4508, { 4507, 4184 }, { 4522, 4185 }, { 4528, 4185 }, { 4515, 4185 }, { 4517, 4186 }, { 4518, 4187 }, { 4520, 4187 } } }, { "NtUserGetKeyboardLayoutName", { 4509, { 4508, 4681 }, { 4523, 4769 }, { 4529, 4790 }, { 4514, 4906 }, { 4516, 4944 }, { 4517, 5016 }, { 4519, 5020 } } }, { "NtUserGetKeyboardState", { 4510, { 4509, 4217 }, { 4524, 4218 }, { 4530, 4216 }, { 4513, 4216 }, { 4515, 4217 }, { 4516, 4218 }, { 4518, 4218 } } }, { "NtUserGetKeyNameText", { 4511, { 4510, 4680 }, { 4525, 4768 }, { 4531, 4789 }, { 4512, 4905 }, { 4514, 4943 }, { 4515, 5015 }, { 4517, 5019 } } }, { "NtUserGetKeyState", { 4512, { 4511, 4099 }, { 4526, 4099 }, { 4532, 4099 }, { 4511, 4100 }, { 4513, 4101 }, { 4514, 4102 }, { 4516, 4102 } } }, { "NtUserGetLayeredWindowAttributes", { 4676, { 4672, 4682 }, { 4700, 4770 }, { 4713, 4791 }, { 4757, 4907 }, { 4760, 4945 }, { 4770, 5017 }, { 4771, 5021 } } }, { "NtUserGetListBoxInfo", { 4513, { 4512, 4683 }, { 4527, 4771 }, { 4533, 4792 }, { 4510, 4908 }, { 4512, 4946 }, { 4513, 5018 }, { 4515, 5022 } } }, { "NtUserGetMenuBarInfo", { 4514, { 4513, 4293 }, { 4528, 4294 }, { 4534, 4289 }, { 4509, 4289 }, { 4511, 4290 }, { 4512, 4291 }, { 4514, 4291 } } }, { "NtUserGetMenuIndex", { 4515, { 4514, 4684 }, { 4529, 4772 }, { 4535, 4793 }, { 4508, 4909 }, { 4510, 4947 }, { 4511, 5019 }, { 4513, 5023 } } }, { "NtUserGetMenuItemRect", { 4516, { 4515, 4685 }, { 4530, 4773 }, { 4536, 4794 }, { 4507, 4910 }, { 4509, 4948 }, { 4510, 5020 }, { 4512, 5024 } } }, { "NtUserGetMessage", { 4517, { 4516, 4102 }, { 4531, 4102 }, { 4537, 4102 }, { 4506, 4103 }, { 4508, 4104 }, { 4509, 4105 }, { 4511, 4105 } } }, { "NtUserGetMouseMovePointsEx", { 4518, { 4517, 4686 }, { 4532, 4774 }, { 4538, 4795 }, { 4505, 4911 }, { 4507, 4949 }, { 4508, 5021 }, { 4510, 5025 } } }, { "NtUserGetObjectInformation", { 4519, { 4518, 4203 }, { 4533, 4204 }, { 4539, 4204 }, { 4504, 4204 }, { 4506, 4205 }, { 4507, 4206 }, { 4509, 4206 } } }, { "NtUserGetOpenClipboardWindow", { 4520, { 4519, 4316 }, { 4534, 4317 }, { 4540, 4312 }, { 4503, 4312 }, { 4505, 4313 }, { 4506, 4314 }, { 4508, 4314 } } }, { "NtUserGetOwnerTransformedMonitorRect", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5131, 4950 }, { 4096, 4096 }, { 4096, 4096 } } }, { "NtUserGetPhysicalDeviceRect", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4810, 4951 }, { 4821, 5022 }, { 4822, 5026 } } }, { "NtUserGetPointerCursorId", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4818, 4912 }, { 4827, 4952 }, { 4839, 5023 }, { 4840, 5027 } } }, { "NtUserGetPointerDevice", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4812, 4913 }, { 4817, 4953 }, { 4828, 5024 }, { 4829, 5028 } } }, { "NtUserGetPointerDeviceCursors", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4808, 4914 }, { 4813, 4954 }, { 4824, 5025 }, { 4825, 5029 } } }, { "NtUserGetPointerDeviceProperties", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4811, 4915 }, { 4816, 4955 }, { 4827, 5026 }, { 4828, 5030 } } }, { "NtUserGetPointerDeviceRects", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4809, 4916 }, { 4814, 4956 }, { 4825, 5027 }, { 4826, 5031 } } }, { "NtUserGetPointerDevices", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4813, 4917 }, { 4818, 4957 }, { 4829, 5028 }, { 4830, 5032 } } }, { "NtUserGetPointerFrameArrivalTimes", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4836, 5029 }, { 4837, 5033 } } }, { "NtUserGetPointerInfoList", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4817, 4918 }, { 4826, 4958 }, { 4838, 5030 }, { 4839, 5034 } } }, { "NtUserGetPointerInputTransform", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4825, 4959 }, { 4837, 5031 }, { 4838, 5035 } } }, { "NtUserGetPointerType", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4819, 4919 }, { 4828, 4960 }, { 4840, 5032 }, { 4841, 5036 } } }, { "NtUserGetPrecisionTouchPadConfiguration", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4820, 4961 }, { 4831, 5033 }, { 4832, 5037 } } }, { "NtUserGetPriorityClipboardFormat", { 4521, { 4520, 4687 }, { 4535, 4775 }, { 4541, 4796 }, { 4502, 4920 }, { 4504, 4962 }, { 4505, 5034 }, { 4507, 5038 } } }, { "NtUserGetProcessDpiAwareness", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5126, 4963 }, { 5203, 5035 }, { 5207, 5039 } } }, { "NtUserGetProcessUIContextInformation", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5068, 4921 }, { 5109, 4964 }, { 5184, 5036 }, { 5187, 5040 } } }, { "NtUserGetProcessWindowStation", { 4522, { 4521, 4129 }, { 4536, 4130 }, { 4542, 4130 }, { 4501, 4131 }, { 4503, 4132 }, { 4504, 4133 }, { 4506, 4133 } } }, { "NtUserGetProp", { -1, { -1, -1 }, { 4648, 4110 }, { 4658, 4110 }, { 4684, 4111 }, { 4687, 4112 }, { 4693, 4113 }, { 4694, 4113 } } }, { "NtUserGetQueueEventStatus", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5079, 4922 }, { 5120, 4965 }, { 5197, 5037 }, { 5201, 5041 } } }, { "NtUserGetRawInputBuffer", { 4523, { 4522, 4688 }, { 4537, 4776 }, { 4543, 4797 }, { 4500, 4923 }, { 4502, 4966 }, { 4503, 5038 }, { 4505, 5042 } } }, { "NtUserGetRawInputData", { 4524, { 4523, 4689 }, { 4538, 4777 }, { 4544, 4798 }, { 4499, 4924 }, { 4501, 4967 }, { 4502, 5039 }, { 4504, 5043 } } }, { "NtUserGetRawInputDeviceInfo", { 4525, { 4524, 4690 }, { 4539, 4778 }, { 4545, 4799 }, { 4498, 4925 }, { 4500, 4968 }, { 4501, 5040 }, { 4503, 5044 } } }, { "NtUserGetRawInputDeviceList", { 4526, { 4525, 4691 }, { 4540, 4779 }, { 4546, 4800 }, { 4497, 4926 }, { 4499, 4969 }, { 4500, 5041 }, { 4502, 5045 } } }, { "NtUserGetRawPointerDeviceData", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4807, 4927 }, { 4812, 4970 }, { 4823, 5042 }, { 4824, 5046 } } }, { "NtUserGetRegisteredRawInputDevices", { 4527, { 4526, 4692 }, { 4541, 4780 }, { 4547, 4801 }, { 4496, 4928 }, { 4498, 4971 }, { 4499, 5043 }, { 4501, 5047 } } }, { "NtUserGetScrollBarInfo", { 4528, { 4527, 4244 }, { 4542, 4245 }, { 4548, 4243 }, { 4495, 4243 }, { 4497, 4244 }, { 4498, 4245 }, { 4500, 4245 } } }, { "NtUserGetSystemMenu", { 4529, { 4528, 4192 }, { 4543, 4193 }, { 4549, 4193 }, { 4494, 4193 }, { 4496, 4194 }, { 4497, 4195 }, { 4499, 4195 } } }, { "NtUserGetThreadDesktop", { 4530, { 4529, 4228 }, { 4544, 4229 }, { 4550, 4227 }, { 4493, 4227 }, { 4495, 4228 }, { 4496, 4229 }, { 4498, 4229 } } }, { "NtUserGetThreadState", { 4531, { 4530, 4096 }, { 4545, 4096 }, { 4551, 4096 }, { 4492, 4097 }, { 4494, 4098 }, { 4495, 4099 }, { 4497, 4099 } } }, { "NtUserGetTitleBarInfo", { 4532, { 4531, 4240 }, { 4546, 4241 }, { 4552, 4239 }, { 4491, 4239 }, { 4493, 4240 }, { 4494, 4241 }, { 4496, 4241 } } }, { "NtUserGetTopLevelWindow", { -1, { -1, -1 }, { -1, -1 }, { 4553, 4802 }, { 4490, 4929 }, { 4492, 4972 }, { 4493, 5044 }, { 4495, 5048 } } }, { "NtUserGetTouchInputInfo", { -1, { -1, -1 }, { -1, -1 }, { 4752, 4803 }, { 4768, 4930 }, { 4771, 4973 }, { 4781, 5045 }, { 4782, 5049 } } }, { "NtUserGetTouchValidationStatus", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4801, 4931 }, { 4804, 4974 }, { 4815, 5046 }, { 4816, 5050 } } }, { "NtUserGetUpdatedClipboardFormats", { -1, { -1, -1 }, { 4547, 4781 }, { 4554, 4804 }, { 4489, 4932 }, { 4491, 4975 }, { 4492, 5047 }, { 4494, 5051 } } }, { "NtUserGetUpdateRect", { 4533, { 4532, 4179 }, { 4548, 4180 }, { 4555, 4180 }, { 4488, 4180 }, { 4490, 4181 }, { 4491, 4182 }, { 4493, 4182 } } }, { "NtUserGetUpdateRgn", { 4534, { 4533, 4231 }, { 4549, 4232 }, { 4556, 4230 }, { 4487, 4230 }, { 4489, 4231 }, { 4490, 4232 }, { 4492, 4232 } } }, { "NtUserGetWindowBand", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4486, 4934 }, { 4488, 4977 }, { 4489, 5049 }, { 4491, 5053 } } }, { "NtUserGetWindowCompositionAttribute", { -1, { -1, -1 }, { -1, -1 }, { 4558, 4806 }, { 4484, 4935 }, { 4486, 4978 }, { 4487, 5050 }, { 4489, 5054 } } }, { "NtUserGetWindowCompositionInfo", { -1, { -1, -1 }, { -1, -1 }, { 4557, 4807 }, { 4485, 4936 }, { 4487, 4979 }, { 4488, 5051 }, { 4490, 5055 } } }, { "NtUserGetWindowDC", { 4535, { 4534, 4195 }, { 4550, 4196 }, { 4559, 4196 }, { 4483, 4196 }, { 4485, 4197 }, { 4486, 4198 }, { 4488, 4198 } } }, { "NtUserGetWindowDisplayAffinity", { -1, { -1, -1 }, { -1, -1 }, { 4560, 4808 }, { 4482, 4937 }, { 4484, 4980 }, { 4485, 5052 }, { 4487, 5056 } } }, { "NtUserGetWindowFeedbackSetting", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4799, 4938 }, { 4802, 4981 }, { 4813, 5053 }, { 4814, 5057 } } }, { "NtUserGetWindowMinimizeRect", { -1, { -1, -1 }, { 4727, 4783 }, { 4737, 4809 }, { 4730, 4939 }, { 4733, 4982 }, { 4743, 5054 }, { 4744, 5058 } } }, { "NtUserGetWindowPlacement", { 4536, { 4535, 4313 }, { 4551, 4314 }, { 4561, 4309 }, { 4481, 4309 }, { 4483, 4310 }, { 4484, 4311 }, { 4486, 4311 } } }, { "NtUserGetWindowRgnEx", { -1, { -1, -1 }, { 4666, 4784 }, { 4678, 4810 }, { 4658, 4940 }, { 4661, 4983 }, { 4664, 5055 }, { 4666, 5059 } } }, { "NtUserGetWOWClass", { 4537, { 4536, 4693 }, { 4552, 4782 }, { 4562, 4805 }, { 4480, 4933 }, { 4482, 4976 }, { 4483, 5048 }, { 4485, 5052 } } }, { "NtUserGhostWindowFromHungWindow", { -1, { -1, -1 }, { 4553, 4785 }, { 4563, 4811 }, { 4479, 4941 }, { 4481, 4984 }, { 4482, 5056 }, { 4484, 5060 } } }, { "NtUserHandleDelegatedInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4576, 4942 }, { 4577, 4985 }, { 4579, 5057 }, { 4581, 5061 } } }, { "NtUserHardErrorControl", { 4538, { 4537, 4694 }, { 4554, 4786 }, { 4564, 4812 }, { 4627, 4943 }, { 4630, 4986 }, { 4632, 5058 }, { 4634, 5062 } } }, { "NtUserHideCaret", { 4539, { 4538, 4126 }, { 4555, 4127 }, { 4565, 4127 }, { 4626, 4128 }, { 4629, 4129 }, { 4631, 4130 }, { 4633, 4130 } } }, { "NtUserHidePointerContactVisualization", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4800, 4944 }, { 4803, 4987 }, { 4814, 5059 }, { 4815, 5063 } } }, { "NtUserHiliteMenuItem", { 4540, { 4539, 4695 }, { 4556, 4787 }, { 4566, 4813 }, { 4625, 4945 }, { 4628, 4988 }, { 4630, 5060 }, { 4632, 5064 } } }, { "NtUserHungWindowFromGhostWindow", { -1, { -1, -1 }, { 4557, 4788 }, { 4567, 4814 }, { 4624, 4946 }, { 4627, 4989 }, { 4629, 5061 }, { 4631, 5065 } } }, { "NtUserHwndQueryRedirectionInfo", { -1, { -1, -1 }, { -1, -1 }, { 4919, 4815 }, { 4991, 4947 }, { 5009, 4990 }, { 5066, 5062 }, { 5068, 5066 } } }, { "NtUserHwndSetRedirectionInfo", { -1, { -1, -1 }, { -1, -1 }, { 4920, 4816 }, { 4990, 4948 }, { 5008, 4991 }, { 5065, 5063 }, { 5067, 5067 } } }, { "NtUserImpersonateDdeClientWindow", { 4541, { 4540, 4696 }, { 4558, 4789 }, { 4568, 4817 }, { 4623, 4949 }, { 4626, 4992 }, { 4628, 5064 }, { 4630, 5068 } } }, { "NtUserInitialize", { 4542, { 4541, 4698 }, { 4559, 4791 }, { 4569, 4819 }, { 4622, 4951 }, { 4625, 4994 }, { 4627, 5066 }, { 4629, 5070 } } }, { "NtUserInitializeClientPfnArrays", { 4543, { 4542, 4699 }, { 4560, 4792 }, { 4570, 4820 }, { 4621, 4952 }, { 4624, 4995 }, { 4626, 5067 }, { 4628, 5071 } } }, { "NtUserInitializeInputDeviceInjection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5208, 5068 }, { 5212, 5072 } } }, { "NtUserInitializePointerDeviceInjection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5209, 5069 }, { 5213, 5073 } } }, { "NtUserInitializeTouchInjection", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4802, 4953 }, { 4805, 4996 }, { 4816, 5070 }, { 4817, 5074 } } }, { "NtUserInitTask", { 4544, { 4543, 4697 }, { 4561, 4790 }, { 4571, 4818 }, { 4620, 4950 }, { 4623, 4993 }, { 4625, 5065 }, { 4627, 5069 } } }, { "NtUserInjectDeviceInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5211, 5071 }, { 5216, 5075 } } }, { "NtUserInjectGesture", { -1, { -1, -1 }, { -1, -1 }, { 4754, 4821 }, { 4824, 4954 }, { 4833, 4997 }, { 4845, 5072 }, { 4846, 5076 } } }, { "NtUserInjectKeyboardInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5213, 5073 }, { 5218, 5077 } } }, { "NtUserInjectMouseInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5212, 5074 }, { 5217, 5078 } } }, { "NtUserInjectPointerInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5214, 5075 }, { 5219, 5079 } } }, { "NtUserInjectTouchInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4803, 4955 }, { 4806, 4998 }, { 4817, 5076 }, { 4818, 5080 } } }, { "NtUserInternalClipCursor", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5076, 4956 }, { 5117, 4999 }, { 5194, 5077 }, { 5198, 5081 } } }, { "NtUserInternalGetWindowIcon", { -1, { -1, -1 }, { 4563, 4793 }, { 4573, 4822 }, { 4618, 4957 }, { 4621, 5000 }, { 4623, 5078 }, { 4625, 5082 } } }, { "NtUserInternalGetWindowText", { 4545, { 4544, 4194 }, { 4562, 4195 }, { 4572, 4195 }, { 4619, 4195 }, { 4622, 4196 }, { 4624, 4197 }, { 4626, 4197 } } }, { "NtUserInvalidateRect", { 4546, { 4545, 4100 }, { 4564, 4100 }, { 4574, 4100 }, { 4617, 4101 }, { 4620, 4102 }, { 4622, 4103 }, { 4624, 4103 } } }, { "NtUserInvalidateRgn", { 4547, { 4546, 4300 }, { 4565, 4301 }, { 4575, 4296 }, { 4616, 4296 }, { 4619, 4297 }, { 4621, 4298 }, { 4623, 4298 } } }, { "NtUserIsChildWindowDpiMessageEnabled", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4678, 5079 }, { 4680, 5083 } } }, { "NtUserIsClipboardFormatAvailable", { 4548, { 4547, 4142 }, { 4566, 4143 }, { 4576, 4143 }, { 4615, 4144 }, { 4618, 4145 }, { 4620, 4146 }, { 4622, 4146 } } }, { "NtUserIsMouseInPointerEnabled", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5071, 4958 }, { 5112, 5001 }, { 5189, 5080 }, { 5193, 5084 } } }, { "NtUserIsMouseInputEnabled", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5075, 4959 }, { 5116, 5002 }, { 5193, 5081 }, { 5197, 5085 } } }, { "NtUserIsTopLevelWindow", { -1, { -1, -1 }, { -1, -1 }, { 4577, 4823 }, { 4614, 4960 }, { 4617, 5003 }, { 4619, 5082 }, { 4621, 5086 } } }, { "NtUserIsTouchWindow", { -1, { -1, -1 }, { -1, -1 }, { 4749, 4824 }, { 4769, 4961 }, { 4772, 5004 }, { 4782, 5083 }, { 4783, 5087 } } }, { "NtUserIsWindowBroadcastingDpiToChildren", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4679, 5084 }, { 4681, 5088 } } }, { "NtUserKillTimer", { 4549, { 4548, 4122 }, { 4567, 4123 }, { 4578, 4123 }, { 4613, 4124 }, { 4616, 4125 }, { 4618, 4126 }, { 4620, 4126 } } }, { "NtUserLayoutCompleted", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4607, 4962 }, { 4609, 5005 }, { 4611, 5085 }, { 4613, 5089 } } }, { "NtUserLinkDpiCursor", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5129, 5006 }, { 5206, 5086 }, { 5210, 5090 } } }, { "NtUserLoadKeyboardLayoutEx", { 4550, { 4549, 4700 }, { 4568, 4794 }, { 4579, 4825 }, { 4612, 4963 }, { 4615, 5007 }, { 4617, 5087 }, { 4619, 5091 } } }, { "NtUserLockWindowStation", { 4551, { 4550, 4701 }, { 4569, 4795 }, { 4580, 4826 }, { 4611, 4964 }, { 4614, 5008 }, { 4616, 5088 }, { 4618, 5092 } } }, { "NtUserLockWindowUpdate", { 4552, { 4551, 4364 }, { 4570, 4365 }, { 4581, 4358 }, { 4610, 4358 }, { 4613, 4359 }, { 4615, 4360 }, { 4617, 4360 } } }, { "NtUserLockWorkStation", { 4553, { 4552, 4702 }, { 4571, 4796 }, { 4582, 4827 }, { 4609, 4965 }, { 4612, 5009 }, { 4614, 5089 }, { 4616, 5093 } } }, { "NtUserLogicalToPerMonitorDPIPhysicalPoint", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4610, 5010 }, { 4612, 5090 }, { 4614, 5094 } } }, { "NtUserLogicalToPhysicalPoint", { -1, { -1, -1 }, { 4572, 4797 }, { 4583, 4828 }, { 4608, 4966 }, { 4611, 5011 }, { 4613, 5091 }, { 4615, 5095 } } }, { "NtUserMagControl", { -1, { -1, -1 }, { -1, -1 }, { 4916, 4831 }, { 4988, 4969 }, { 5006, 5014 }, { 5063, 5094 }, { 5065, 5098 } } }, { "NtUserMagGetContextInformation", { -1, { -1, -1 }, { -1, -1 }, { 4918, 4832 }, { 4986, 4970 }, { 5004, 5015 }, { 5061, 5095 }, { 5063, 5099 } } }, { "NtUserMagSetContextInformation", { -1, { -1, -1 }, { -1, -1 }, { 4917, 4833 }, { 4987, 4971 }, { 5005, 5016 }, { 5062, 5096 }, { 5064, 5100 } } }, { "NtUserManageGestureHandlerWindow", { -1, { -1, -1 }, { -1, -1 }, { 4757, 4834 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserMapVirtualKeyEx", { 4554, { 4553, 4186 }, { 4573, 4187 }, { 4584, 4187 }, { 4606, 4187 }, { 4608, 4188 }, { 4610, 4189 }, { 4612, 4189 } } }, { "NtUserMenuItemFromPoint", { 4555, { 4554, 4705 }, { 4574, 4800 }, { 4585, 4835 }, { 4605, 4972 }, { 4607, 5017 }, { 4609, 5097 }, { 4611, 5101 } } }, { "NtUserMessageCall", { 4556, { 4555, 4103 }, { 4575, 4103 }, { 4586, 4103 }, { 4604, 4104 }, { 4606, 4105 }, { 4608, 4106 }, { 4610, 4106 } } }, { "NtUserMinMaximize", { 4557, { 4556, 4706 }, { 4576, 4801 }, { 4587, 4836 }, { 4603, 4973 }, { 4605, 5018 }, { 4607, 5098 }, { 4609, 5102 } } }, { "NtUserMNDragLeave", { 4558, { 4557, 4703 }, { 4577, 4798 }, { 4588, 4829 }, { 4602, 4967 }, { 4604, 5012 }, { 4606, 5092 }, { 4608, 5096 } } }, { "NtUserMNDragOver", { 4559, { 4558, 4704 }, { 4578, 4799 }, { 4589, 4830 }, { 4601, 4968 }, { 4603, 5013 }, { 4605, 5093 }, { 4607, 5097 } } }, { "NtUserModifyUserStartupInfoFlags", { 4560, { 4559, 4372 }, { 4579, 4373 }, { 4590, 4366 }, { 4600, 4366 }, { 4602, 4367 }, { 4604, 4368 }, { 4606, 4368 } } }, { "NtUserModifyWindowTouchCapability", { -1, { -1, -1 }, { -1, -1 }, { 4748, 4837 }, { 4770, 4974 }, { 4773, 5019 }, { 4783, 5099 }, { 4784, 5103 } } }, { "NtUserMoveWindow", { 4561, { 4560, 4189 }, { 4580, 4190 }, { 4591, 4190 }, { 4599, 4190 }, { 4601, 4191 }, { 4603, 4192 }, { 4605, 4192 } } }, { "NtUserNavigateFocus", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5222, 5100 }, { 5227, 5104 } } }, { "NtUserNotifyIMEStatus", { 4562, { 4561, 4707 }, { 4581, 4802 }, { 4592, 4838 }, { 4598, 4975 }, { 4600, 5020 }, { 4602, 5101 }, { 4604, 5105 } } }, { "NtUserNotifyProcessCreate", { 4563, { 4562, 4238 }, { 4582, 4239 }, { 4593, 4237 }, { 4597, 4237 }, { 4599, 4238 }, { 4601, 4239 }, { 4603, 4239 } } }, { "NtUserNotifyWinEvent", { 4564, { 4563, 4140 }, { 4583, 4141 }, { 4594, 4141 }, { 4596, 4142 }, { 4598, 4143 }, { 4600, 4144 }, { 4602, 4144 } } }, { "NtUserOpenClipboard", { 4565, { 4564, 4307 }, { 4584, 4308 }, { 4595, 4303 }, { 4595, 4303 }, { 4597, 4304 }, { 4599, 4305 }, { 4601, 4305 } } }, { "NtUserOpenDesktop", { 4566, { 4565, 4267 }, { 4585, 4268 }, { 4596, 4263 }, { 4594, 4263 }, { 4596, 4264 }, { 4598, 4265 }, { 4600, 4265 } } }, { "NtUserOpenInputDesktop", { 4567, { 4566, 4708 }, { 4586, 4803 }, { 4597, 4839 }, { 4593, 4976 }, { 4595, 5021 }, { 4597, 5102 }, { 4599, 5106 } } }, { "NtUserOpenThreadDesktop", { -1, { -1, -1 }, { 4587, 4804 }, { 4598, 4840 }, { 4592, 4977 }, { 4594, 5022 }, { 4596, 5103 }, { 4598, 5107 } } }, { "NtUserOpenWindowStation", { 4568, { 4567, 4257 }, { 4588, 4258 }, { 4599, 4256 }, { 4591, 4256 }, { 4593, 4257 }, { 4595, 4258 }, { 4597, 4258 } } }, { "NtUserPaintDesktop", { 4569, { 4568, 4379 }, { 4589, 4380 }, { 4600, 4373 }, { 4590, 4373 }, { 4592, 4374 }, { 4594, 4375 }, { 4596, 4375 } } }, { "NtUserPaintMenuBar", { 4663, { 4659, 4338 }, { 4687, 4339 }, { 4700, 4334 }, { 4632, 4334 }, { 4635, 4335 }, { 4638, 4336 }, { 4640, 4336 } } }, { "NtUserPaintMonitor", { -1, { -1, -1 }, { 4590, 4805 }, { 4601, 4841 }, { 4589, 4978 }, { 4591, 5023 }, { 4593, 5104 }, { 4595, 5108 } } }, { "NtUserPeekMessage", { 4570, { 4569, 4097 }, { 4591, 4097 }, { 4602, 4097 }, { 4588, 4098 }, { 4590, 4099 }, { 4592, 4100 }, { 4594, 4100 } } }, { "NtUserPerMonitorDPIPhysicalToLogicalPoint", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4584, 5024 }, { 4586, 5105 }, { 4588, 5109 } } }, { "NtUserPhysicalToLogicalPoint", { -1, { -1, -1 }, { 4592, 4806 }, { 4603, 4842 }, { 4587, 4979 }, { 4589, 5025 }, { 4591, 5106 }, { 4593, 5110 } } }, { "NtUserPostMessage", { 4571, { 4570, 4110 }, { 4593, 4111 }, { 4604, 4111 }, { 4586, 4112 }, { 4588, 4113 }, { 4590, 4114 }, { 4592, 4114 } } }, { "NtUserPostThreadMessage", { 4572, { 4571, 4190 }, { 4594, 4191 }, { 4605, 4191 }, { 4585, 4191 }, { 4587, 4192 }, { 4589, 4193 }, { 4591, 4193 } } }, { "NtUserPrintWindow", { 4573, { 4572, 4709 }, { 4595, 4807 }, { 4606, 4843 }, { 4584, 4980 }, { 4586, 5026 }, { 4588, 5107 }, { 4590, 5111 } } }, { "NtUserProcessConnect", { 4574, { 4573, 4346 }, { 4596, 4347 }, { 4607, 4342 }, { 4583, 4342 }, { 4585, 4343 }, { 4587, 4344 }, { 4589, 4344 } } }, { "NtUserPromoteMouseInPointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5072, 4981 }, { 5113, 5027 }, { 5190, 5108 }, { 5194, 5112 } } }, { "NtUserPromotePointer", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4814, 4982 }, { 4822, 5028 }, { 4833, 5109 }, { 4834, 5113 } } }, { "NtUserQueryBSDRWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4582, 4983 }, { 4583, 5029 }, { 4585, 5110 }, { 4587, 5114 } } }, { "NtUserQueryDisplayConfig", { -1, { -1, -1 }, { -1, -1 }, { 4436, 4844 }, { 4439, 4984 }, { 4441, 5030 }, { 4442, 5111 }, { 4444, 5115 } } }, { "NtUserQueryInformationThread", { 4575, { 4574, 4710 }, { 4597, 4808 }, { 4608, 4845 }, { 4581, 4985 }, { 4582, 5031 }, { 4584, 5112 }, { 4586, 5116 } } }, { "NtUserQueryInputContext", { 4576, { 4575, 4711 }, { 4598, 4809 }, { 4609, 4846 }, { 4580, 4986 }, { 4581, 5032 }, { 4583, 5113 }, { 4585, 5117 } } }, { "NtUserQuerySendMessage", { 4577, { 4576, 4712 }, { 4599, 4810 }, { 4610, 4847 }, { 4579, 4987 }, { 4580, 5033 }, { 4582, 5114 }, { 4584, 5118 } } }, { "NtUserQueryUserCounters", { 4578, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserQueryWindow", { 4579, { 4577, 4111 }, { 4600, 4112 }, { 4611, 4112 }, { 4578, 4113 }, { 4579, 4114 }, { 4581, 4115 }, { 4583, 4115 } } }, { "NtUserRealChildWindowFromPoint", { 4580, { 4578, 4713 }, { 4601, 4811 }, { 4612, 4848 }, { 4577, 4988 }, { 4578, 5034 }, { 4580, 5115 }, { 4582, 5119 } } }, { "NtUserRealInternalGetMessage", { 4581, { 4579, 4334 }, { 4602, 4335 }, { 4613, 4330 }, { 4628, 4330 }, { 4631, 4331 }, { 4633, 4332 }, { 4635, 4332 } } }, { "NtUserRealWaitMessageEx", { 4582, { 4580, 4714 }, { 4603, 4812 }, { 4614, 4849 }, { 4629, 4989 }, { 4632, 5035 }, { 4634, 5116 }, { 4636, 5120 } } }, { "NtUserRedrawWindow", { 4583, { 4581, 4114 }, { 4604, 4115 }, { 4615, 4115 }, { 4728, 4116 }, { 4731, 4117 }, { 4741, 4118 }, { 4742, 4118 } } }, { "NtUserRegisterBSDRWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4727, 4990 }, { 4730, 5036 }, { 4740, 5117 }, { 4741, 5121 } } }, { "NtUserRegisterClassExWOW", { 4584, { 4582, 4276 }, { 4605, 4277 }, { 4616, 4272 }, { 4726, 4272 }, { 4729, 4273 }, { 4739, 4274 }, { 4740, 4274 } } }, { "NtUserRegisterDManipHook", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4733, 5118 }, { 4734, 5122 } } }, { "NtUserRegisterEdgy", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4798, 4991 }, { 4801, 5037 }, { 4811, 5119 }, { 4812, 5123 } } }, { "NtUserRegisterErrorReportingDialog", { -1, { -1, -1 }, { 4606, 4813 }, { 4617, 4850 }, { 4725, 4992 }, { 4728, 5038 }, { 4738, 5120 }, { 4739, 5124 } } }, { "NtUserRegisterHotKey", { 4586, { 4584, 4715 }, { 4608, 4814 }, { 4619, 4851 }, { 4723, 4993 }, { 4726, 5039 }, { 4732, 5121 }, { 4733, 5125 } } }, { "NtUserRegisterManipulationThread", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4735, 5122 }, { 4736, 5126 } } }, { "NtUserRegisterPointerDeviceNotifications", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4810, 4994 }, { 4815, 5040 }, { 4826, 5123 }, { 4827, 5127 } } }, { "NtUserRegisterPointerInputTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4816, 4995 }, { 4824, 5041 }, { 4835, 5124 }, { 4836, 5128 } } }, { "NtUserRegisterRawInputDevices", { 4587, { 4585, 4716 }, { 4609, 4815 }, { 4620, 4852 }, { 4722, 4996 }, { 4725, 5042 }, { 4731, 5125 }, { 4732, 5129 } } }, { "NtUserRegisterServicesProcess", { -1, { -1, -1 }, { -1, -1 }, { 4621, 4853 }, { 4721, 4997 }, { 4724, 5043 }, { 4730, 5126 }, { 4731, 5130 } } }, { "NtUserRegisterSessionPort", { -1, { -1, -1 }, { 4720, 4816 }, { 4732, 4854 }, { 4738, 4998 }, { 4741, 5044 }, { 4751, 5127 }, { 4752, 5131 } } }, { "NtUserRegisterShellPTPListener", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4812, 5128 }, { 4813, 5132 } } }, { "NtUserRegisterTasklist", { 4588, { 4586, 4717 }, { 4610, 4817 }, { 4622, 4855 }, { 4720, 4999 }, { 4723, 5045 }, { 4729, 5129 }, { 4730, 5133 } } }, { "NtUserRegisterTouchHitTestingWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4804, 5000 }, { 4807, 5046 }, { 4818, 5130 }, { 4819, 5134 } } }, { "NtUserRegisterTouchPadCapable", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4811, 5047 }, { 4822, 5131 }, { 4823, 5135 } } }, { "NtUserRegisterUserApiHook", { 4585, { 4583, 4718 }, { 4607, 4818 }, { 4618, 4856 }, { 4724, 5001 }, { 4727, 5048 }, { 4737, 5132 }, { 4738, 5136 } } }, { "NtUserRegisterWindowMessage", { 4589, { 4587, 4150 }, { 4611, 4151 }, { 4623, 4151 }, { 4719, 4152 }, { 4722, 4153 }, { 4728, 4154 }, { 4729, 4154 } } }, { "NtUserReleaseDwmHitTestWaiters", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4635, 5133 }, { 4637, 5137 } } }, { "NtUserRemoteConnect", { 4690, { 4686, 4719 }, { 4715, 4819 }, { 4727, 4857 }, { 4743, 5002 }, { 4746, 5049 }, { 4756, 5134 }, { 4757, 5138 } } }, { "NtUserRemoteRedrawRectangle", { 4691, { 4687, 4720 }, { 4716, 4820 }, { 4728, 4858 }, { 4742, 5003 }, { 4745, 5050 }, { 4755, 5135 }, { 4756, 5139 } } }, { "NtUserRemoteRedrawScreen", { 4692, { 4688, -1 }, { 4717, 4821 }, { 4729, 4859 }, { 4741, 5004 }, { 4744, 5051 }, { 4754, 5136 }, { 4755, 5140 } } }, { "NtUserRemoteStopScreenUpdates", { 4693, { 4689, -1 }, { 4718, 4822 }, { 4730, 4860 }, { 4740, 5005 }, { 4743, 5052 }, { 4753, 5137 }, { 4754, 5141 } } }, { "NtUserRemoveClipboardFormatListener", { -1, { -1, -1 }, { 4612, 4823 }, { 4624, 4861 }, { 4718, 5006 }, { 4721, 5053 }, { 4727, 5138 }, { 4728, 5142 } } }, { "NtUserRemoveInjectionDevice", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 5143 }, { 5214, 5143 } } }, { "NtUserRemoveMenu", { 4590, { 4588, 4350 }, { 4613, 4351 }, { 4625, 4346 }, { 4717, 4346 }, { 4720, 4347 }, { 4726, 4348 }, { 4727, 4348 } } }, { "NtUserRemoveProp", { 4591, { 4589, 4165 }, { 4614, 4166 }, { 4626, 4166 }, { 4716, 4167 }, { 4719, 4168 }, { 4725, 4169 }, { 4726, 4169 } } }, { "NtUserReportInertia", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5128, 5054 }, { 5205, 5139 }, { 5209, 5144 } } }, { "NtUserResolveDesktop", { 4592, { 4590, 4384 }, { 4615, 4385 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserResolveDesktopForWOW", { 4593, { 4591, 4723 }, { 4616, 4824 }, { 4627, 4862 }, { 4715, 5007 }, { 4718, 5055 }, { 4724, 5140 }, { 4725, 5145 } } }, { "NtUserSBGetParms", { 4594, { 4592, 4173 }, { 4617, 4174 }, { 4628, 4174 }, { 4714, 4175 }, { 4717, 4176 }, { 4723, 4177 }, { 4724, 4177 } } }, { "NtUserScrollDC", { 4595, { 4593, 4202 }, { 4618, 4203 }, { 4629, 4203 }, { 4713, 4203 }, { 4716, 4204 }, { 4722, 4205 }, { 4723, 4205 } } }, { "NtUserScrollWindowEx", { 4596, { 4594, 4290 }, { 4619, 4291 }, { 4630, 4286 }, { 4712, 4286 }, { 4715, 4287 }, { 4721, 4288 }, { 4722, 4288 } } }, { "NtUserSelectPalette", { 4597, { 4595, 4124 }, { 4620, 4125 }, { 4631, 4125 }, { 4711, 4126 }, { 4714, 4127 }, { 4720, 4128 }, { 4721, 4128 } } }, { "NtUserSendEventMessage", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4641, 5008 }, { 4644, 5056 }, { 4647, 5141 }, { 4649, 5146 } } }, { "NtUserSendInput", { 4598, { 4596, 4227 }, { 4621, 4228 }, { 4632, 4226 }, { 4710, 4226 }, { 4713, 4227 }, { 4719, 4228 }, { 4720, 4228 } } }, { "NtUserSendTouchInput", { -1, { -1, -1 }, { -1, -1 }, { 4750, 4863 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetActivationFilter", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5103, 5057 }, { 5178, 5142 }, { 5181, 5147 } } }, { "NtUserSetActiveProcess", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5055, 5009 }, { 5095, 5058 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetActiveProcessForMonitor", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5170, 5143 }, { 5173, 5148 } } }, { "NtUserSetActiveWindow", { 4599, { 4597, 4324 }, { 4622, 4325 }, { 4633, 4320 }, { 4709, 4320 }, { 4712, 4321 }, { 4718, 4322 }, { 4719, 4322 } } }, { "NtUserSetAppImeLevel", { 4600, { 4598, 4724 }, { 4623, 4825 }, { 4634, 4864 }, { 4708, 5010 }, { 4711, 5059 }, { 4717, 5144 }, { 4718, 5149 } } }, { "NtUserSetAutoRotation", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5059, 5011 }, { 5099, 5060 }, { 5174, 5145 }, { 5177, 5150 } } }, { "NtUserSetBrokeredForeground", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5065, 5012 }, { 5105, 5061 }, { 5180, 5146 }, { 5183, 5151 } } }, { "NtUserSetCalibrationData", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4806, 5013 }, { 4809, 5062 }, { 4820, 5147 }, { 4821, 5152 } } }, { "NtUserSetCapture", { 4601, { 4599, 4168 }, { 4624, 4169 }, { 4635, 4169 }, { 4707, 4170 }, { 4710, 4171 }, { 4716, 4172 }, { 4717, 4172 } } }, { "NtUserSetChildWindowNoActivate", { -1, { -1, -1 }, { -1, -1 }, { 4636, 4865 }, { 4706, 5014 }, { 4709, 5063 }, { 4715, 5148 }, { 4716, 5153 } } }, { "NtUserSetClassLong", { 4602, { 4600, 4292 }, { 4625, 4293 }, { 4637, 4288 }, { 4705, 4288 }, { 4708, 4289 }, { 4714, 4290 }, { 4715, 4290 } } }, { "NtUserSetClassLongPtr", { -1, { -1, 4759 }, { -1, 4868 }, { -1, 4921 }, { -1, 5080 }, { -1, 5132 }, { 5224, 5224 }, { 5229, 5229 } } }, { "NtUserSetClassWord", { 4603, { 4601, 4725 }, { 4626, 4826 }, { 4638, 4866 }, { 4704, 5015 }, { 4707, 5064 }, { 4713, 5149 }, { 4714, 5154 } } }, { "NtUserSetClipboardData", { 4604, { 4602, 4309 }, { 4627, 4310 }, { 4639, 4305 }, { 4703, 4305 }, { 4706, 4306 }, { 4712, 4307 }, { 4713, 4307 } } }, { "NtUserSetClipboardViewer", { 4605, { 4603, 4385 }, { 4628, 4386 }, { 4640, 4378 }, { 4702, 4378 }, { 4705, 4379 }, { 4711, 4380 }, { 4712, 4380 } } }, { "NtUserSetConsoleReserveKeys", { 4606, { 4604, 4387 }, { 4629, 4388 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetCoreWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5220, 5150 }, { 5225, 5155 } } }, { "NtUserSetCoreWindowPartner", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5221, 5151 }, { 5226, 5156 } } }, { "NtUserSetCursor", { 4607, { 4605, 4121 }, { 4630, 4122 }, { 4641, 4122 }, { 4701, 4123 }, { 4704, 4124 }, { 4710, 4125 }, { 4711, 4125 } } }, { "NtUserSetCursorContents", { 4608, { 4606, 4726 }, { 4631, 4827 }, { 4642, 4867 }, { 4700, 5016 }, { 4703, 5065 }, { 4709, 5152 }, { 4710, 5157 } } }, { "NtUserSetCursorIconData", { 4609, { 4607, 4264 }, { 4632, 4265 }, { 4643, 4260 }, { 4699, 4260 }, { 4702, 4261 }, { 4708, 4262 }, { 4709, 4262 } } }, { "NtUserSetDbgTag", { 4610, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetDisplayAutoRotationPreferences", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5058, 5017 }, { 5098, 5066 }, { 5173, 5153 }, { 5176, 5158 } } }, { "NtUserSetDisplayConfig", { -1, { -1, -1 }, { -1, -1 }, { 4435, 4868 }, { 4440, 5018 }, { 4442, 5067 }, { 4443, 5154 }, { 4445, 5159 } } }, { "NtUserSetDisplayMapping", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4805, 5019 }, { 4808, 5068 }, { 4819, 5155 }, { 4820, 5160 } } }, { "NtUserSetFallbackForeground", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5064, 5020 }, { 5104, 5069 }, { 5179, 5156 }, { 5182, 5161 } } }, { "NtUserSetFeatureReportResponse", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5210, 5157 }, { 5215, 5162 } } }, { "NtUserSetFocus", { 4611, { 4608, 4176 }, { 4633, 4177 }, { 4644, 4177 }, { 4698, 4178 }, { 4701, 4179 }, { 4707, 4180 }, { 4708, 4180 } } }, { "NtUserSetGestureConfig", { -1, { -1, -1 }, { -1, -1 }, { 4758, 4869 }, { 4821, 5021 }, { 4830, 5070 }, { 4842, 5158 }, { 4843, 5163 } } }, { "NtUserSetImeHotKey", { 4612, { 4609, 4727 }, { 4634, 4828 }, { 4645, 4870 }, { 4697, 5022 }, { 4700, 5071 }, { 4706, 5159 }, { 4707, 5164 } } }, { "NtUserSetImeInfoEx", { 4613, { 4610, -1 }, { 4635, 4829 }, { 4646, 4871 }, { 4696, 5023 }, { 4699, 5072 }, { 4705, 5160 }, { 4706, 5165 } } }, { "NtUserSetImeOwnerWindow", { 4614, { 4611, 4729 }, { 4636, 4830 }, { 4647, 4872 }, { 4695, 5024 }, { 4698, 5073 }, { 4704, 5161 }, { 4705, 5166 } } }, { "NtUserSetImmersiveBackgroundWindow", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4681, 5025 }, { 4684, 5074 }, { 4690, 5162 }, { -1, -1 } } }, { "NtUserSetInformationProcess", { 4615, { 4612, 4352 }, { 4637, 4353 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetInformationThread", { 4616, { 4613, 4325 }, { 4638, 4326 }, { 4648, 4321 }, { 4694, 4321 }, { 4697, 4322 }, { 4703, 4323 }, { 4704, 4323 } } }, { "NtUserSetInternalWindowPos", { 4617, { 4614, 4730 }, { 4639, 4831 }, { 4649, 4873 }, { 4693, 5026 }, { 4696, 5075 }, { 4702, 5163 }, { 4703, 5167 } } }, { "NtUserSetKeyboardState", { 4618, { 4615, 4339 }, { 4640, 4340 }, { 4650, 4335 }, { 4692, 4335 }, { 4695, 4336 }, { 4701, 4337 }, { 4702, 4337 } } }, { "NtUserSetLayeredWindowAttributes", { 4677, { 4673, 4731 }, { 4701, 4832 }, { 4714, 4874 }, { 4756, 5027 }, { 4759, 5076 }, { 4769, 5164 }, { 4770, 5168 } } }, { "NtUserSetLogonNotifyWindow", { 4619, { 4616, 4732 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetManipulationInputTarget", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4736, 5165 }, { 4737, 5169 } } }, { "NtUserSetMenu", { 4620, { 4617, 4733 }, { 4641, 4833 }, { 4651, 4875 }, { 4691, 5028 }, { 4694, 5077 }, { 4700, 5166 }, { 4701, 5170 } } }, { "NtUserSetMenuContextHelpId", { 4621, { 4618, 4734 }, { 4642, 4834 }, { 4652, 4876 }, { 4690, 5029 }, { 4693, 5078 }, { 4699, 5167 }, { 4700, 5171 } } }, { "NtUserSetMenuDefaultItem", { 4622, { 4619, 4359 }, { 4643, 4360 }, { 4653, 4354 }, { 4689, 4354 }, { 4692, 4355 }, { 4698, 4356 }, { 4699, 4356 } } }, { "NtUserSetMenuFlagRtoL", { 4623, { 4620, 4735 }, { 4644, 4835 }, { 4654, 4877 }, { 4688, 5030 }, { 4691, 5079 }, { 4697, 5168 }, { 4698, 5172 } } }, { "NtUserSetMirrorRendering", { -1, { -1, -1 }, { 4866, 4836 }, { 4914, 4878 }, { 4985, 5031 }, { 5003, 5080 }, { 5060, 5169 }, { 5062, 5173 } } }, { "NtUserSetObjectInformation", { 4624, { 4621, 4736 }, { 4645, 4837 }, { 4655, 4879 }, { 4687, 5032 }, { 4690, 5081 }, { 4696, 5170 }, { 4697, 5174 } } }, { "NtUserSetParent", { 4625, { 4622, 4216 }, { 4646, 4217 }, { 4656, 4215 }, { 4686, 4215 }, { 4689, 4216 }, { 4695, 4217 }, { 4696, 4217 } } }, { "NtUserSetPrecisionTouchPadConfiguration", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4821, 5082 }, { 4832, 5171 }, { 4833, 5175 } } }, { "NtUserSetProcessDPIAware", { -1, { -1, -1 }, { 4660, 4838 }, { 4670, 4880 }, { 4670, 5033 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetProcessDpiAwareness", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4673, 5083 }, { 4676, 5172 }, { 4678, 5176 } } }, { "NtUserSetProcessRestrictionExemption", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5069, 5034 }, { 5110, 5084 }, { 5185, 5173 }, { 5188, 5177 } } }, { "NtUserSetProcessUIAccessZorder", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4669, 5035 }, { 4672, 5085 }, { 4675, 5174 }, { 4677, 5178 } } }, { "NtUserSetProcessWindowStation", { 4626, { 4623, 4268 }, { 4647, 4269 }, { 4657, 4264 }, { 4685, 4264 }, { 4688, 4265 }, { 4694, 4266 }, { 4695, 4266 } } }, { "NtUserSetProp", { 4627, { 4624, 4171 }, { 4649, 4172 }, { 4659, 4172 }, { 4683, 4173 }, { 4686, 4174 }, { 4692, 4175 }, { 4693, 4175 } } }, { "NtUserSetRipFlags", { 4628, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSetScrollInfo", { 4629, { 4625, 4143 }, { 4650, 4144 }, { 4660, 4144 }, { 4682, 4145 }, { 4685, 4146 }, { 4691, 4147 }, { 4692, 4147 } } }, { "NtUserSetSensorPresence", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5062, 5036 }, { 4097, 4097 }, { 4098, 4098 }, { 4098, 4098 } } }, { "NtUserSetShellWindowEx", { 4630, { 4626, 4737 }, { 4651, 4839 }, { 4661, 4881 }, { 4680, 5037 }, { 4683, 5086 }, { 4689, 5175 }, { 4691, 5179 } } }, { "NtUserSetSysColors", { 4631, { 4627, 4738 }, { 4652, 4840 }, { 4662, 4882 }, { 4679, 5038 }, { 4682, 5087 }, { 4688, 5176 }, { 4690, 5180 } } }, { "NtUserSetSystemCursor", { 4632, { 4628, 4739 }, { 4653, 4841 }, { 4663, 4883 }, { 4678, 5039 }, { 4681, 5088 }, { 4687, 5177 }, { 4689, 5181 } } }, { "NtUserSetSystemMenu", { 4633, { 4629, 4365 }, { 4654, 4366 }, { 4664, 4359 }, { 4677, 4359 }, { 4680, 4360 }, { 4686, 4361 }, { 4688, 4361 } } }, { "NtUserSetSystemTimer", { 4634, { 4630, 4740 }, { 4655, 4842 }, { 4665, 4884 }, { 4676, 5040 }, { 4679, 5089 }, { 4685, 5178 }, { 4687, 5182 } } }, { "NtUserSetThreadDesktop", { 4635, { 4631, 4242 }, { 4656, 4243 }, { 4666, 4241 }, { 4674, 4241 }, { 4677, 4242 }, { 4683, 4243 }, { 4685, 4243 } } }, { "NtUserSetThreadInputBlocked", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4675, 5041 }, { 4678, 5090 }, { 4684, 5179 }, { 4686, 5183 } } }, { "NtUserSetThreadLayoutHandles", { 4636, { 4632, 4741 }, { 4657, 4843 }, { 4667, 4885 }, { 4673, 5042 }, { 4676, 5091 }, { 4682, 5180 }, { 4684, 5184 } } }, { "NtUserSetThreadState", { 4637, { 4633, 4317 }, { 4658, 4318 }, { 4668, 4313 }, { 4672, 4313 }, { 4675, 4314 }, { 4681, 4315 }, { 4683, 4315 } } }, { "NtUserSetTimer", { 4638, { 4634, 4119 }, { 4659, 4120 }, { 4669, 4120 }, { 4671, 4121 }, { 4674, 4122 }, { 4680, 4123 }, { 4682, 4123 } } }, { "NtUserSetWindowArrangement", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5186, 5181 }, { 5189, 5185 } } }, { "NtUserSetWindowBand", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4668, 5043 }, { 4671, 5092 }, { 4674, 5182 }, { 4676, 5186 } } }, { "NtUserSetWindowCompositionAttribute", { -1, { -1, -1 }, { -1, -1 }, { 4671, 4886 }, { 4667, 5044 }, { 4670, 5093 }, { 4673, 5183 }, { 4675, 5187 } } }, { "NtUserSetWindowCompositionTransition", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4665, 5045 }, { 4668, 5094 }, { 4671, 5184 }, { 4673, 5188 } } }, { "NtUserSetWindowDisplayAffinity", { -1, { -1, -1 }, { -1, -1 }, { 4672, 4887 }, { 4664, 5046 }, { 4667, 5095 }, { 4670, 5185 }, { 4672, 5189 } } }, { "NtUserSetWindowFeedbackSetting", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4797, 5047 }, { 4800, 5096 }, { 4810, 5186 }, { 4811, 5190 } } }, { "NtUserSetWindowFNID", { 4639, { 4635, 4246 }, { 4661, 4247 }, { 4673, 4245 }, { 4663, 4245 }, { 4666, 4246 }, { 4669, 4247 }, { 4671, 4247 } } }, { "NtUserSetWindowLong", { 4640, { 4636, 4187 }, { 4662, 4188 }, { 4674, 4188 }, { 4662, 4188 }, { 4665, 4189 }, { 4668, 4190 }, { 4670, 4190 } } }, { "NtUserSetWindowLongPtr", { -1, { -1, 4760 }, { -1, 4869 }, { -1, 4922 }, { -1, 5081 }, { -1, 5133 }, { 5225, 5225 }, { 5230, 5230 } } }, { "NtUserSetWindowPlacement", { 4641, { 4637, 4326 }, { 4663, 4327 }, { 4675, 4322 }, { 4661, 4322 }, { 4664, 4323 }, { 4667, 4324 }, { 4669, 4324 } } }, { "NtUserSetWindowPos", { 4642, { 4638, 4131 }, { 4664, 4132 }, { 4676, 4132 }, { 4660, 4133 }, { 4663, 4134 }, { 4666, 4135 }, { 4668, 4135 } } }, { "NtUserSetWindowRgn", { 4643, { 4639, 4302 }, { 4665, 4303 }, { 4677, 4298 }, { 4659, 4298 }, { 4662, 4299 }, { 4665, 4300 }, { 4667, 4300 } } }, { "NtUserSetWindowRgnEx", { -1, { -1, -1 }, { 4667, 4844 }, { 4679, 4888 }, { 4657, 5048 }, { 4660, 5097 }, { 4663, 5187 }, { 4665, 5191 } } }, { "NtUserSetWindowsHookAW", { 4644, { 4640, 4358 }, { 4668, 4359 }, { 4680, 4353 }, { 4656, 4353 }, { 4659, 4354 }, { 4662, 4355 }, { 4664, 4355 } } }, { "NtUserSetWindowsHookEx", { 4645, { 4641, 4237 }, { 4669, 4238 }, { 4681, 4236 }, { 4655, 4236 }, { 4658, 4237 }, { 4661, 4238 }, { 4663, 4238 } } }, { "NtUserSetWindowShowState", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5187, 5188 }, { 5190, 5192 } } }, { "NtUserSetWindowStationUser", { 4646, { 4642, 4742 }, { 4670, 4845 }, { 4682, 4889 }, { 4654, 5049 }, { 4657, 5098 }, { 4660, 5189 }, { 4662, 5193 } } }, { "NtUserSetWindowWord", { 4647, { 4643, 4332 }, { 4671, 4333 }, { 4683, 4328 }, { 4653, 4328 }, { 4656, 4329 }, { 4659, 4330 }, { 4661, 4330 } } }, { "NtUserSetWinEventHook", { 4648, { 4644, 4361 }, { 4672, 4362 }, { 4684, 4356 }, { 4652, 4356 }, { 4655, 4357 }, { 4658, 4358 }, { 4660, 4358 } } }, { "NtUserSfmDestroyLogicalSurfaceBinding", { -1, { -1, -1 }, { -1, -1 }, { 4747, 4890 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxBindSwapChain", { -1, { -1, -1 }, { -1, -1 }, { 4738, 4891 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxGetSwapChainStats", { -1, { -1, -1 }, { -1, -1 }, { 4744, 4892 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxOpenSwapChain", { -1, { -1, -1 }, { -1, -1 }, { 4739, 4893 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxQuerySwapChainBindingStatus", { -1, { -1, -1 }, { -1, -1 }, { 4742, 4894 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxReleaseSwapChain", { -1, { -1, -1 }, { -1, -1 }, { 4740, 4895 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxReportPendingBindingsToDwm", { -1, { -1, -1 }, { -1, -1 }, { 4743, 4896 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxSetSwapChainBindingStatus", { -1, { -1, -1 }, { -1, -1 }, { 4741, 4897 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmDxSetSwapChainStats", { -1, { -1, -1 }, { -1, -1 }, { 4745, 4898 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserSfmGetLogicalSurfaceBinding", { -1, { -1, -1 }, { -1, -1 }, { 4746, 4899 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserShowCaret", { 4649, { 4645, 4132 }, { 4673, 4133 }, { 4685, 4133 }, { 4651, 4134 }, { 4654, 4135 }, { 4657, 4136 }, { 4659, 4136 } } }, { "NtUserShowScrollBar", { 4650, { 4646, 4156 }, { 4674, 4157 }, { 4686, 4157 }, { 4650, 4158 }, { 4653, 4159 }, { 4656, 4160 }, { 4658, 4160 } } }, { "NtUserShowSystemCursor", { -1, { -1, -1 }, { 4867, 4846 }, { 4915, 4900 }, { 4984, 5050 }, { 5002, 5099 }, { 5059, 5190 }, { 5061, 5194 } } }, { "NtUserShowWindow", { 4651, { 4647, 4183 }, { 4675, 4184 }, { 4687, 4184 }, { 4649, 4184 }, { 4652, 4185 }, { 4655, 4186 }, { 4657, 4186 } } }, { "NtUserShowWindowAsync", { 4652, { 4648, 4386 }, { 4676, 4387 }, { 4688, 4379 }, { 4648, 4379 }, { 4651, 4380 }, { 4654, 4381 }, { 4656, 4381 } } }, { "NtUserShutdownBlockReasonCreate", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4647, 5051 }, { 4650, 5100 }, { 4653, 5191 }, { 4655, 5195 } } }, { "NtUserShutdownBlockReasonQuery", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4646, 5052 }, { 4649, 5101 }, { 4652, 5192 }, { 4654, 5196 } } }, { "NtUserShutdownReasonDestroy", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4645, 5053 }, { 4648, 5102 }, { 4651, 5193 }, { 4653, 5197 } } }, { "NtUserSignalRedirectionStartComplete", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5054, 5054 }, { 5094, 5103 }, { 5169, 5194 }, { 5172, 5198 } } }, { "NtUserSlicerControl", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4989, 5055 }, { 5007, 5104 }, { 5064, 5195 }, { 5066, 5199 } } }, { "NtUserSoundSentry", { 4653, { 4649, -1 }, { 4677, 4847 }, { 4689, 4901 }, { 4644, 5056 }, { 4647, 5105 }, { 4650, 5196 }, { 4652, 5200 } } }, { "NtUserSwitchDesktop", { 4654, { 4650, 4744 }, { 4678, 4848 }, { 4690, 4902 }, { 4643, 5057 }, { 4646, 5106 }, { 4649, 5197 }, { 4651, 5201 } } }, { "NtUserSystemParametersInfo", { 4655, { 4651, 4161 }, { 4679, 4162 }, { 4691, 4162 }, { 4642, 4163 }, { 4645, 4164 }, { 4648, 4165 }, { 4650, 4165 } } }, { "NtUserTestForInteractiveUser", { 4656, { 4652, 4745 }, { 4680, 4849 }, { 4692, 4903 }, { 4640, 5058 }, { 4643, 5107 }, { 4646, 5198 }, { 4648, 5202 } } }, { "NtUserThunkedMenuInfo", { 4657, { 4653, 4366 }, { 4681, 4367 }, { 4693, 4360 }, { 4639, 4360 }, { 4642, 4361 }, { 4645, 4362 }, { 4647, 4362 } } }, { "NtUserThunkedMenuItemInfo", { 4658, { 4654, 4249 }, { 4682, 4250 }, { 4694, 4248 }, { 4638, 4248 }, { 4641, 4249 }, { 4644, 4250 }, { 4646, 4250 } } }, { "NtUserToUnicodeEx", { 4659, { 4655, 4218 }, { 4683, 4219 }, { 4695, 4217 }, { 4637, 4217 }, { 4640, 4218 }, { 4643, 4219 }, { 4645, 4219 } } }, { "NtUserTrackMouseEvent", { 4660, { 4656, 4319 }, { 4684, 4320 }, { 4696, 4315 }, { 4636, 4315 }, { 4639, 4316 }, { 4642, 4317 }, { 4644, 4317 } } }, { "NtUserTrackPopupMenuEx", { 4661, { 4657, 4746 }, { 4685, 4850 }, { 4697, 4904 }, { 4635, 5059 }, { 4638, 5108 }, { 4641, 5199 }, { 4643, 5203 } } }, { "NtUserTransformPoint", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5123, 5109 }, { 5200, 5200 }, { 5204, 5204 } } }, { "NtUserTransformRect", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5124, 5110 }, { 5201, 5201 }, { 5205, 5205 } } }, { "NtUserTranslateAccelerator", { 4664, { 4660, 4112 }, { 4688, 4113 }, { 4701, 4113 }, { 4631, 4114 }, { 4634, 4115 }, { 4637, 4116 }, { 4639, 4116 } } }, { "NtUserTranslateMessage", { 4665, { 4661, 4109 }, { 4689, 4109 }, { 4702, 4109 }, { 4630, 4110 }, { 4633, 4111 }, { 4636, 4112 }, { 4638, 4112 } } }, { "NtUserUndelegateInput", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4729, 5060 }, { 4732, 5111 }, { 4742, 5202 }, { 4743, 5206 } } }, { "NtUserUnhookWindowsHookEx", { 4666, { 4662, 4208 }, { 4690, 4209 }, { 4703, 4208 }, { 4767, 4208 }, { 4770, 4209 }, { 4780, 4210 }, { 4781, 4210 } } }, { "NtUserUnhookWinEvent", { 4667, { 4663, 4362 }, { 4691, 4363 }, { 4704, 4357 }, { 4766, 4357 }, { 4769, 4358 }, { 4779, 4359 }, { 4780, 4359 } } }, { "NtUserUnloadKeyboardLayout", { 4668, { 4664, 4747 }, { 4692, 4851 }, { 4705, 4905 }, { 4765, 5061 }, { 4768, 5112 }, { 4778, 5203 }, { 4779, 5207 } } }, { "NtUserUnlockWindowStation", { 4669, { 4665, 4748 }, { 4693, 4852 }, { 4706, 4906 }, { 4764, 5062 }, { 4767, 5113 }, { 4777, 5204 }, { 4778, 5208 } } }, { "NtUserUnregisterClass", { 4670, { 4666, 4287 }, { 4694, 4288 }, { 4707, 4283 }, { 4763, 4283 }, { 4766, 4284 }, { 4776, 4285 }, { 4777, 4285 } } }, { "NtUserUnregisterHotKey", { 4672, { 4668, 4749 }, { 4696, 4853 }, { 4709, 4907 }, { 4761, 5063 }, { 4764, 5114 }, { 4774, 5205 }, { 4775, 5209 } } }, { "NtUserUnregisterSessionPort", { -1, { -1, -1 }, { 4721, 4854 }, { 4733, 4908 }, { 4737, 5064 }, { 4740, 5115 }, { 4750, 5206 }, { 4751, 5210 } } }, { "NtUserUnregisterUserApiHook", { 4671, { 4667, 4750 }, { 4695, 4855 }, { 4708, 4909 }, { 4762, 5065 }, { 4765, 5116 }, { 4775, 5207 }, { 4776, 5211 } } }, { "NtUserUpdateDefaultDesktopThumbnail", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4666, 5066 }, { 4669, 5117 }, { 4672, 5208 }, { 4674, 5212 } } }, { "NtUserUpdateInputContext", { 4673, { 4669, 4751 }, { 4697, 4856 }, { 4710, 4910 }, { 4760, 5067 }, { 4763, 5118 }, { 4773, 5209 }, { 4774, 5213 } } }, { "NtUserUpdateInstance", { 4674, { 4670, 4752 }, { 4698, 4857 }, { 4711, 4911 }, { 4759, 5068 }, { 4762, 5119 }, { 4772, 5210 }, { 4773, 5214 } } }, { "NtUserUpdateLayeredWindow", { 4675, { 4671, 4753 }, { 4699, 4858 }, { 4712, 4912 }, { 4758, 5069 }, { 4761, 5120 }, { 4771, 5211 }, { 4772, 5215 } } }, { "NtUserUpdatePerUserSystemParameters", { 4678, { 4674, 4754 }, { 4702, 4859 }, { 4715, 4913 }, { 4755, 5070 }, { 4758, 5121 }, { 4768, 5212 }, { 4769, 5216 } } }, { "NtUserUpdateWindowInputSinkHints", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5122, 5122 }, { 5199, 5213 }, { 5203, 5217 } } }, { "NtUserUpdateWindowTrackingInfo", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, 5218 }, { 5191, 5218 } } }, { "NtUserUpdateWindowTransform", { -1, { -1, -1 }, { 4722, 4860 }, { 4734, 4914 }, { 4735, 5071 }, { 4738, 5123 }, { 4748, 5214 }, { 4749, 5219 } } }, { "NtUserUserHandleGrantAccess", { 4679, { 4675, 4755 }, { 4703, 4861 }, { 4716, 4915 }, { 4754, 5072 }, { 4757, 5124 }, { 4767, 5215 }, { 4768, 5220 } } }, { "NtUserValidateHandleSecure", { 4680, { 4676, 4756 }, { 4704, 4862 }, { 4717, 4916 }, { 4753, 5073 }, { 4756, 5125 }, { 4766, 5216 }, { 4767, 5221 } } }, { "NtUserValidateRect", { 4681, { 4677, 4305 }, { 4705, 4306 }, { 4718, 4301 }, { 4752, 4301 }, { 4755, 4302 }, { 4765, 4303 }, { 4766, 4303 } } }, { "NtUserValidateTimerCallback", { 4682, { 4678, 4117 }, { 4706, 4118 }, { 4719, 4118 }, { 4751, 4119 }, { 4754, 4120 }, { 4764, 4121 }, { 4765, 4121 } } }, { "NtUserVkKeyScanEx", { 4683, { 4679, 4135 }, { 4707, 4136 }, { 4720, 4136 }, { 4750, 4137 }, { 4753, 4138 }, { 4763, 4139 }, { 4764, 4139 } } }, { "NtUserWaitAvailableMessageEx", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4744, 5074 }, { 4747, 5126 }, { 4757, 5217 }, { 4758, 5222 } } }, { "NtUserWaitForInputIdle", { 4684, { 4680, 4757 }, { 4708, 4863 }, { 4721, 4917 }, { 4749, 5075 }, { 4752, 5127 }, { 4762, 5218 }, { 4763, 5223 } } }, { "NtUserWaitForMsgAndEvent", { 4685, { 4681, 4758 }, { 4709, 4864 }, { 4722, 4918 }, { 4748, 5076 }, { 4751, 5128 }, { 4761, 5219 }, { 4762, 5224 } } }, { "NtUserWaitForRedirectionStartComplete", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5053, 5077 }, { 5093, 5129 }, { 5168, 5220 }, { 5171, 5225 } } }, { "NtUserWaitMessage", { 4686, { 4682, 4108 }, { 4710, 4108 }, { 4723, 4108 }, { 4747, 4109 }, { 4750, 4110 }, { 4760, 4111 }, { 4761, 4111 } } }, { "NtUserWin32PoolAllocationStats", { 4687, { 4683, 4761 }, { 4711, 4865 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } } }, { "NtUserWindowFromPhysicalPoint", { -1, { -1, -1 }, { 4712, 4866 }, { 4724, 4919 }, { 4746, 5078 }, { 4749, 5130 }, { 4759, 5221 }, { 4760, 5226 } } }, { "NtUserWindowFromPoint", { 4688, { 4684, 4115 }, { 4713, 4116 }, { 4725, 4116 }, { 4745, 4117 }, { 4748, 4118 }, { 4758, 4119 }, { 4759, 4119 } } }, { "NtUserYieldTask", { 4689, { 4685, 4762 }, { 4714, 4867 }, { 4726, 4920 }, { 4096, 4096 }, { 4096, 4096 }, { 4097, 4097 }, { 4097, 4097 } } }, { "NtValidateCompositionSurfaceHandle", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 4993, 5079 }, { 5011, 5131 }, { 5068, 5222 }, { 5070, 5227 } } }, { "NtVisualCaptureBits", { -1, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 }, { 5084, 5223 }, { 5086, 5228 } } } };
C/C++
x64dbg-development/src/dbg/taskthread.h
#ifndef _TASKTHREAD_H #define _TASKTHREAD_H #include "_global.h" #include <thread> #include <tuple> #include <type_traits> #include <utility> const size_t TASK_THREAD_DEFAULT_SLEEP_TIME = 100; template <typename F, typename... Args> class TaskThread_ { protected: F fn; std::tuple<Args...> args; bool active = true; HANDLE hThread; CRITICAL_SECTION access; HANDLE wakeupSemaphore; size_t minSleepTimeMs = 0; size_t wakeups = 0; size_t execs = 0; void Loop(); // Given new args, compress it into old args. virtual std::tuple<Args...> CompressArguments(Args && ... args); // Reset called after we latch in a value virtual void ResetArgs() { } public: void WakeUp(Args...); explicit TaskThread_(F, size_t minSleepTimeMs = TASK_THREAD_DEFAULT_SLEEP_TIME); virtual ~TaskThread_(); }; template <typename F> class StringConcatTaskThread_ : public TaskThread_<F, std::string> { virtual std::tuple<std::string> CompressArguments(std::string && msg) override { std::get<0>(this->args) += msg; return this->args; } // Reset called after we latch in a value void ResetArgs() override { std::get<0>(this->args).resize(0); } public: explicit StringConcatTaskThread_(F fn, size_t minSleepTimeMs = TASK_THREAD_DEFAULT_SLEEP_TIME) : TaskThread_<F, std::string>(fn, minSleepTimeMs) {} }; // using aliases for cleaner syntax template<class T> using Invoke = typename T::type; template<unsigned...> struct seq { using type = seq; }; template<class S1, class S2> struct concat; template<unsigned... I1, unsigned... I2> struct concat<seq<I1...>, seq<I2...>> : seq < I1..., (sizeof...(I1) + I2)... > {}; template<class S1, class S2> using Concat = Invoke<concat<S1, S2>>; template<unsigned N> struct gen_seq; template<unsigned N> using GenSeq = Invoke<gen_seq<N>>; template<unsigned N> struct gen_seq : Concat < GenSeq < N / 2 >, GenSeq < N - N / 2 >> {}; template<> struct gen_seq<0> : seq<> {}; template<> struct gen_seq<1> : seq<0> {}; #define DECLTYPE_AND_RETURN( eval ) -> decltype ( eval ) { return eval; } template<typename F, typename Tuple, unsigned ...S> auto apply_tuple_impl(F && fn, Tuple && t, const seq<S...> &) DECLTYPE_AND_RETURN(std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...)); template<typename F, typename Tuple> auto apply_from_tuple(F && fn, Tuple && t) DECLTYPE_AND_RETURN(apply_tuple_impl(std::forward<F>(fn), std::forward<Tuple>(t), GenSeq < std::tuple_size<typename std::remove_reference<Tuple>::type>::value > ())); template <typename F, typename... Args> std::tuple<Args...> TaskThread_<F, Args...>::CompressArguments(Args && ... _args) { return std::make_tuple<Args...>(std::forward<Args>(_args)...); } template <typename F, typename... Args> void TaskThread_<F, Args...>::WakeUp(Args... _args) { ++this->wakeups; EnterCriticalSection(&this->access); this->args = CompressArguments(std::forward<Args>(_args)...); LeaveCriticalSection(&this->access); // This will fail silently if it's redundant, which is what we want. ReleaseSemaphore(this->wakeupSemaphore, 1, nullptr); } template <typename F, typename... Args> void TaskThread_<F, Args...>::Loop() { std::tuple<Args...> argLatch; while(this->active) { WaitForSingleObject(this->wakeupSemaphore, INFINITE); EnterCriticalSection(&this->access); argLatch = this->args; this->ResetArgs(); LeaveCriticalSection(&this->access); if(this->active) { apply_from_tuple(this->fn, argLatch); std::this_thread::sleep_for(std::chrono::milliseconds(this->minSleepTimeMs)); ++this->execs; } } } template <typename F, typename... Args> TaskThread_<F, Args...>::TaskThread_(F fn, size_t minSleepTimeMs) : fn(fn), minSleepTimeMs(minSleepTimeMs) { this->wakeupSemaphore = CreateSemaphoreW(nullptr, 0, 1, nullptr); InitializeCriticalSection(&this->access); this->hThread = CreateThread(nullptr, 0, [](LPVOID thisPtr) -> DWORD { ((TaskThread_<F, Args...>*)thisPtr)->Loop(); return 0; }, this, 0, nullptr); } template <typename F, typename... Args> TaskThread_<F, Args...>::~TaskThread_() { EnterCriticalSection(&this->access); this->active = false; LeaveCriticalSection(&this->access); ReleaseSemaphore(this->wakeupSemaphore, 1, nullptr); WaitForSingleObject(this->hThread, INFINITE); CloseHandle(this->hThread); DeleteCriticalSection(&this->access); CloseHandle(this->wakeupSemaphore); } #endif // _TASKTHREAD_H
C++
x64dbg-development/src/dbg/tcpconnections.cpp
#include <WS2tcpip.h> #undef _WIN32_WINNT #undef WINVER #undef _WIN32_IE #include "tcpconnections.h" #include "IPHlpApi.h" static const char* TcpStateToString(DWORD State) { switch(State) { case MIB_TCP_STATE_CLOSED: return "CLOSED"; case MIB_TCP_STATE_LISTEN: return "LISTEN"; case MIB_TCP_STATE_SYN_SENT: return "SYN-SENT"; case MIB_TCP_STATE_SYN_RCVD: return "SYN-RECEIVED"; case MIB_TCP_STATE_ESTAB: return "ESTABLISHED"; case MIB_TCP_STATE_FIN_WAIT1: return "FIN-WAIT-1"; case MIB_TCP_STATE_FIN_WAIT2: return "FIN-WAIT-2"; case MIB_TCP_STATE_CLOSE_WAIT: return "CLOSE-WAIT"; case MIB_TCP_STATE_CLOSING: return "CLOSING"; case MIB_TCP_STATE_LAST_ACK: return "LAST-ACK"; case MIB_TCP_STATE_TIME_WAIT: return "TIME-WAIT"; case MIB_TCP_STATE_DELETE_TCB: return "DELETE-TCB"; default: return "UNKNOWN"; } } typedef ULONG(WINAPI* GETTCPTABLE2)(PMIB_TCPTABLE2 TcpTable, PULONG SizePointer, BOOL Order); typedef ULONG(WINAPI* GETTCP6TABLE2)(PMIB_TCP6TABLE2 TcpTable, PULONG SizePointer, BOOL Order); typedef PCTSTR(WSAAPI* INETNTOPW)(INT Family, PVOID pAddr, wchar_t* pStringBuf, size_t StringBufSize); bool TcpEnumConnections(duint pid, std::vector<TCPCONNECTIONINFO> & connections) { // The following code is modified from code sample at MSDN.GetTcpTable2 static auto hIpHlp = LoadLibraryW(L"iphlpapi.dll"); if(!hIpHlp) return false; // To ensure WindowsXP compatibility we won't link them statically static auto GetTcpTable2 = GETTCPTABLE2(GetProcAddress(hIpHlp, "GetTcpTable2")); static auto GetTcp6Table2 = GETTCP6TABLE2(GetProcAddress(hIpHlp, "GetTcp6Table2")); static auto InetNtopW = INETNTOPW(GetProcAddress(GetModuleHandleW(L"ws2_32.dll"), "InetNtopW")); if(!InetNtopW) return false; TCPCONNECTIONINFO info; wchar_t AddrBuffer[TCP_ADDR_SIZE] = L""; if(GetTcpTable2) { ULONG ulSize = 0; // Make an initial call to GetTcpTable2 to get the necessary size into the ulSize variable if(GetTcpTable2(nullptr, &ulSize, TRUE) == ERROR_INSUFFICIENT_BUFFER) { Memory<MIB_TCPTABLE2*> pTcpTable(ulSize); // Make a second call to GetTcpTable2 to get the actual data we require if(GetTcpTable2(pTcpTable(), &ulSize, TRUE) == NO_ERROR) { for(auto i = 0; i < int(pTcpTable()->dwNumEntries); i++) { auto & entry = pTcpTable()->table[i]; if(entry.dwOwningPid != pid) continue; info.State = entry.dwState; strcpy_s(info.StateText, TcpStateToString(info.State)); struct in_addr IpAddr; IpAddr.S_un.S_addr = u_long(entry.dwLocalAddr); InetNtopW(AF_INET, &IpAddr, AddrBuffer, TCP_ADDR_SIZE); strcpy_s(info.LocalAddress, StringUtils::Utf16ToUtf8(AddrBuffer).c_str()); info.LocalPort = ntohs(u_short(entry.dwLocalPort)); IpAddr.S_un.S_addr = u_long(entry.dwRemoteAddr); InetNtopW(AF_INET, &IpAddr, AddrBuffer, TCP_ADDR_SIZE); strcpy_s(info.RemoteAddress, StringUtils::Utf16ToUtf8(AddrBuffer).c_str()); info.RemotePort = ntohs(u_short(entry.dwRemotePort)); connections.push_back(info); } } } } if(GetTcp6Table2) { ULONG ulSize = 0; // Make an initial call to GetTcp6Table2 to get the necessary size into the ulSize variable if(GetTcp6Table2(nullptr, &ulSize, TRUE) == ERROR_INSUFFICIENT_BUFFER) { Memory<MIB_TCP6TABLE2*> pTcp6Table(ulSize); // Make a second call to GetTcpTable2 to get the actual data we require if(GetTcp6Table2(pTcp6Table(), &ulSize, TRUE) == NO_ERROR) { for(auto i = 0; i < int(pTcp6Table()->dwNumEntries); i++) { auto & entry = pTcp6Table()->table[i]; if(entry.dwOwningPid != pid) continue; info.State = entry.State; strcpy_s(info.StateText, TcpStateToString(info.State)); InetNtopW(AF_INET6, &entry.LocalAddr, AddrBuffer, TCP_ADDR_SIZE); sprintf_s(info.LocalAddress, "[%s]", StringUtils::Utf16ToUtf8(AddrBuffer).c_str()); info.LocalPort = ntohs(u_short(entry.dwLocalPort)); InetNtopW(AF_INET6, &entry.RemoteAddr, AddrBuffer, TCP_ADDR_SIZE); sprintf_s(info.RemoteAddress, "[%s]", StringUtils::Utf16ToUtf8(AddrBuffer).c_str()); info.RemotePort = ntohs(u_short(entry.dwRemotePort)); connections.push_back(info); } } } } return true; }
C/C++
x64dbg-development/src/dbg/tcpconnections.h
#pragma once #include "_global.h" #include "_dbgfunctions.h" bool TcpEnumConnections(duint pid, std::vector<TCPCONNECTIONINFO> & connections);
C++
x64dbg-development/src/dbg/thread.cpp
/** @file thread.cpp @brief Implements the thread class. */ #include "thread.h" #include "memory.h" #include "threading.h" #include "ntdll/ntdll.h" #include "debugger.h" static std::unordered_map<DWORD, THREADINFO> threadList; static std::unordered_map<DWORD, THREADWAITREASON> threadWaitReasons; // Function pointer for dynamic linking. Do not link statically for Windows XP compatibility. // TODO: move this function definition out of thread.cpp BOOL(WINAPI* QueryThreadCycleTime)(HANDLE ThreadHandle, PULONG64 CycleTime) = nullptr; BOOL WINAPI QueryThreadCycleTimeUnsupported(HANDLE ThreadHandle, PULONG64 CycleTime) { *CycleTime = 0; return TRUE; } void ThreadCreate(CREATE_THREAD_DEBUG_INFO* CreateThread) { THREADINFO curInfo; memset(&curInfo, 0, sizeof(THREADINFO)); curInfo.ThreadNumber = ThreadGetCount(); curInfo.Handle = INVALID_HANDLE_VALUE; curInfo.ThreadId = ((DEBUG_EVENT*)GetDebugData())->dwThreadId; curInfo.ThreadStartAddress = (duint)CreateThread->lpStartAddress; curInfo.ThreadLocalBase = (duint)CreateThread->lpThreadLocalBase; // Duplicate the debug thread handle -> thread handle DuplicateHandle(GetCurrentProcess(), CreateThread->hThread, GetCurrentProcess(), &curInfo.Handle, 0, FALSE, DUPLICATE_SAME_ACCESS); typedef HRESULT(WINAPI * GETTHREADDESCRIPTION)(HANDLE hThread, PWSTR * ppszThreadDescription); static GETTHREADDESCRIPTION _GetThreadDescription = (GETTHREADDESCRIPTION)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"); PWSTR threadDescription = nullptr; // The first thread (#0) is always the main program thread if(curInfo.ThreadNumber <= 0) strncpy_s(curInfo.threadName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Main Thread")), _TRUNCATE); else if(_GetThreadDescription && SUCCEEDED(_GetThreadDescription(curInfo.Handle, &threadDescription)) && threadDescription) { if(threadDescription[0]) strncpy_s(curInfo.threadName, StringUtils::Escape(StringUtils::Utf16ToUtf8(threadDescription)).c_str(), _TRUNCATE); LocalFree(threadDescription); } else curInfo.threadName[0] = 0; // Modify global thread list EXCLUSIVE_ACQUIRE(LockThreads); threadList.emplace(curInfo.ThreadId, curInfo); EXCLUSIVE_RELEASE(); // Notify GUI GuiUpdateThreadView(); } void ThreadExit(DWORD ThreadId) { EXCLUSIVE_ACQUIRE(LockThreads); // Erase element using native functions auto itr = threadList.find(ThreadId); if(itr != threadList.end()) { CloseHandle(itr->second.Handle); threadList.erase(itr); } EXCLUSIVE_RELEASE(); GuiUpdateThreadView(); } void ThreadClear() { EXCLUSIVE_ACQUIRE(LockThreads); // Close all handles first for(auto & itr : threadList) CloseHandle(itr.second.Handle); // Empty the array threadList.clear(); // Update the GUI's list EXCLUSIVE_RELEASE(); GuiUpdateThreadView(); } int ThreadGetCount() { SHARED_ACQUIRE(LockThreads); return (int)threadList.size(); } void ThreadGetList(THREADLIST* List) { ASSERT_NONNULL(List); SHARED_ACQUIRE(LockThreads); // // This function converts a C++ std::unordered_map to a C-style THREADLIST[]. // Also assume BridgeAlloc zeros the returned buffer. // List->count = (int)threadList.size(); if(List->count == 0) { List->list = nullptr; return; } // Allocate C-style array List->list = (THREADALLINFO*)BridgeAlloc(List->count * sizeof(THREADALLINFO)); // Fill out the list data int index = 0; // Unused thread exit time FILETIME threadExitTime; for(auto & itr : threadList) { HANDLE threadHandle = itr.second.Handle; // Get the debugger's active thread index if(threadHandle == hActiveThread) List->CurrentThread = index; memcpy(&List->list[index].BasicInfo, &itr.second, sizeof(THREADINFO)); typedef HRESULT(WINAPI * GETTHREADDESCRIPTION)(HANDLE hThread, PWSTR * ppszThreadDescription); static GETTHREADDESCRIPTION _GetThreadDescription = (GETTHREADDESCRIPTION)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"); PWSTR threadDescription = nullptr; if(_GetThreadDescription && SUCCEEDED(_GetThreadDescription(threadHandle, &threadDescription)) && threadDescription) { // Thread name may have changed if(threadDescription[0]) strncpy_s(List->list[index].BasicInfo.threadName, StringUtils::Escape(StringUtils::Utf16ToUtf8(threadDescription)).c_str(), _TRUNCATE); LocalFree(threadDescription); } List->list[index].ThreadCip = GetContextDataEx(threadHandle, UE_CIP); List->list[index].SuspendCount = ThreadGetSuspendCount(threadHandle); List->list[index].Priority = ThreadGetPriority(threadHandle); List->list[index].LastError = ThreadGetLastErrorTEB(itr.second.ThreadLocalBase); GetThreadTimes(threadHandle, &List->list[index].CreationTime, &threadExitTime, &List->list[index].KernelTime, &List->list[index].UserTime); List->list[index].Cycles = ThreadQueryCycleTime(threadHandle); index++; } // Get the wait reason for every thread in the list for(int i = 0; i < List->count; i++) { auto found = threadWaitReasons.find(List->list[i].BasicInfo.ThreadId); if(found != threadWaitReasons.end()) List->list[i].WaitReason = found->second; } } void ThreadGetList(std::vector<THREADINFO> & list) { SHARED_ACQUIRE(LockThreads); list.clear(); list.reserve(threadList.size()); for(const auto & thread : threadList) list.push_back(thread.second); } bool ThreadGetInfo(DWORD ThreadId, THREADINFO & info) { SHARED_ACQUIRE(LockThreads); auto found = threadList.find(ThreadId); if(found == threadList.end()) return false; info = found->second; return true; } bool ThreadIsValid(DWORD ThreadId) { SHARED_ACQUIRE(LockThreads); return threadList.find(ThreadId) != threadList.end(); } bool ThreadGetTib(duint TEBAddress, NT_TIB* Tib) { // Calculate offset from structure member TEBAddress += offsetof(TEB, NtTib); memset(Tib, 0, sizeof(NT_TIB)); return MemReadUnsafe(TEBAddress, Tib, sizeof(NT_TIB)); } bool ThreadGetTeb(duint TEBAddress, TEB* Teb) { memset(Teb, 0, sizeof(TEB)); return MemReadUnsafe(TEBAddress, Teb, sizeof(TEB)); } int ThreadGetSuspendCount(HANDLE Thread) { // Query the suspend count. This only works on Windows 8.1 and later DWORD suspendCount; if(NT_SUCCESS(NtQueryInformationThread(Thread, ThreadSuspendCount, &suspendCount, sizeof(suspendCount), nullptr))) { return suspendCount; } // // Suspend a thread in order to get the previous suspension count // WARNING: This function is very bad (threads should not be randomly interrupted) // // Use NtSuspendThread, because there is no Win32 error for STATUS_SUSPEND_COUNT_EXCEEDED NTSTATUS status = NtSuspendThread(Thread, &suspendCount); if(status == STATUS_SUSPEND_COUNT_EXCEEDED) suspendCount = MAXCHAR; // If the thread is already at the max suspend count, KeSuspendThread raises an exception and never returns the count else if(!NT_SUCCESS(status)) suspendCount = 0; // Resume the thread's normal execution if(NT_SUCCESS(status)) ResumeThread(Thread); return suspendCount; } THREADPRIORITY ThreadGetPriority(HANDLE Thread) { return (THREADPRIORITY)GetThreadPriority(Thread); } DWORD ThreadGetLastErrorTEB(ULONG_PTR ThreadLocalBase) { // Get the offset for the TEB::LastErrorValue and read it DWORD lastError = 0; duint structOffset = ThreadLocalBase + offsetof(TEB, LastErrorValue); MemReadUnsafe(structOffset, &lastError, sizeof(DWORD)); return lastError; } DWORD ThreadGetLastError(DWORD ThreadId) { SHARED_ACQUIRE(LockThreads); if(threadList.find(ThreadId) != threadList.end()) return ThreadGetLastErrorTEB(threadList[ThreadId].ThreadLocalBase); ASSERT_ALWAYS("Trying to get last error of a thread that doesn't exist!"); return 0; } NTSTATUS ThreadGetLastStatusTEB(ULONG_PTR ThreadLocalBase) { // Get the offset for the TEB::LastStatusValue and read it NTSTATUS lastStatus = 0; duint structOffset = ThreadLocalBase + offsetof(TEB, LastStatusValue); MemReadUnsafe(structOffset, &lastStatus, sizeof(NTSTATUS)); return lastStatus; } NTSTATUS ThreadGetLastStatus(DWORD ThreadId) { SHARED_ACQUIRE(LockThreads); if(threadList.find(ThreadId) != threadList.end()) return ThreadGetLastStatusTEB(threadList[ThreadId].ThreadLocalBase); ASSERT_ALWAYS("Trying to get last status of a thread that doesn't exist!"); return 0; } bool ThreadSetName(DWORD ThreadId, const char* Name) { EXCLUSIVE_ACQUIRE(LockThreads); // Modifies a variable (name), so an exclusive lock is required if(threadList.find(ThreadId) != threadList.end()) { if(!Name) Name = ""; strncpy_s(threadList[ThreadId].threadName, Name, _TRUNCATE); return true; } return false; } /** @brief ThreadGetName Get the name of the thread. @param ThreadId The id of the thread. @param Name The returned name of the thread. Must be at least MAX_THREAD_NAME_SIZE size @return True if the function succeeds. False otherwise. */ bool ThreadGetName(DWORD ThreadId, char* Name) { SHARED_ACQUIRE(LockThreads); if(threadList.find(ThreadId) != threadList.end()) { strncpy_s(Name, MAX_THREAD_NAME_SIZE, threadList[ThreadId].threadName, _TRUNCATE); return true; } return false; } HANDLE ThreadGetHandle(DWORD ThreadId) { SHARED_ACQUIRE(LockThreads); if(threadList.find(ThreadId) != threadList.end()) return threadList[ThreadId].Handle; return nullptr; } DWORD ThreadGetId(HANDLE Thread) { SHARED_ACQUIRE(LockThreads); // Search for the ID in the local list for(auto & entry : threadList) { if(entry.second.Handle == Thread) return entry.first; } // Wasn't found, check with Windows typedef DWORD (WINAPI * GETTHREADID)(HANDLE hThread); static GETTHREADID _GetThreadId = (GETTHREADID)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadId"); return _GetThreadId ? _GetThreadId(Thread) : 0; } int ThreadSuspendAll() { // SuspendThread does not modify any internal variables SHARED_ACQUIRE(LockThreads); int count = 0; for(auto & entry : threadList) { if(SuspendThread(entry.second.Handle) != -1) count++; else dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to suspend thread 0x%X...\n"), entry.second.ThreadId); } return count; } int ThreadResumeAll() { // ResumeThread does not modify any internal variables SHARED_ACQUIRE(LockThreads); int count = 0; for(auto & entry : threadList) { if(ResumeThread(entry.second.Handle) != -1) count++; } return count; } ULONG_PTR ThreadGetLocalBase(DWORD ThreadId) { SHARED_ACQUIRE(LockThreads); auto found = threadList.find(ThreadId); return found != threadList.end() ? found->second.ThreadLocalBase : 0; } ULONG64 ThreadQueryCycleTime(HANDLE hThread) { ULONG64 CycleTime; // Initialize function pointer if(QueryThreadCycleTime == nullptr) { QueryThreadCycleTime = (BOOL(WINAPI*)(HANDLE, PULONG64))GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "QueryThreadCycleTime"); if(QueryThreadCycleTime == nullptr) QueryThreadCycleTime = QueryThreadCycleTimeUnsupported; } if(!QueryThreadCycleTime(hThread, &CycleTime)) CycleTime = 0; return CycleTime; } void ThreadUpdateWaitReasons() { ULONG size; if(NtQuerySystemInformation(SystemProcessInformation, NULL, 0, &size) != STATUS_INFO_LENGTH_MISMATCH) return; Memory<PSYSTEM_PROCESS_INFORMATION> systemProcessInfo(2 * size, "_dbg_threadwaitreason"); NTSTATUS status = NtQuerySystemInformation(SystemProcessInformation, systemProcessInfo(), (ULONG)systemProcessInfo.size(), NULL); if(!NT_SUCCESS(status)) return; PSYSTEM_PROCESS_INFORMATION process = systemProcessInfo(); EXCLUSIVE_ACQUIRE(LockThreads); while(true) { for(ULONG thread = 0; thread < process->NumberOfThreads; ++thread) { auto tid = (DWORD)process->Threads[thread].ClientId.UniqueThread; if(threadList.count(tid)) threadWaitReasons[tid] = (THREADWAITREASON)process->Threads[thread].WaitReason; } if(process->NextEntryOffset == 0) // Last entry break; process = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)process + process->NextEntryOffset); } }
C/C++
x64dbg-development/src/dbg/thread.h
#ifndef _THREAD_H #define _THREAD_H #include "_global.h" #include "ntdll/ntdll.h" void ThreadCreate(CREATE_THREAD_DEBUG_INFO* CreateThread); void ThreadExit(DWORD ThreadId); void ThreadClear(); int ThreadGetCount(); void ThreadGetList(THREADLIST* list); void ThreadGetList(std::vector<THREADINFO> & list); bool ThreadGetInfo(DWORD ThreadId, THREADINFO & info); bool ThreadIsValid(DWORD ThreadId); bool ThreadSetName(DWORD ThreadId, const char* name); bool ThreadGetTib(duint TEBAddress, NT_TIB* Tib); bool ThreadGetTeb(duint TEBAddress, TEB* Teb); int ThreadGetSuspendCount(HANDLE Thread); THREADPRIORITY ThreadGetPriority(HANDLE Thread); DWORD ThreadGetLastErrorTEB(ULONG_PTR ThreadLocalBase); DWORD ThreadGetLastError(DWORD ThreadId); NTSTATUS ThreadGetLastStatusTEB(ULONG_PTR ThreadLocalBase); NTSTATUS ThreadGetLastStatus(DWORD ThreadId); bool ThreadSetName(DWORD dwThreadId, const char* name); bool ThreadGetName(DWORD ThreadId, char* Name); HANDLE ThreadGetHandle(DWORD ThreadId); DWORD ThreadGetId(HANDLE Thread); int ThreadSuspendAll(); int ThreadResumeAll(); ULONG_PTR ThreadGetLocalBase(DWORD ThreadId); ULONG64 ThreadQueryCycleTime(HANDLE hThread); void ThreadUpdateWaitReasons(); #endif // _THREAD_H
C++
x64dbg-development/src/dbg/threading.cpp
#include <ntstatus.h> #include "threading.h" static HANDLE waitArray[WAITID_LAST]; void waitclear() { for(int i = 0; i < WAITID_LAST; i++) unlock((WAIT_ID)i); } void wait(WAIT_ID id) { WaitForSingleObject(waitArray[id], INFINITE); } bool waitfor(WAIT_ID id, unsigned int Milliseconds) { return WaitForSingleObject(waitArray[id], Milliseconds) == 0; } void lock(WAIT_ID id) { ResetEvent(waitArray[id]); } void unlock(WAIT_ID id) { SetEvent(waitArray[id]); } bool waitislocked(WAIT_ID id) { return !WaitForSingleObject(waitArray[id], 0) == WAIT_OBJECT_0; } void waitinitialize() { for(int i = 0; i < WAITID_LAST; i++) waitArray[i] = CreateEventW(NULL, TRUE, TRUE, NULL); } void waitdeinitialize() { for(int i = 0; i < WAITID_LAST; i++) { wait((WAIT_ID)i); CloseHandle(waitArray[i]); } } bool SectionLockerGlobal::m_Initialized = false; bool SectionLockerGlobal::m_SRWLocks = false; CacheAligned<SRWLOCK> SectionLockerGlobal::m_srwLocks[SectionLock::LockLast]; SectionLockerGlobal::owner_info SectionLockerGlobal::m_exclusiveOwner[SectionLock::LockLast]; CacheAligned<CRITICAL_SECTION> SectionLockerGlobal::m_crLocks[SectionLock::LockLast]; SectionLockerGlobal::SRWLOCKFUNCTION SectionLockerGlobal::m_InitializeSRWLock; SectionLockerGlobal::SRWLOCKFUNCTION SectionLockerGlobal::m_AcquireSRWLockShared; SectionLockerGlobal::TRYSRWLOCKFUNCTION SectionLockerGlobal::m_TryAcquireSRWLockShared; SectionLockerGlobal::SRWLOCKFUNCTION SectionLockerGlobal::m_AcquireSRWLockExclusive; SectionLockerGlobal::TRYSRWLOCKFUNCTION SectionLockerGlobal::m_TryAcquireSRWLockExclusive; SectionLockerGlobal::SRWLOCKFUNCTION SectionLockerGlobal::m_ReleaseSRWLockShared; SectionLockerGlobal::SRWLOCKFUNCTION SectionLockerGlobal::m_ReleaseSRWLockExclusive; DWORD SectionLockerGlobal::m_guiMainThreadId; void SectionLockerGlobal::Initialize() { // This is supposed to only be called once, but // create a flag anyway if(m_Initialized) return; // This gets called on the same thread as the GUI m_guiMainThreadId = GetCurrentThreadId(); // Attempt to read the SRWLock API HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll"); m_InitializeSRWLock = (SRWLOCKFUNCTION)GetProcAddress(hKernel32, "InitializeSRWLock"); m_AcquireSRWLockShared = (SRWLOCKFUNCTION)GetProcAddress(hKernel32, "AcquireSRWLockShared"); m_TryAcquireSRWLockShared = (TRYSRWLOCKFUNCTION)GetProcAddress(hKernel32, "TryAcquireSRWLockShared"); m_AcquireSRWLockExclusive = (SRWLOCKFUNCTION)GetProcAddress(hKernel32, "AcquireSRWLockExclusive"); m_TryAcquireSRWLockExclusive = (TRYSRWLOCKFUNCTION)GetProcAddress(hKernel32, "TryAcquireSRWLockExclusive"); m_ReleaseSRWLockShared = (SRWLOCKFUNCTION)GetProcAddress(hKernel32, "ReleaseSRWLockShared"); m_ReleaseSRWLockExclusive = (SRWLOCKFUNCTION)GetProcAddress(hKernel32, "ReleaseSRWLockExclusive"); m_SRWLocks = m_InitializeSRWLock && m_AcquireSRWLockShared && m_TryAcquireSRWLockShared && m_AcquireSRWLockExclusive && m_TryAcquireSRWLockExclusive && m_ReleaseSRWLockShared && m_ReleaseSRWLockExclusive; if(m_SRWLocks) // Prefer SRWLocks { // Destroy previous data if any existed memset(m_srwLocks, 0, sizeof(m_srwLocks)); for(int i = 0; i < ARRAYSIZE(m_srwLocks); i++) m_InitializeSRWLock(&m_srwLocks[i]); } else // Fall back to critical sections otherwise { // Destroy previous data if any existed memset(m_crLocks, 0, sizeof(m_crLocks)); for(int i = 0; i < ARRAYSIZE(m_crLocks); i++) InitializeCriticalSection(&m_crLocks[i]); } m_Initialized = true; } void SectionLockerGlobal::Deinitialize() { if(!m_Initialized) return; if(m_SRWLocks) { for(int i = 0; i < ARRAYSIZE(m_srwLocks); i++) { // Wait for the lock's ownership to be released m_AcquireSRWLockExclusive(&m_srwLocks[i]); m_ReleaseSRWLockExclusive(&m_srwLocks[i]); // Invalidate data memset(&m_srwLocks[i], 0, sizeof(SRWLOCK)); } } else { for(int i = 0; i < ARRAYSIZE(m_crLocks); i++) { // Wait for the lock's ownership to be released EnterCriticalSection(&m_crLocks[i]); LeaveCriticalSection(&m_crLocks[i]); // Delete critical section DeleteCriticalSection(&m_crLocks[i]); memset(&m_crLocks[i], 0, sizeof(CRITICAL_SECTION)); } } m_Initialized = false; }
C/C++
x64dbg-development/src/dbg/threading.h
#ifndef _THREADING_H #define _THREADING_H #include "_global.h" enum WAIT_ID { WAITID_RUN, WAITID_LAST }; //functions void waitclear(); void wait(WAIT_ID id); bool waitfor(WAIT_ID id, unsigned int Milliseconds); void lock(WAIT_ID id); void unlock(WAIT_ID id); bool waitislocked(WAIT_ID id); void waitinitialize(); void waitdeinitialize(); // // THREAD SYNCHRONIZATION // // Win Vista and newer: (Faster) SRW locks used // Win 2003 and older: (Slower) Critical sections used // #define EXCLUSIVE_ACQUIRE(Index) SectionLocker<Index, false> __ThreadLock #define EXCLUSIVE_ACQUIRE_GUI(Index) SectionLocker<Index, false, true> __ThreadLock #define EXCLUSIVE_REACQUIRE() __ThreadLock.Lock() #define EXCLUSIVE_RELEASE() __ThreadLock.Unlock() #define SHARED_ACQUIRE(Index) SectionLocker<Index, true> __SThreadLock #define SHARED_ACQUIRE_GUI(Index) SectionLocker<Index, true, true> __SThreadLock #define SHARED_REACQUIRE() __SThreadLock.Lock() #define SHARED_RELEASE() __SThreadLock.Unlock() enum SectionLock { LockMemoryPages, LockVariables, LockModules, LockComments, LockLabels, LockBookmarks, LockFunctions, LockLoops, LockBreakpoints, LockPatches, LockThreads, LockSym, LockCmdLine, LockDatabase, LockPluginList, LockPluginCallbackList, LockPluginCommandList, LockPluginMenuList, LockPluginExprfunctionList, LockPluginFormatfunctionList, LockSehCache, LockMnemonicHelp, LockTraceRecord, LockCrossReferences, LockDebugStartStop, LockArguments, LockEncodeMaps, LockCallstackCache, LockRunToUserCode, LockWatch, LockExpressionFunctions, LockHistory, LockSymbolCache, LockLineCache, LockTypeManager, LockModuleHashes, LockFormatFunctions, LockDllBreakpoints, LockHandleCache, // Number of elements in this enumeration. Must always be the last index. LockLast }; template<typename T> struct __declspec(align(64)) CacheAligned { T value; T* operator&() { return &value; } }; class SectionLockerGlobal { template<SectionLock LockIndex, bool Shared, bool ProcessGuiEvents> friend class SectionLocker; public: static void Initialize(); static void Deinitialize(); private: template<SectionLock LockIndex, bool Shared, bool ProcessGuiEvents> static void AcquireLock() { auto threadId = GetCurrentThreadId(); if(m_SRWLocks) { auto srwLock = &m_srwLocks[LockIndex]; if(Shared) { if(m_exclusiveOwner[LockIndex].threadId == threadId) return; if(ProcessGuiEvents && threadId == m_guiMainThreadId) { while(!m_TryAcquireSRWLockShared(srwLock)) GuiProcessEvents(); } else { m_AcquireSRWLockShared(srwLock); } return; } if(m_exclusiveOwner[LockIndex].threadId == threadId) { assert(m_exclusiveOwner[LockIndex].count > 0); m_exclusiveOwner[LockIndex].count++; return; } if(ProcessGuiEvents && threadId == m_guiMainThreadId) { while(!m_TryAcquireSRWLockExclusive(srwLock)) GuiProcessEvents(); } else { m_AcquireSRWLockExclusive(srwLock); } assert(m_exclusiveOwner[LockIndex].threadId == 0); assert(m_exclusiveOwner[LockIndex].count == 0); m_exclusiveOwner[LockIndex].threadId = threadId; m_exclusiveOwner[LockIndex].count = 1; } else { auto cr = &m_crLocks[LockIndex]; if(ProcessGuiEvents && threadId == m_guiMainThreadId) { while(!TryEnterCriticalSection(cr)) GuiProcessEvents(); } else { EnterCriticalSection(cr); } } } template<SectionLock LockIndex, bool Shared> static void ReleaseLock() { if(m_SRWLocks) { if(Shared) { if(m_exclusiveOwner[LockIndex].threadId == GetCurrentThreadId()) return; m_ReleaseSRWLockShared(&m_srwLocks[LockIndex]); return; } assert(m_exclusiveOwner[LockIndex].count && m_exclusiveOwner[LockIndex].threadId); m_exclusiveOwner[LockIndex].count--; if(m_exclusiveOwner[LockIndex].count == 0) { m_exclusiveOwner[LockIndex].threadId = 0; m_ReleaseSRWLockExclusive(&m_srwLocks[LockIndex]); } } else { LeaveCriticalSection(&m_crLocks[LockIndex]); } } typedef void (WINAPI* SRWLOCKFUNCTION)(PSRWLOCK SWRLock); typedef BOOLEAN(WINAPI* TRYSRWLOCKFUNCTION)(PSRWLOCK SWRLock); static bool m_Initialized; static bool m_SRWLocks; struct __declspec(align(64)) owner_info { DWORD threadId; size_t count; }; static owner_info m_exclusiveOwner[SectionLock::LockLast]; static CacheAligned<SRWLOCK> m_srwLocks[SectionLock::LockLast]; static CacheAligned<CRITICAL_SECTION> m_crLocks[SectionLock::LockLast]; static SRWLOCKFUNCTION m_InitializeSRWLock; static SRWLOCKFUNCTION m_AcquireSRWLockShared; static TRYSRWLOCKFUNCTION m_TryAcquireSRWLockShared; static SRWLOCKFUNCTION m_AcquireSRWLockExclusive; static TRYSRWLOCKFUNCTION m_TryAcquireSRWLockExclusive; static SRWLOCKFUNCTION m_ReleaseSRWLockShared; static SRWLOCKFUNCTION m_ReleaseSRWLockExclusive; static DWORD m_guiMainThreadId; }; template<SectionLock LockIndex, bool Shared, bool ProcessGuiEvents = false> class SectionLocker { public: SectionLocker() { m_LockCount = 0; Lock(); } ~SectionLocker() { if(m_LockCount > 0) Unlock(); // The lock count should be zero after destruction. assert(m_LockCount == 0); } inline void Lock() { Internal::AcquireLock<LockIndex, Shared, ProcessGuiEvents>(); // We cannot recursively lock more than 255 times. assert(m_LockCount < 255); m_LockCount++; } inline void Unlock() { // Unlocking twice will cause undefined behaviour. assert(m_LockCount != 0); m_LockCount--; Internal::ReleaseLock<LockIndex, Shared>(); } protected: BYTE m_LockCount; private: using Internal = SectionLockerGlobal; }; #endif // _THREADING_H
C++
x64dbg-development/src/dbg/TraceRecord.cpp
#include "TraceRecord.h" #include "module.h" #include "memory.h" #include "threading.h" #include "thread.h" #include "disasm_helper.h" #include "disasm_fast.h" #include "plugin_loader.h" #include "stringformat.h" #include "value.h" #define MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP 512 TraceRecordManager TraceRecord; TraceRecordManager::TraceRecordManager() { ModuleNames.emplace_back(""); } TraceRecordManager::~TraceRecordManager() { clear(); } void TraceRecordManager::clear() { EXCLUSIVE_ACQUIRE(LockTraceRecord); for(auto i = TraceRecord.begin(); i != TraceRecord.end(); ++i) efree(i->second.rawPtr, "TraceRecordManager"); TraceRecord.clear(); ModuleNames.clear(); ModuleNames.emplace_back(""); } bool TraceRecordManager::setTraceRecordType(duint pageAddress, TraceRecordType type) { EXCLUSIVE_ACQUIRE(LockTraceRecord); pageAddress &= ~((duint)4096 - 1); auto pageInfo = TraceRecord.find(ModHashFromAddr(pageAddress)); if(pageInfo == TraceRecord.end()) { if(type != TraceRecordType::TraceRecordNone) { TraceRecordPage newPage; char modName[MAX_MODULE_SIZE]; switch(type) { case TraceRecordBitExec: newPage.rawPtr = emalloc(4096 / 8, "TraceRecordManager"); memset(newPage.rawPtr, 0, 4096 / 8); break; case TraceRecordByteWithExecTypeAndCounter: newPage.rawPtr = emalloc(4096, "TraceRecordManager"); memset(newPage.rawPtr, 0, 4096); break; case TraceRecordWordWithExecTypeAndCounter: newPage.rawPtr = emalloc(4096 * 2, "TraceRecordManager"); memset(newPage.rawPtr, 0, 4096 * 2); break; default: return false; } newPage.dataType = type; if(ModNameFromAddr(pageAddress, modName, true)) { newPage.rva = pageAddress - ModBaseFromAddr(pageAddress); newPage.moduleIndex = getModuleIndex(std::string(modName)); } else { newPage.rva = pageAddress; newPage.moduleIndex = ~0; } auto inserted = TraceRecord.insert(std::make_pair(ModHashFromAddr(pageAddress), newPage)); if(inserted.second == false) // we failed to insert new page into the map { efree(newPage.rawPtr); return false; } return true; } else return true; } else { if(type == TraceRecordType::TraceRecordNone) { if(pageInfo != TraceRecord.end()) { efree(pageInfo->second.rawPtr, "TraceRecordManager"); TraceRecord.erase(pageInfo); } return true; } else return pageInfo->second.dataType == type; //Can't covert between data types } } TraceRecordManager::TraceRecordType TraceRecordManager::getTraceRecordType(duint pageAddress) { SHARED_ACQUIRE(LockTraceRecord); pageAddress &= ~((duint)4096 - 1); auto pageInfo = TraceRecord.find(ModHashFromAddr(pageAddress)); if(pageInfo == TraceRecord.end()) return TraceRecordNone; else return pageInfo->second.dataType; } void TraceRecordManager::TraceExecute(duint address, duint size) { SHARED_ACQUIRE(LockTraceRecord); if(size == 0) return; duint base = address & ~((duint)4096 - 1); auto pageInfoIterator = TraceRecord.find(ModHashFromAddr(base)); if(pageInfoIterator == TraceRecord.end()) return; TraceRecordPage pageInfo; pageInfo = pageInfoIterator->second; duint offset = address - base; bool isMixed; if((offset + size) > 4096) // execution crossed page boundary, splitting into 2 sub calls. Noting that byte type may be mislabelled. { SHARED_RELEASE(); TraceExecute(address, 4096 - offset); TraceExecute(base + 4096, size + offset - 4096); return; } isMixed = false; switch(pageInfo.dataType) { case TraceRecordType::TraceRecordBitExec: for(unsigned char i = 0; i < size; i++) *((char*)pageInfo.rawPtr + (i + offset) / 8) |= 1 << ((i + offset) % 8); break; case TraceRecordType::TraceRecordByteWithExecTypeAndCounter: for(unsigned char i = 0; i < size; i++) { TraceRecordByteType_2bit currentByteType; if(isMixed) currentByteType = TraceRecordByteType_2bit::_InstructionOverlapped; else if(i == 0) currentByteType = TraceRecordByteType_2bit::_InstructionHeading; else if(i == size - 1) currentByteType = TraceRecordByteType_2bit::_InstructionTailing; else currentByteType = TraceRecordByteType_2bit::_InstructionBody; char* data = (char*)pageInfo.rawPtr + offset + i; if(*data == 0) { *data = (char)currentByteType << 6 | 1; } else { isMixed |= (*data & 0xC0) >> 6 == currentByteType; *data = ((char)currentByteType << 6) | ((*data & 0x3F) == 0x3F ? 0x3F : (*data & 0x3F) + 1); } } if(isMixed) for(unsigned char i = 0; i < size; i++) *((char*)pageInfo.rawPtr + i + offset) |= 0xC0; break; case TraceRecordType::TraceRecordWordWithExecTypeAndCounter: for(unsigned char i = 0; i < size; i++) { TraceRecordByteType_2bit currentByteType; if(isMixed) currentByteType = TraceRecordByteType_2bit::_InstructionOverlapped; else if(i == 0) currentByteType = TraceRecordByteType_2bit::_InstructionHeading; else if(i == size - 1) currentByteType = TraceRecordByteType_2bit::_InstructionTailing; else currentByteType = TraceRecordByteType_2bit::_InstructionBody; short* data = (short*)pageInfo.rawPtr + offset + i; if(*data == 0) { *data = (char)currentByteType << 14 | 1; } else { isMixed |= (*data & 0xC0) >> 6 == currentByteType; *data = ((char)currentByteType << 14) | ((*data & 0x3FFF) == 0x3FFF ? 0x3FFF : (*data & 0x3FFF) + 1); } } if(isMixed) for(unsigned char i = 0; i < size; i++) *((short*)pageInfo.rawPtr + i + offset) |= 0xC000; break; default: break; } } //See https://www.felixcloutier.com/x86/FXSAVE.html, max 512 bytes #define memoryContentSize 512 static void HandleZydisOperand(const Zydis & cp, int opindex, DISASM_ARGTYPE* argType, duint* value, unsigned char memoryContent[memoryContentSize], unsigned char* memorySize) { *value = cp.ResolveOpValue(opindex, [&cp](ZydisRegister reg) { auto regName = cp.RegName(reg); return regName ? getregister(nullptr, regName) : 0; //TODO: temporary needs enums + caching }); const auto & op = cp[opindex]; switch(op.type) { case ZYDIS_OPERAND_TYPE_REGISTER: *argType = arg_normal; break; case ZYDIS_OPERAND_TYPE_IMMEDIATE: *argType = arg_normal; break; case ZYDIS_OPERAND_TYPE_POINTER: *argType = arg_normal; break; case ZYDIS_OPERAND_TYPE_MEMORY: { *argType = arg_memory; const auto & mem = op.mem; if(mem.segment == ArchValue(ZYDIS_REGISTER_FS, ZYDIS_REGISTER_GS)) { *value += ThreadGetLocalBase(ThreadGetId(hActiveThread)); } *memorySize = op.size / 8; if(*memorySize <= memoryContentSize && DbgMemIsValidReadPtr(*value)) { MemRead(*value, memoryContent, max(op.size / 8, sizeof(duint))); } } break; default: __debugbreak(); } } void TraceRecordManager::TraceExecuteRecord(const Zydis & newInstruction) { if(!isTraceRecordingEnabled()) return; unsigned char WriteBuffer[3072]; unsigned char* WriteBufferPtr = WriteBuffer; //Get current data REGDUMPWORD newContext; //DISASM_INSTR newInstruction; DWORD newThreadId; const size_t memoryArrayCount = 32; duint newMemory[memoryArrayCount]; duint newMemoryAddress[memoryArrayCount]; duint oldMemory[memoryArrayCount]; unsigned char newMemoryArrayCount = 0; DbgGetRegDumpEx(&newContext.registers, sizeof(REGDUMP)); newThreadId = ThreadGetId(hActiveThread); // Don't try to resolve memory values for invalid/lea/nop instructions if(newInstruction.Success() && !newInstruction.IsNop() && newInstruction.GetId() != ZYDIS_MNEMONIC_LEA) { // This can happen when trace execute instruction is used, we need to fix that or something would go wrong with the GUI. newContext.registers.regcontext.cip = newInstruction.Address(); DISASM_ARGTYPE argType; duint value; unsigned char memoryContent[memoryContentSize]; unsigned char memorySize; for(int i = 0; i < newInstruction.OpCount(); i++) { memset(memoryContent, 0, sizeof(memoryContent)); HandleZydisOperand(newInstruction, i, &argType, &value, memoryContent, &memorySize); // check for overflow of the memory buffer if(newMemoryArrayCount * sizeof(duint) + memorySize > memoryArrayCount * sizeof(duint)) continue; // TODO: Implicit memory access by push and pop instructions // TODO: Support memory value of ??? for invalid memory access if(argType == arg_memory) { if(memorySize <= sizeof(duint)) { memcpy(&newMemory[newMemoryArrayCount], memoryContent, sizeof(duint)); newMemoryAddress[newMemoryArrayCount] = value; newMemoryArrayCount++; } else for(unsigned char index = 0; index < memorySize / sizeof(duint) + ((memorySize % sizeof(duint)) > 0 ? 1 : 0); index++) { memcpy(&newMemory[newMemoryArrayCount], memoryContent + sizeof(duint) * index, sizeof(duint)); newMemoryAddress[newMemoryArrayCount] = value + sizeof(duint) * index; newMemoryArrayCount++; } } } if(newInstruction.GetId() == ZYDIS_MNEMONIC_PUSH || newInstruction.GetId() == ZYDIS_MNEMONIC_PUSHF || newInstruction.GetId() == ZYDIS_MNEMONIC_PUSHFD || newInstruction.GetId() == ZYDIS_MNEMONIC_PUSHFQ || newInstruction.GetId() == ZYDIS_MNEMONIC_CALL //TODO: far call accesses 2 stack entries ) { MemRead(newContext.registers.regcontext.csp - sizeof(duint), &newMemory[newMemoryArrayCount], sizeof(duint)); newMemoryAddress[newMemoryArrayCount] = newContext.registers.regcontext.csp - sizeof(duint); newMemoryArrayCount++; } else if(newInstruction.GetId() == ZYDIS_MNEMONIC_POP || newInstruction.GetId() == ZYDIS_MNEMONIC_POPF || newInstruction.GetId() == ZYDIS_MNEMONIC_POPFD || newInstruction.GetId() == ZYDIS_MNEMONIC_POPFQ || newInstruction.GetId() == ZYDIS_MNEMONIC_RET) { MemRead(newContext.registers.regcontext.csp, &newMemory[newMemoryArrayCount], sizeof(duint)); newMemoryAddress[newMemoryArrayCount] = newContext.registers.regcontext.csp; newMemoryArrayCount++; } //TODO: PUSHAD/POPAD assert(newMemoryArrayCount < memoryArrayCount); } if(rtPrevInstAvailable) { for(unsigned char i = 0; i < rtOldMemoryArrayCount; i++) { MemRead(rtOldMemoryAddress[i], oldMemory + i, sizeof(duint)); } //Delta compress registers //Data layout is Structure of Arrays to gather the same type of data in continuous memory to improve RLE compression performance. //1byte:block type,1byte:reg changed count,1byte:memory accessed count,1byte:flags,4byte/none:threadid,string:opcode,1byte[]:position,ptrbyte[]:regvalue,1byte[]:flags,ptrbyte[]:address,ptrbyte[]:oldmem,ptrbyte[]:newmem //Always record state of LAST INSTRUCTION! (NOT current instruction) unsigned char changed = 0; for(unsigned char i = 0; i < _countof(rtOldContext.regword); i++) { //rtRecordedInstructions - 1 hack: always record full registers dump at first instruction (recorded at 2nd instruction execution time) //prints ASCII table in run trace at first instruction :) if(rtOldContext.regword[i] != newContext.regword[i] || rtOldContextChanged[i] || ((rtRecordedInstructions - 1) % MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP == 0)) changed++; } unsigned char blockFlags = 0; if(newThreadId != rtOldThreadId || ((rtRecordedInstructions - 1) % MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP == 0)) blockFlags = 0x80; blockFlags |= rtOldOpcodeSize; WriteBufferPtr[0] = 0; //1byte: block type WriteBufferPtr[1] = changed; //1byte: registers changed WriteBufferPtr[2] = rtOldMemoryArrayCount; //1byte: memory accesses count WriteBufferPtr[3] = blockFlags; //1byte: flags and opcode size WriteBufferPtr += 4; if(newThreadId != rtOldThreadId || rtNeedThreadId || ((rtRecordedInstructions - 1) % MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP == 0)) { memcpy(WriteBufferPtr, &rtOldThreadId, sizeof(rtOldThreadId)); WriteBufferPtr += sizeof(rtOldThreadId); rtNeedThreadId = (newThreadId != rtOldThreadId); } memcpy(WriteBufferPtr, rtOldOpcode, rtOldOpcodeSize); WriteBufferPtr += rtOldOpcodeSize; int lastChangedPosition = -1; //-1 for(int i = 0; i < _countof(rtOldContext.regword); i++) //1byte: position { if(rtOldContext.regword[i] != newContext.regword[i] || rtOldContextChanged[i] || ((rtRecordedInstructions - 1) % MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP == 0)) { WriteBufferPtr[0] = (unsigned char)(i - lastChangedPosition - 1); WriteBufferPtr++; lastChangedPosition = i; } } for(unsigned char i = 0; i < _countof(rtOldContext.regword); i++) //ptrbyte: newvalue { if(rtOldContext.regword[i] != newContext.regword[i] || rtOldContextChanged[i] || ((rtRecordedInstructions - 1) % MAX_INSTRUCTIONS_TRACED_FULL_REG_DUMP == 0)) { memcpy(WriteBufferPtr, &rtOldContext.regword[i], sizeof(duint)); WriteBufferPtr += sizeof(duint); } rtOldContextChanged[i] = (rtOldContext.regword[i] != newContext.regword[i]); } for(unsigned char i = 0; i < rtOldMemoryArrayCount; i++) //1byte: flags { unsigned char memoryOperandFlags = 0; if(rtOldMemory[i] == oldMemory[i]) //bit 0: memory is unchanged, no new memory is saved memoryOperandFlags |= 1; //proposed flags: is memory valid, is memory zero WriteBufferPtr[0] = memoryOperandFlags; WriteBufferPtr += 1; } for(unsigned char i = 0; i < rtOldMemoryArrayCount; i++) //ptrbyte: address { memcpy(WriteBufferPtr, &rtOldMemoryAddress[i], sizeof(duint)); WriteBufferPtr += sizeof(duint); } for(unsigned char i = 0; i < rtOldMemoryArrayCount; i++) //ptrbyte: old content { memcpy(WriteBufferPtr, &rtOldMemory[i], sizeof(duint)); WriteBufferPtr += sizeof(duint); } for(unsigned char i = 0; i < rtOldMemoryArrayCount; i++) //ptrbyte: new content { if(rtOldMemory[i] != oldMemory[i]) { memcpy(WriteBufferPtr, &oldMemory[i], sizeof(duint)); WriteBufferPtr += sizeof(duint); } } } //Switch context buffers rtOldThreadId = newThreadId; rtOldContext = newContext; rtOldMemoryArrayCount = newMemoryArrayCount; memcpy(rtOldMemory, newMemory, sizeof(newMemory)); memcpy(rtOldMemoryAddress, newMemoryAddress, sizeof(newMemoryAddress)); memset(rtOldOpcode, 0, 16); rtOldOpcodeSize = newInstruction.Size() & 0x0F; MemRead(newContext.registers.regcontext.cip, rtOldOpcode, rtOldOpcodeSize); //Write to file if(rtPrevInstAvailable) { if(WriteBufferPtr - WriteBuffer <= sizeof(WriteBuffer)) { DWORD written; WriteFile(rtFile, WriteBuffer, (DWORD)(WriteBufferPtr - WriteBuffer), &written, NULL); if(written < DWORD(WriteBufferPtr - WriteBuffer)) //Disk full? { CloseHandle(rtFile); String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "Trace recording has stopped unexpectedly because WriteFile() failed. GetLastError() = %s.\r\n"), error.c_str()); rtEnabled = false; } } else __debugbreak(); // Buffer overrun? } rtPrevInstAvailable = true; rtRecordedInstructions++; dbgtracebrowserneedsupdate(); } unsigned int TraceRecordManager::getHitCount(duint address) { SHARED_ACQUIRE(LockTraceRecord); duint base = address & ~((duint)4096 - 1); auto pageInfoIterator = TraceRecord.find(ModHashFromAddr(base)); if(pageInfoIterator == TraceRecord.end()) return 0; else { TraceRecordPage pageInfo = pageInfoIterator->second; duint offset = address - base; switch(pageInfo.dataType) { case TraceRecordType::TraceRecordBitExec: return ((char*)pageInfo.rawPtr)[offset / 8] & (1 << (offset % 8)) ? 1 : 0; case TraceRecordType::TraceRecordByteWithExecTypeAndCounter: return ((char*)pageInfo.rawPtr)[offset] & 0x3F; case TraceRecordType::TraceRecordWordWithExecTypeAndCounter: return ((short*)pageInfo.rawPtr)[offset] & 0x3FFF; default: return 0; } } } TraceRecordManager::TraceRecordByteType TraceRecordManager::getByteType(duint address) { SHARED_ACQUIRE(LockTraceRecord); duint base = address & ~((duint)4096 - 1); auto pageInfoIterator = TraceRecord.find(ModHashFromAddr(base)); if(pageInfoIterator == TraceRecord.end()) return TraceRecordByteType::InstructionHeading; else { TraceRecordPage pageInfo = pageInfoIterator->second; duint offset = address - base; switch(pageInfo.dataType) { case TraceRecordType::TraceRecordBitExec: default: return TraceRecordByteType::InstructionHeading; case TraceRecordType::TraceRecordByteWithExecTypeAndCounter: return (TraceRecordByteType)((((char*)pageInfo.rawPtr)[offset] & 0xC0) >> 6); case TraceRecordType::TraceRecordWordWithExecTypeAndCounter: return (TraceRecordByteType)((((short*)pageInfo.rawPtr)[offset] & 0xC000) >> 14); } } } void TraceRecordManager::increaseInstructionCounter() { InterlockedIncrement((volatile long*)&instructionCounter); } bool TraceRecordManager::enableTraceRecording(bool enabled, const char* fileName) { if(enabled) { if(rtEnabled) enableTraceRecording(false, NULL); //re-enable run trace if(!DbgIsDebugging()) return false; rtFile = CreateFileW(StringUtils::Utf8ToUtf16(fileName).c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(rtFile != INVALID_HANDLE_VALUE) { LARGE_INTEGER size; if(GetFileSizeEx(rtFile, &size)) { if(size.QuadPart != 0) { SetFilePointer(rtFile, 0, 0, FILE_END); } else //file is empty, write some file header { //TRAC, SIZE, JSON header json_t* root = json_object(); json_object_set_new(root, "ver", json_integer(1)); json_object_set_new(root, "arch", json_string(ArchValue("x86", "x64"))); json_object_set_new(root, "hashAlgorithm", json_string("murmurhash")); json_object_set_new(root, "hash", json_hex(dbgfunctionsget()->DbGetHash())); json_object_set_new(root, "compression", json_string("")); char path[MAX_PATH]; ModPathFromAddr(dbgdebuggedbase(), path, MAX_PATH); json_object_set_new(root, "path", json_string(path)); char* headerinfo; headerinfo = json_dumps(root, JSON_COMPACT); size_t headerinfosize = strlen(headerinfo); LARGE_INTEGER header; DWORD written; header.LowPart = MAKEFOURCC('T', 'R', 'A', 'C'); header.HighPart = (LONG)headerinfosize; WriteFile(rtFile, &header, 8, &written, nullptr); if(written < 8) //read-only? { CloseHandle(rtFile); json_free(headerinfo); json_decref(root); dputs(QT_TRANSLATE_NOOP("DBG", "Trace recording failed to start because the file header cannot be written.")); return false; } WriteFile(rtFile, headerinfo, (DWORD)headerinfosize, &written, nullptr); json_free(headerinfo); json_decref(root); if(written < headerinfosize) //disk-full? { CloseHandle(rtFile); dputs(QT_TRANSLATE_NOOP("DBG", "Trace recording failed to start because the file header cannot be written.")); return false; } } } rtPrevInstAvailable = false; rtEnabled = true; rtRecordedInstructions = 0; rtNeedThreadId = true; for(size_t i = 0; i < _countof(rtOldContextChanged); i++) rtOldContextChanged[i] = true; dprintf(QT_TRANSLATE_NOOP("DBG", "Started trace recording to file: %s\r\n"), fileName); Zydis cp; unsigned char instr[MAX_DISASM_BUFFER]; auto cip = GetContextDataEx(hActiveThread, UE_CIP); if(MemRead(cip, instr, MAX_DISASM_BUFFER)) { cp.DisassembleSafe(cip, instr, MAX_DISASM_BUFFER); TraceExecuteRecord(cp); } GuiOpenTraceFile(fileName); return true; } else { String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "Cannot create trace recording file. GetLastError() = %s.\r\n"), error.c_str()); return false; } } else { if(rtEnabled) { CloseHandle(rtFile); rtPrevInstAvailable = false; rtEnabled = false; dputs(QT_TRANSLATE_NOOP("DBG", "Trace recording stopped.")); } return true; } } void TraceRecordManager::saveToDb(JSON root) { EXCLUSIVE_ACQUIRE(LockTraceRecord); const JSON jsonTraceRecords = json_array(); const char* byteToHex = "0123456789ABCDEF"; for(auto i : TraceRecord) { JSON jsonObj = json_object(); if(i.second.moduleIndex != ~0) { json_object_set_new(jsonObj, "module", json_string(ModuleNames[i.second.moduleIndex].c_str())); json_object_set_new(jsonObj, "rva", json_hex(i.second.rva)); } else { json_object_set_new(jsonObj, "module", json_string("")); json_object_set_new(jsonObj, "rva", json_hex(i.first)); } json_object_set_new(jsonObj, "type", json_hex((duint)i.second.dataType)); auto ptr = (unsigned char*)i.second.rawPtr; duint size = 0; switch(i.second.dataType) { case TraceRecordType::TraceRecordBitExec: size = 4096 / 8; break; case TraceRecordType::TraceRecordByteWithExecTypeAndCounter: size = 4096; break; case TraceRecordType::TraceRecordWordWithExecTypeAndCounter: size = 4096 * 2; break; default: __debugbreak(); // We have encountered an error condition. } auto hex = StringUtils::ToCompressedHex(ptr, size); json_object_set_new(jsonObj, "data", json_string(hex.c_str())); json_array_append_new(jsonTraceRecords, jsonObj); } if(json_array_size(jsonTraceRecords)) json_object_set(root, "tracerecord", jsonTraceRecords); // Notify garbage collector json_decref(jsonTraceRecords); } void TraceRecordManager::loadFromDb(JSON root) { EXCLUSIVE_ACQUIRE(LockTraceRecord); // get the root object const JSON tracerecord = json_object_get(root, "tracerecord"); // return if nothing found if(!tracerecord) return; size_t i; JSON value; json_array_foreach(tracerecord, i, value) { TraceRecordPage currentPage; size_t size; currentPage.dataType = (TraceRecordType)json_hex_value(json_object_get(value, "type")); currentPage.rva = (duint)json_hex_value(json_object_get(value, "rva")); switch(currentPage.dataType) { case TraceRecordType::TraceRecordBitExec: size = 4096 / 8; break; case TraceRecordType::TraceRecordByteWithExecTypeAndCounter: size = 4096; break; case TraceRecordType::TraceRecordWordWithExecTypeAndCounter: size = 4096 * 2; break; default: size = 0; break; } if(size != 0) { currentPage.rawPtr = emalloc(size, "TraceRecordManager"); const char* p = json_string_value(json_object_get(value, "data")); std::vector<unsigned char> data; if(StringUtils::FromCompressedHex(p, data) && data.size() == size) { memcpy(currentPage.rawPtr, data.data(), size); const char* moduleName = json_string_value(json_object_get(value, "module")); duint key; if(*moduleName) { currentPage.moduleIndex = getModuleIndex(std::string(moduleName)); key = currentPage.rva + ModHashFromName(moduleName); } else { currentPage.moduleIndex = ~0; key = currentPage.rva; } TraceRecord.insert(std::make_pair(key, currentPage)); } else efree(currentPage.rawPtr, "TraceRecordManager"); } } } unsigned int TraceRecordManager::getModuleIndex(const String & moduleName) { auto iterator = std::find(ModuleNames.begin(), ModuleNames.end(), moduleName); if(iterator != ModuleNames.end()) return (unsigned int)(iterator - ModuleNames.begin()); else { ModuleNames.push_back(moduleName); return (unsigned int)(ModuleNames.size() - 1); } } bool TraceRecordManager::isTraceRecordingEnabled() { return rtEnabled; } void dbgtraceexecute(duint CIP) { if(TraceRecord.getTraceRecordType(CIP) != TraceRecordManager::TraceRecordType::TraceRecordNone) { Zydis instruction; unsigned char data[MAX_DISASM_BUFFER]; if(MemRead(CIP, data, MAX_DISASM_BUFFER)) { instruction.DisassembleSafe(CIP, data, MAX_DISASM_BUFFER); if(TraceRecord.isTraceRecordingEnabled()) { TraceRecord.TraceExecute(CIP, instruction.Size()); TraceRecord.TraceExecuteRecord(instruction); } else { TraceRecord.TraceExecute(CIP, instruction.Size()); } } } else { if(TraceRecord.isTraceRecordingEnabled()) { Zydis instruction; unsigned char data[MAX_DISASM_BUFFER]; if(MemRead(CIP, data, MAX_DISASM_BUFFER)) { instruction.DisassembleSafe(CIP, data, MAX_DISASM_BUFFER); TraceRecord.TraceExecuteRecord(instruction); } } } TraceRecord.increaseInstructionCounter(); }
C/C++
x64dbg-development/src/dbg/TraceRecord.h
#ifndef TRACERECORD_H #define TRACERECORD_H #include "_global.h" #include "_dbgfunctions.h" #include "debugger.h" #include "jansson/jansson_x64dbg.h" #include <zydis_wrapper.h> class TraceRecordManager { public: enum TraceRecordByteType { InstructionBody = 0, InstructionHeading = 1, InstructionTailing = 2, InstructionOverlapped = 3, // The byte was executed with differing instruction base addresses DataByte, // This and the following is not implemented yet. DataWord, DataDWord, DataQWord, DataFloat, DataDouble, DataLongDouble, DataXMM, DataYMM, DataMMX, DataMixed, //the byte is accessed in multiple ways InstructionDataMixed //the byte is both executed and written }; /*************************************************************** * Trace record data layout * TraceRecordNonoe: disable trace record * TraceRecordBitExec: single-bit, executed. * TraceRecordByteWithExecTypeAndCounter: 8-bit, YYXXXXXX YY:=TraceRecordByteType_2bit, XXXXXX:=Hit count(6bit) * TraceRecordWordWithExecTypeAndCounter: 16-bit, YYXXXXXX XXXXXXXX YY:=TraceRecordByteType_2bit, XX:=Hit count(14bit) * Other: reserved for future expanding **************************************************************/ enum TraceRecordType { TraceRecordNone, TraceRecordBitExec, TraceRecordByteWithExecTypeAndCounter, TraceRecordWordWithExecTypeAndCounter }; TraceRecordManager(); ~TraceRecordManager(); void clear(); bool setTraceRecordType(duint pageAddress, TraceRecordType type); TraceRecordType getTraceRecordType(duint pageAddress); void TraceExecute(duint address, duint size); //void TraceAccess(duint address, unsigned char size, TraceRecordByteType accessType); void TraceExecuteRecord(const Zydis & newInstruction); unsigned int getHitCount(duint address); TraceRecordByteType getByteType(duint address); void increaseInstructionCounter(); bool isTraceRecordingEnabled(); bool enableTraceRecording(bool enabled, const char* fileName); void saveToDb(JSON root); void loadFromDb(JSON root); private: enum TraceRecordByteType_2bit { _InstructionBody = 0, _InstructionHeading = 1, _InstructionTailing = 2, _InstructionOverlapped = 3 }; struct TraceRecordPage { void* rawPtr; duint rva; TraceRecordType dataType; unsigned int moduleIndex; }; typedef union _REGDUMPWORD { REGDUMP registers; // 172 qwords on x64, 216 dwords on x86. Almost no space left for AVX512 // strip off lastStatus and 128 bytes of lastError.name member. duint regword[(FIELD_OFFSET(REGDUMP, lastError) + sizeof(DWORD)) / sizeof(duint)]; } REGDUMPWORD; //Key := page base, value := trace record raw data std::unordered_map<duint, TraceRecordPage> TraceRecord; std::vector<std::string> ModuleNames; unsigned int getModuleIndex(const String & moduleName); unsigned int instructionCounter = 0; bool rtEnabled = false; bool rtPrevInstAvailable = false; HANDLE rtFile = nullptr; REGDUMPWORD rtOldContext; bool rtOldContextChanged[(FIELD_OFFSET(REGDUMP, lastError) + sizeof(DWORD)) / sizeof(duint)]; DWORD rtOldThreadId; bool rtNeedThreadId; duint rtOldMemory[32]; duint rtOldMemoryAddress[32]; char rtOldOpcode[16]; unsigned int rtRecordedInstructions; unsigned char rtOldOpcodeSize; unsigned char rtOldMemoryArrayCount; }; extern TraceRecordManager TraceRecord; void dbgtraceexecute(duint CIP); #endif // TRACERECORD_H
C++
x64dbg-development/src/dbg/types.cpp
#include "types.h" #include "stringutils.h" #include "threading.h" #include "filehelper.h" #include "console.h" #include "jansson/jansson_x64dbg.h" #include <algorithm> using namespace Types; static TypeManager typeManager; TypeManager::TypeManager() { auto p = [this](const std::string & n, Primitive p, int size) { primitivesizes[p] = size; auto splits = StringUtils::Split(n, ','); for(const auto & split : splits) addType("", p, split); }; p("int8_t,int8,char,byte,bool,signed char", Int8, sizeof(char)); p("uint8_t,uint8,uchar,unsigned char,ubyte", Uint8, sizeof(unsigned char)); p("int16_t,int16,wchar_t,char16_t,short", Int16, sizeof(short)); p("uint16_t,uint16,ushort,unsigned short", Int16, sizeof(unsigned short)); p("int32_t,int32,int,long", Int32, sizeof(int)); p("uint32_t,uint32,unsigned int,unsigned long", Uint32, sizeof(unsigned int)); p("int64_t,int64,long long", Int64, sizeof(long long)); p("uint64_t,uint64,unsigned long long", Uint64, sizeof(unsigned long long)); p("dsint", Dsint, sizeof(void*)); p("duint,size_t", Duint, sizeof(void*)); p("float", Float, sizeof(float)); p("double", Double, sizeof(double)); p("ptr,void*", Pointer, sizeof(void*)); p("char*,const char*", PtrString, sizeof(char*)); p("wchar_t*,const wchar_t*", PtrWString, sizeof(wchar_t*)); } bool TypeManager::AddType(const std::string & owner, const std::string & type, const std::string & name) { if(owner.empty()) return false; validPtr(type); auto found = types.find(type); if(found == types.end()) return false; return addType(owner, found->second.primitive, name); } bool TypeManager::AddStruct(const std::string & owner, const std::string & name) { StructUnion s; s.name = name; s.owner = owner; return addStructUnion(s); } bool TypeManager::AddUnion(const std::string & owner, const std::string & name) { StructUnion u; u.owner = owner; u.name = name; u.isunion = true; return addStructUnion(u); } bool TypeManager::AddMember(const std::string & parent, const std::string & type, const std::string & name, int arrsize, int offset) { if(!isDefined(type) && !validPtr(type)) return false; auto found = structs.find(parent); if(arrsize < 0 || found == structs.end() || !isDefined(type) || name.empty() || type.empty() || type == parent) return false; auto & s = found->second; for(const auto & member : s.members) if(member.name == name) return false; auto typeSize = Sizeof(type); if(arrsize) typeSize *= arrsize; Member m; m.name = name; m.arrsize = arrsize; m.type = type; m.offset = offset; if(offset >= 0) //user-defined offset { if(offset < s.size) return false; if(offset > s.size) { Member pad; pad.type = "char"; pad.arrsize = offset - s.size; char padname[32] = ""; sprintf_s(padname, "padding%d", pad.arrsize); pad.name = padname; s.members.push_back(pad); s.size += pad.arrsize; } } s.members.push_back(m); if(s.isunion) { if(typeSize > s.size) s.size = typeSize; } else { s.size += typeSize; } return true; } bool TypeManager::AppendMember(const std::string & type, const std::string & name, int arrsize, int offset) { return AddMember(laststruct, type, name, arrsize, offset); } bool TypeManager::AddFunction(const std::string & owner, const std::string & name, const std::string & rettype, CallingConvention callconv, bool noreturn) { auto found = functions.find(name); if(found != functions.end() || name.empty() || owner.empty()) return false; lastfunction = name; Function f; f.owner = owner; f.name = name; if(rettype != "void" && !isDefined(rettype) && !validPtr(rettype)) return false; f.rettype = rettype; f.callconv = callconv; f.noreturn = noreturn; functions.insert({f.name, f}); return true; } bool TypeManager::AddArg(const std::string & function, const std::string & type, const std::string & name) { if(!isDefined(type) && !validPtr(type)) return false; auto found = functions.find(function); if(found == functions.end() || function.empty() || name.empty() || !isDefined(type)) return false; lastfunction = function; Member arg; arg.name = name; arg.type = type; found->second.args.push_back(arg); return true; } bool TypeManager::AppendArg(const std::string & type, const std::string & name) { return AddArg(lastfunction, type, name); } int TypeManager::Sizeof(const std::string & type) const { auto foundT = types.find(type); if(foundT != types.end()) return foundT->second.size; auto foundS = structs.find(type); if(foundS != structs.end()) return foundS->second.size; auto foundF = functions.find(type); if(foundF != functions.end()) { const auto foundP = primitivesizes.find(Pointer); if(foundP != primitivesizes.end()) return foundP->second; return sizeof(void*); } return 0; } bool TypeManager::Visit(const std::string & type, const std::string & name, Visitor & visitor) const { Member m; m.name = name; m.type = type; return visitMember(m, visitor); } template<typename K, typename V> static void filterOwnerMap(std::unordered_map<K, V> & map, const std::string & owner) { for(auto i = map.begin(); i != map.end();) { auto j = i++; if(j->second.owner.empty()) continue; if(owner.empty() || j->second.owner == owner) map.erase(j); } } void TypeManager::Clear(const std::string & owner) { laststruct.clear(); lastfunction.clear(); filterOwnerMap(types, owner); filterOwnerMap(structs, owner); filterOwnerMap(functions, owner); } template<typename K, typename V> static bool removeType(std::unordered_map<K, V> & map, const std::string & type) { auto found = map.find(type); if(found == map.end()) return false; if(found->second.owner.empty()) return false; map.erase(found); return true; } bool TypeManager::RemoveType(const std::string & type) { return removeType(types, type) || removeType(structs, type) || removeType(functions, type); } static std::string getKind(const StructUnion & su) { return su.isunion ? "union" : "struct"; } static std::string getKind(const Type & t) { return "typedef"; } static std::string getKind(const Function & f) { return "function"; } template<typename K, typename V> static void enumType(const std::unordered_map<K, V> & map, std::vector<TypeManager::Summary> & types) { for(auto i = map.begin(); i != map.end(); ++i) { TypeManager::Summary s; s.kind = getKind(i->second); s.name = i->second.name; s.owner = i->second.owner; s.size = SizeofType(s.name); types.push_back(s); } } void TypeManager::Enum(std::vector<Summary> & typeList) const { typeList.clear(); enumType(types, typeList); enumType(structs, typeList); enumType(functions, typeList); //nasty hacks to sort in a nice way std::sort(typeList.begin(), typeList.end(), [](const Summary & a, const Summary & b) { auto kindInt = [](const std::string & kind) { if(kind == "typedef") return 0; if(kind == "struct") return 1; if(kind == "union") return 2; if(kind == "function") return 3; __debugbreak(); return 4; }; if(a.owner < b.owner) return true; else if(a.owner > b.owner) return false; auto ka = kindInt(a.kind), kb = kindInt(b.kind); if(ka < kb) return true; else if(ka > kb) return false; if(a.name < b.name) return true; else if(a.name > b.name) return false; return a.size < b.size; }); } std::string Types::TypeManager::StructUnionPtrType(const std::string & pointto) const { auto itr = structs.find(pointto); if(itr == structs.end()) return ""; return getKind(itr->second); } template<typename K, typename V> static bool mapContains(const std::unordered_map<K, V> & map, const K & k) { return map.find(k) != map.end(); } bool TypeManager::isDefined(const std::string & id) const { return mapContains(types, id) || mapContains(structs, id); } bool TypeManager::validPtr(const std::string & id) { if(id[id.length() - 1] == '*') { auto type = id.substr(0, id.length() - 1); if(!isDefined(type) && !validPtr(type)) return false; std::string owner("ptr"); auto foundT = types.find(type); if(foundT != types.end()) owner = foundT->second.owner; auto foundS = structs.find(type); if(foundS != structs.end()) owner = foundS->second.owner; return addType(owner, Pointer, id, type); } return false; } bool TypeManager::addStructUnion(const StructUnion & s) { laststruct = s.name; if(s.owner.empty() || s.name.empty() || isDefined(s.name)) return false; structs.insert({s.name, s}); return true; } bool TypeManager::addType(const Type & t) { if(t.name.empty() || isDefined(t.name)) return false; types.insert({t.name, t}); return true; } bool TypeManager::addType(const std::string & owner, Primitive primitive, const std::string & name, const std::string & pointto) { if(name.empty() || isDefined(name)) return false; Type t; t.owner = owner; t.name = name; t.primitive = primitive; t.size = primitivesizes[primitive]; t.pointto = pointto; return addType(t); } bool TypeManager::visitMember(const Member & root, Visitor & visitor) const { auto foundT = types.find(root.type); if(foundT != types.end()) { const auto & t = foundT->second; if(!t.pointto.empty()) { if(!isDefined(t.pointto)) return false; if(visitor.visitPtr(root, t)) //allow the visitor to bail out { if(!Visit(t.pointto, "*" + root.name, visitor)) return false; return visitor.visitBack(root); } return true; } return visitor.visitType(root, t); } auto foundS = structs.find(root.type); if(foundS != structs.end()) { const auto & s = foundS->second; if(!visitor.visitStructUnion(root, s)) return false; for(const auto & child : s.members) { if(child.arrsize) { if(!visitor.visitArray(child)) return false; for(auto i = 0; i < child.arrsize; i++) if(!visitMember(child, visitor)) return false; if(!visitor.visitBack(child)) return false; } else if(!visitMember(child, visitor)) return false; } return visitor.visitBack(root); } return false; } bool AddType(const std::string & owner, const std::string & type, const std::string & name) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddType(owner, type, name); } bool AddStruct(const std::string & owner, const std::string & name) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddStruct(owner, name); } bool AddUnion(const std::string & owner, const std::string & name) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddUnion(owner, name); } bool AddMember(const std::string & parent, const std::string & type, const std::string & name, int arrsize, int offset) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddMember(parent, type, name, arrsize, offset); } bool AppendMember(const std::string & type, const std::string & name, int arrsize, int offset) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AppendMember(type, name, arrsize, offset); } bool AddFunction(const std::string & owner, const std::string & name, const std::string & rettype, Types::CallingConvention callconv, bool noreturn) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddFunction(owner, name, rettype, callconv, noreturn); } bool AddArg(const std::string & function, const std::string & type, const std::string & name) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AddArg(function, type, name); } bool AppendArg(const std::string & type, const std::string & name) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.AppendArg(type, name); } int SizeofType(const std::string & type) { SHARED_ACQUIRE(LockTypeManager); return typeManager.Sizeof(type); } bool VisitType(const std::string & type, const std::string & name, Types::TypeManager::Visitor & visitor) { SHARED_ACQUIRE(LockTypeManager); return typeManager.Visit(type, name, visitor); } void ClearTypes(const std::string & owner) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.Clear(owner); } bool RemoveType(const std::string & type) { EXCLUSIVE_ACQUIRE(LockTypeManager); return typeManager.RemoveType(type); } void EnumTypes(std::vector<Types::TypeManager::Summary> & typeList) { SHARED_ACQUIRE(LockTypeManager); return typeManager.Enum(typeList); } int json_default_int(const JSON object, const char* key, int defaultVal) { auto jint = json_object_get(object, key); if(jint && json_is_integer(jint)) return int(json_integer_value(jint)); return defaultVal; } static void loadTypes(const JSON troot, std::vector<Member> & types) { if(!troot) return; size_t i; JSON vali; Member curType; json_array_foreach(troot, i, vali) { auto type = json_string_value(json_object_get(vali, "type")); auto name = json_string_value(json_object_get(vali, "name")); if(!type || !*type || !name || !*name) continue; curType.type = type; curType.name = name; types.push_back(curType); } } static void loadStructUnions(const JSON suroot, bool isunion, std::vector<StructUnion> & structUnions) { if(!suroot) return; size_t i; JSON vali; StructUnion curSu; curSu.isunion = isunion; json_array_foreach(suroot, i, vali) { auto suname = json_string_value(json_object_get(vali, "name")); if(!suname || !*suname) continue; curSu.name = suname; curSu.members.clear(); auto members = json_object_get(vali, "members"); size_t j; JSON valj; Member curMember; json_array_foreach(members, j, valj) { auto type = json_string_value(json_object_get(valj, "type")); auto name = json_string_value(json_object_get(valj, "name")); if(!type || !*type || !name || !*name) continue; curMember.type = type; curMember.name = name; curMember.arrsize = json_default_int(valj, "arrsize", 0); curMember.offset = json_default_int(valj, "offset", -1); curSu.members.push_back(curMember); } structUnions.push_back(curSu); } } static void loadFunctions(const JSON froot, std::vector<Function> & functions) { if(!froot) return; size_t i; JSON vali; Function curFunction; json_array_foreach(froot, i, vali) { auto rettype = json_string_value(json_object_get(vali, "rettype")); auto fname = json_string_value(json_object_get(vali, "name")); if(!rettype || !*rettype || !fname || !*fname) continue; curFunction.rettype = rettype; curFunction.name = fname; curFunction.args.clear(); auto callconv = json_string_value(json_object_get(vali, "callconv")); curFunction.noreturn = json_boolean_value(json_object_get(vali, "noreturn")); if(scmp(callconv, "cdecl")) curFunction.callconv = Cdecl; else if(scmp(callconv, "stdcall")) curFunction.callconv = Stdcall; else if(scmp(callconv, "thiscall")) curFunction.callconv = Thiscall; else if(scmp(callconv, "delphi")) curFunction.callconv = Delphi; else curFunction.callconv = Cdecl; auto args = json_object_get(vali, "args"); size_t j; JSON valj; Member curArg; json_array_foreach(args, j, valj) { auto type = json_string_value(json_object_get(valj, "type")); auto name = json_string_value(json_object_get(valj, "name")); if(!type || !*type || !name || !*name) continue; curArg.type = type; curArg.name = name; curFunction.args.push_back(curArg); } functions.push_back(curFunction); } } void LoadModel(const std::string & owner, Model & model) { //Add all base struct/union types first to avoid errors later for(auto & su : model.structUnions) { auto success = su.isunion ? typeManager.AddUnion(owner, su.name) : typeManager.AddStruct(owner, su.name); if(!success) { //TODO properly handle errors dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to add %s %s;\n"), su.isunion ? "union" : "struct", su.name.c_str()); su.name.clear(); //signal error } } //Add simple typedefs for(auto & type : model.types) { auto success = typeManager.AddType(owner, type.type, type.name); if(!success) { //TODO properly handle errors dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to add typedef %s %s;\n"), type.type.c_str(), type.name.c_str()); } } //Add base function types to avoid errors later for(auto & function : model.functions) { auto success = typeManager.AddFunction(owner, function.name, function.rettype, function.callconv, function.noreturn); if(!success) { //TODO properly handle errors dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to add function %s %s()\n"), function.rettype.c_str(), function.name.c_str()); function.name.clear(); //signal error } } //Add struct/union members for(auto & su : model.structUnions) { if(su.name.empty()) //skip error-signalled structs/unions continue; for(auto & member : su.members) { auto success = typeManager.AddMember(su.name, member.type, member.name, member.arrsize, member.offset); if(!success) { //TODO properly handle errors dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to add member %s %s.%s;\n"), member.type.c_str(), su.name.c_str(), member.name.c_str()); } } } //Add function arguments for(auto & function : model.functions) { if(function.name.empty()) //skip error-signalled functions continue; for(auto & arg : function.args) { auto success = typeManager.AddArg(function.name, arg.type, arg.name); if(!success) { //TODO properly handle errors dprintf(QT_TRANSLATE_NOOP("DBG", "Failed to add argument %s %s.%s;\n"), arg.type.c_str(), function.name.c_str(), arg.name.c_str()); } } } } bool LoadTypesJson(const std::string & json, const std::string & owner) { EXCLUSIVE_ACQUIRE(LockTypeManager); auto root = json_loads(json.c_str(), 0, 0); if(root) { Model model; loadTypes(json_object_get(root, "types"), model.types); loadTypes(json_object_get(root, ArchValue("types32", "types64")), model.types); loadStructUnions(json_object_get(root, "structs"), false, model.structUnions); loadStructUnions(json_object_get(root, ArchValue("structs32", "structs64")), false, model.structUnions); loadStructUnions(json_object_get(root, "unions"), true, model.structUnions); loadStructUnions(json_object_get(root, ArchValue("unions32", "unions64")), true, model.structUnions); loadFunctions(json_object_get(root, "functions"), model.functions); loadFunctions(json_object_get(root, ArchValue("functions32", "functions64")), model.functions); LoadModel(owner, model); // Free root json_decref(root); } else return false; return true; } bool LoadTypesFile(const std::string & path, const std::string & owner) { std::string json; if(!FileHelper::ReadAllText(path, json)) return false; return LoadTypesJson(json, owner); } std::string StructUnionPtrType(const std::string & pointto) { return typeManager.StructUnionPtrType(pointto); }
C/C++
x64dbg-development/src/dbg/types.h
#pragma once #include <string> #include <vector> #include <unordered_map> namespace Types { enum Primitive { Void, Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Dsint, Duint, Float, Double, Pointer, PtrString, //char* (null-terminated) PtrWString //wchar_t* (null-terminated) }; struct Type { std::string owner; //Type owner std::string name; //Type identifier. std::string pointto; //Type identifier of *Type Primitive primitive; //Primitive type. int size = 0; //Size in bytes. }; struct Member { std::string name; //Member identifier std::string type; //Type.name int arrsize = 0; //Number of elements if Member is an array int offset = -1; //Member offset (only stored for reference) }; struct StructUnion { std::string owner; //StructUnion owner std::string name; //StructUnion identifier std::vector<Member> members; //StructUnion members bool isunion = false; //Is this a union? int size = 0; }; enum CallingConvention { Cdecl, Stdcall, Thiscall, Delphi }; struct Function { std::string owner; //Function owner std::string name; //Function identifier std::string rettype; //Function return type CallingConvention callconv = Cdecl; //Function calling convention bool noreturn = false; //Function does not return (ExitProcess, _exit) std::vector<Member> args; //Function arguments }; struct TypeManager { struct Visitor { virtual ~Visitor() { } virtual bool visitType(const Member & member, const Type & type) = 0; virtual bool visitStructUnion(const Member & member, const StructUnion & type) = 0; virtual bool visitArray(const Member & member) = 0; virtual bool visitPtr(const Member & member, const Type & type) = 0; virtual bool visitBack(const Member & member) = 0; }; struct Summary { std::string kind; std::string name; std::string owner; int size = 0; }; explicit TypeManager(); bool AddType(const std::string & owner, const std::string & type, const std::string & name); bool AddStruct(const std::string & owner, const std::string & name); bool AddUnion(const std::string & owner, const std::string & name); bool AddMember(const std::string & parent, const std::string & type, const std::string & name, int arrsize = 0, int offset = -1); bool AppendMember(const std::string & type, const std::string & name, int arrsize = 0, int offset = -1); bool AddFunction(const std::string & owner, const std::string & name, const std::string & rettype, CallingConvention callconv = Cdecl, bool noreturn = false); bool AddArg(const std::string & function, const std::string & type, const std::string & name); bool AppendArg(const std::string & type, const std::string & name); int Sizeof(const std::string & type) const; bool Visit(const std::string & type, const std::string & name, Visitor & visitor) const; void Clear(const std::string & owner = ""); bool RemoveType(const std::string & type); void Enum(std::vector<Summary> & typeList) const; std::string StructUnionPtrType(const std::string & pointto) const; private: std::unordered_map<Primitive, int> primitivesizes; std::unordered_map<std::string, Type> types; std::unordered_map<std::string, StructUnion> structs; std::unordered_map<std::string, Function> functions; std::string laststruct; std::string lastfunction; bool isDefined(const std::string & id) const; bool validPtr(const std::string & id); bool addStructUnion(const StructUnion & s); bool addType(const std::string & owner, Primitive primitive, const std::string & name, const std::string & pointto = ""); bool addType(const Type & t); bool visitMember(const Member & root, Visitor & visitor) const; }; struct Model { std::vector<Member> types; std::vector<StructUnion> structUnions; std::vector<Function> functions; }; }; bool AddType(const std::string & owner, const std::string & type, const std::string & name); bool AddStruct(const std::string & owner, const std::string & name); bool AddUnion(const std::string & owner, const std::string & name); bool AddMember(const std::string & parent, const std::string & type, const std::string & name, int arrsize = 0, int offset = -1); bool AppendMember(const std::string & type, const std::string & name, int arrsize = 0, int offset = -1); bool AddFunction(const std::string & owner, const std::string & name, const std::string & rettype, Types::CallingConvention callconv = Types::Cdecl, bool noreturn = false); bool AddArg(const std::string & function, const std::string & type, const std::string & name); bool AppendArg(const std::string & type, const std::string & name); int SizeofType(const std::string & type); bool VisitType(const std::string & type, const std::string & name, Types::TypeManager::Visitor & visitor); void ClearTypes(const std::string & owner = ""); bool RemoveType(const std::string & type); void EnumTypes(std::vector<Types::TypeManager::Summary> & typeList); bool LoadTypesJson(const std::string & json, const std::string & owner); bool LoadTypesFile(const std::string & path, const std::string & owner); bool ParseTypes(const std::string & parse, const std::string & owner); std::string StructUnionPtrType(const std::string & pointto);
C++
x64dbg-development/src/dbg/typesparser.cpp
#include "types.h" #include "console.h" using namespace Types; #include "btparser/btparser/lexer.h" void LoadModel(const std::string & owner, Model & model); bool ParseTypes(const std::string & parse, const std::string & owner) { Lexer lexer; lexer.SetInputData(parse); std::vector<Lexer::TokenState> tokens; size_t index = 0; auto getToken = [&](size_t i) -> Lexer::TokenState & { if(index >= tokens.size() - 1) i = tokens.size() - 1; return tokens[i]; }; auto curToken = [&]() -> Lexer::TokenState & { return getToken(index); }; auto isToken = [&](Lexer::Token token) { return getToken(index).Token == token; }; auto isTokenList = [&](std::initializer_list<Lexer::Token> il) { size_t i = 0; for(auto l : il) if(getToken(index + i++).Token != l) return false; return true; }; std::string error; if(!lexer.DoLexing(tokens, error)) { dputs_untranslated(error.c_str()); return false; } Model model; auto errLine = [&]() { dprintf("[line %d:%d] ", curToken().CurLine, curToken().LineIndex); }; auto eatSemic = [&]() { while(curToken().Token == Lexer::tok_semic) index++; }; auto parseTypedef = [&]() { if(isToken(Lexer::tok_typedef)) { index++; std::vector<Lexer::TokenState> tdefToks; while(!isToken(Lexer::tok_semic)) { if(isToken(Lexer::tok_eof)) { errLine(); dputs("unexpected eof in typedef"); return false; } tdefToks.push_back(curToken()); index++; } eatSemic(); if(tdefToks.size() >= 2) //at least typedef a b; { Member tm; tm.name = lexer.TokString(tdefToks[tdefToks.size() - 1]); tdefToks.pop_back(); for(auto & t : tdefToks) if(!t.IsType() && t.Token != Lexer::tok_op_mul && t.Token != Lexer::tok_identifier && t.Token != Lexer::tok_void) { errLine(); dprintf("token %s is not a type...\n", lexer.TokString(t).c_str()); return false; } else { if(!tm.type.empty() && t.Token != Lexer::tok_op_mul) tm.type.push_back(' '); tm.type += lexer.TokString(t); } //dprintf("typedef %s:%s\n", tm.type.c_str(), tm.name.c_str()); model.types.push_back(tm); return true; } errLine(); dputs("not enough tokens for typedef"); return false; } return true; }; auto parseMember = [&](StructUnion & su) { std::vector<Lexer::TokenState> memToks; while(!isToken(Lexer::tok_semic)) { if(isToken(Lexer::tok_eof)) { errLine(); dputs("unexpected eof in member"); return false; } memToks.push_back(curToken()); index++; } eatSemic(); if(memToks.size() >= 2) //at least type name; { Member m; for(size_t i = 0; i < memToks.size(); i++) { const auto & t = memToks[i]; if(t.Token == Lexer::tok_subopen) { if(i + 1 >= memToks.size()) { errLine(); dputs("unexpected end after ["); return false; } if(memToks[i + 1].Token != Lexer::tok_number) { errLine(); dputs("expected number token"); return false; } m.arrsize = int(memToks[i + 1].NumberVal); if(i + 2 >= memToks.size()) { errLine(); dputs("unexpected end, expected ]"); return false; } if(memToks[i + 2].Token != Lexer::tok_subclose) { errLine(); dprintf("expected ], got %s\n", lexer.TokString(memToks[i + 2]).c_str()); return false; } if(i + 2 != memToks.size() - 1) { errLine(); dputs("too many tokens"); return false; } break; } else if(i + 1 == memToks.size() || memToks[i + 1].Token == Lexer::tok_subopen) //last = name { m.name = lexer.TokString(memToks[i]); } else if(!t.IsType() && t.Token != Lexer::tok_op_mul && t.Token != Lexer::tok_identifier && t.Token != Lexer::tok_void) { errLine(); dprintf("token %s is not a type...\n", lexer.TokString(t).c_str()); return false; } else { if(!m.type.empty() && t.Token != Lexer::tok_op_mul) m.type.push_back(' '); m.type += lexer.TokString(t); } } //dprintf("member: %s %s;\n", m.type.c_str(), m.name.c_str()); su.members.push_back(m); return true; } errLine(); dputs("not enough tokens for member"); return false; }; auto parseStructUnion = [&]() { if(isToken(Lexer::tok_struct) || isToken(Lexer::tok_union)) { StructUnion su; su.isunion = isToken(Lexer::tok_union); index++; if(isTokenList({ Lexer::tok_identifier, Lexer::tok_bropen })) { su.name = lexer.TokString(curToken()); index += 2; while(!isToken(Lexer::tok_brclose)) { if(isToken(Lexer::tok_eof)) { errLine(); dprintf("unexpected eof in %s\n", su.isunion ? "union" : "struct"); return false; } if(isToken(Lexer::tok_bropen)) { errLine(); dputs("nested blocks are not allowed!"); return false; } if(!parseMember(su)) return false; } index++; //eat tok_brclose //dprintf("%s %s, members: %d\n", su.isunion ? "union" : "struct", su.name.c_str(), int(su.members.size())); model.structUnions.push_back(su); if(!isToken(Lexer::tok_semic)) { errLine(); dputs("expected semicolon!"); return false; } eatSemic(); return true; } else { errLine(); dputs("invalid struct token sequence!"); return false; } } return true; }; while(!isToken(Lexer::tok_eof)) { auto curIndex = index; if(!parseTypedef()) return false; if(!parseStructUnion()) return false; eatSemic(); if(curIndex == index) { errLine(); dprintf("unexpected token %s\n", lexer.TokString(curToken()).c_str()); return false; } } LoadModel(owner, model); return true; }
C++
x64dbg-development/src/dbg/value.cpp
/** @file value.cpp @brief Implements the value class. */ #include "value.h" #include "variable.h" #include "debugger.h" #include "console.h" #include "memory.h" #include "symbolinfo.h" #include "module.h" #include "label.h" #include "expressionparser.h" #include "function.h" #include "threading.h" #include "TraceRecord.h" #include "plugin_loader.h" #include "exception.h" static bool dosignedcalc = false; /** \brief Returns whether we do signed or unsigned calculations. \return true if we do signed calculations, false for unsigned calculationss. */ bool valuesignedcalc() { return dosignedcalc; } /** \brief Set whether we do signed or unsigned calculations. \param a true for signed calculations, false for unsigned calculations. */ void valuesetsignedcalc(bool a) { dosignedcalc = a; } /** \brief Check if a string is a flag. \param string The string to check. \return true if the string is a flag, false otherwise. */ static bool isflag(const char* string) { if(scmp(string, "cf")) return true; if(scmp(string, "pf")) return true; if(scmp(string, "af")) return true; if(scmp(string, "zf")) return true; if(scmp(string, "sf")) return true; if(scmp(string, "tf")) return true; if(scmp(string, "if")) return true; if(scmp(string, "df")) return true; if(scmp(string, "of")) return true; if(scmp(string, "rf")) return true; if(scmp(string, "vm")) return true; if(scmp(string, "ac")) return true; if(scmp(string, "vif")) return true; if(scmp(string, "vip")) return true; if(scmp(string, "id")) return true; return false; } /** \brief Check if a string is a register. \param string The string to check. \return true if the string is a register, false otherwise. */ static bool isregister(const char* string) { if(scmp(string, "eax")) return true; if(scmp(string, "ebx")) return true; if(scmp(string, "ecx")) return true; if(scmp(string, "edx")) return true; if(scmp(string, "edi")) return true; if(scmp(string, "esi")) return true; if(scmp(string, "ebp")) return true; if(scmp(string, "esp")) return true; if(scmp(string, "eip")) return true; if(scmp(string, "eflags")) return true; if(scmp(string, "ax")) return true; if(scmp(string, "bx")) return true; if(scmp(string, "cx")) return true; if(scmp(string, "dx")) return true; if(scmp(string, "si")) return true; if(scmp(string, "di")) return true; if(scmp(string, "bp")) return true; if(scmp(string, "sp")) return true; if(scmp(string, "ip")) return true; if(scmp(string, "ah")) return true; if(scmp(string, "al")) return true; if(scmp(string, "bh")) return true; if(scmp(string, "bl")) return true; if(scmp(string, "ch")) return true; if(scmp(string, "cl")) return true; if(scmp(string, "dh")) return true; if(scmp(string, "dl")) return true; if(scmp(string, "sih")) return true; if(scmp(string, "sil")) return true; if(scmp(string, "dih")) return true; if(scmp(string, "dil")) return true; if(scmp(string, "bph")) return true; if(scmp(string, "bpl")) return true; if(scmp(string, "sph")) return true; if(scmp(string, "spl")) return true; if(scmp(string, "iph")) return true; if(scmp(string, "ipl")) return true; if(scmp(string, "dr0")) return true; if(scmp(string, "dr1")) return true; if(scmp(string, "dr2")) return true; if(scmp(string, "dr3")) return true; if(scmp(string, "dr6") || scmp(string, "dr4")) return true; if(scmp(string, "dr7") || scmp(string, "dr5")) return true; if(scmp(string, "cax")) return true; if(scmp(string, "cbx")) return true; if(scmp(string, "ccx")) return true; if(scmp(string, "cdx")) return true; if(scmp(string, "csi")) return true; if(scmp(string, "cdi")) return true; if(scmp(string, "cip")) return true; if(scmp(string, "csp")) return true; if(scmp(string, "cbp")) return true; if(scmp(string, "cflags")) return true; if(scmp(string, "lasterror")) return true; if(scmp(string, "laststatus")) return true; if(scmp(string, "gs")) return true; if(scmp(string, "fs")) return true; if(scmp(string, "es")) return true; if(scmp(string, "ds")) return true; if(scmp(string, "cs")) return true; if(scmp(string, "ss")) return true; #ifndef _WIN64 return false; #endif // _WIN64 if(scmp(string, "rax")) return true; if(scmp(string, "rbx")) return true; if(scmp(string, "rcx")) return true; if(scmp(string, "rdx")) return true; if(scmp(string, "rdi")) return true; if(scmp(string, "rsi")) return true; if(scmp(string, "rbp")) return true; if(scmp(string, "rsp")) return true; if(scmp(string, "rip")) return true; if(scmp(string, "rflags")) return true; if(scmp(string, "r8")) return true; if(scmp(string, "r9")) return true; if(scmp(string, "r10")) return true; if(scmp(string, "r11")) return true; if(scmp(string, "r12")) return true; if(scmp(string, "r13")) return true; if(scmp(string, "r14")) return true; if(scmp(string, "r15")) return true; if(scmp(string, "r8d")) return true; if(scmp(string, "r9d")) return true; if(scmp(string, "r10d")) return true; if(scmp(string, "r11d")) return true; if(scmp(string, "r12d")) return true; if(scmp(string, "r13d")) return true; if(scmp(string, "r14d")) return true; if(scmp(string, "r15d")) return true; if(scmp(string, "r8w")) return true; if(scmp(string, "r9w")) return true; if(scmp(string, "r10w")) return true; if(scmp(string, "r11w")) return true; if(scmp(string, "r12w")) return true; if(scmp(string, "r13w")) return true; if(scmp(string, "r14w")) return true; if(scmp(string, "r15w")) return true; if(scmp(string, "r8b")) return true; if(scmp(string, "r9b")) return true; if(scmp(string, "r10b")) return true; if(scmp(string, "r11b")) return true; if(scmp(string, "r12b")) return true; if(scmp(string, "r13b")) return true; if(scmp(string, "r14b")) return true; if(scmp(string, "r15b")) return true; return false; } #define MXCSRFLAG_IE 0x1 #define MXCSRFLAG_DE 0x2 #define MXCSRFLAG_ZE 0x4 #define MXCSRFLAG_OE 0x8 #define MXCSRFLAG_UE 0x10 #define MXCSRFLAG_PE 0x20 #define MXCSRFLAG_DAZ 0x40 #define MXCSRFLAG_IM 0x80 #define MXCSRFLAG_DM 0x100 #define MXCSRFLAG_ZM 0x200 #define MXCSRFLAG_OM 0x400 #define MXCSRFLAG_UM 0x800 #define MXCSRFLAG_PM 0x1000 #define MXCSRFLAG_FZ 0x8000 typedef struct { const char* name; unsigned int flag; } FLAG_NAME_VALUE_TABLE_t; #define MXCSR_NAME_FLAG_TABLE_ENTRY(flag_name) { #flag_name, MXCSRFLAG_##flag_name } /** \brief Gets the MXCSR flag AND value from a string. \param string The flag name. \return The value to AND the MXCSR value with to get the flag. 0 when not found. */ static unsigned int getmxcsrflagfromstring(const char* string) { static FLAG_NAME_VALUE_TABLE_t mxcsrnameflagtable[] = { MXCSR_NAME_FLAG_TABLE_ENTRY(IE), MXCSR_NAME_FLAG_TABLE_ENTRY(DE), MXCSR_NAME_FLAG_TABLE_ENTRY(ZE), MXCSR_NAME_FLAG_TABLE_ENTRY(OE), MXCSR_NAME_FLAG_TABLE_ENTRY(UE), MXCSR_NAME_FLAG_TABLE_ENTRY(PE), MXCSR_NAME_FLAG_TABLE_ENTRY(DAZ), MXCSR_NAME_FLAG_TABLE_ENTRY(IM), MXCSR_NAME_FLAG_TABLE_ENTRY(DM), MXCSR_NAME_FLAG_TABLE_ENTRY(ZM), MXCSR_NAME_FLAG_TABLE_ENTRY(OM), MXCSR_NAME_FLAG_TABLE_ENTRY(UM), MXCSR_NAME_FLAG_TABLE_ENTRY(PM), MXCSR_NAME_FLAG_TABLE_ENTRY(FZ) }; for(int i = 0; i < (sizeof(mxcsrnameflagtable) / sizeof(*mxcsrnameflagtable)); i++) { if(scmp(string, mxcsrnameflagtable[i].name)) return mxcsrnameflagtable[i].flag; } return 0; } /** \brief Gets the MXCSR flag from a string and a flags value. \param mxcsrflags The flags value to get the flag from. \param string The string with the flag name. \return true if the flag is 1, false if the flag is 0. */ bool valmxcsrflagfromstring(duint mxcsrflags, const char* string) { unsigned int flag = getmxcsrflagfromstring(string); if(flag == 0) return false; return (bool)((int)(mxcsrflags & flag) != 0); } #define x87STATUSWORD_FLAG_I 0x1 #define x87STATUSWORD_FLAG_D 0x2 #define x87STATUSWORD_FLAG_Z 0x4 #define x87STATUSWORD_FLAG_O 0x8 #define x87STATUSWORD_FLAG_U 0x10 #define x87STATUSWORD_FLAG_P 0x20 #define x87STATUSWORD_FLAG_SF 0x40 #define x87STATUSWORD_FLAG_ES 0x80 #define x87STATUSWORD_FLAG_C0 0x100 #define x87STATUSWORD_FLAG_C1 0x200 #define x87STATUSWORD_FLAG_C2 0x400 #define x87STATUSWORD_FLAG_C3 0x4000 #define x87STATUSWORD_FLAG_B 0x8000 #define X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(flag_name) { #flag_name, x87STATUSWORD_FLAG_##flag_name } /** \brief Gets the x87 status word AND value from a string. \param string The status word name. \return The value to AND the status word with to get the flag. 0 when not found. */ static unsigned int getx87statuswordflagfromstring(const char* string) { static FLAG_NAME_VALUE_TABLE_t statuswordflagtable[] = { X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(I), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(D), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(Z), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(O), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(U), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(P), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(SF), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(ES), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(C0), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(C1), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(C2), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(C3), X87STATUSWORD_NAME_FLAG_TABLE_ENTRY(B) }; for(int i = 0; i < (sizeof(statuswordflagtable) / sizeof(*statuswordflagtable)); i++) { if(scmp(string, statuswordflagtable[i].name)) return statuswordflagtable[i].flag; } return 0; } /** \brief Gets an x87 status flag from a string. \param statusword The status word value. \param string The flag name. \return true if the flag is 1, false if the flag is 0. */ bool valx87statuswordflagfromstring(duint statusword, const char* string) { unsigned int flag = getx87statuswordflagfromstring(string); if(flag == 0) return false; return (bool)((int)(statusword & flag) != 0); } #define x87CONTROLWORD_FLAG_IM 0x1 #define x87CONTROLWORD_FLAG_DM 0x2 #define x87CONTROLWORD_FLAG_ZM 0x4 #define x87CONTROLWORD_FLAG_OM 0x8 #define x87CONTROLWORD_FLAG_UM 0x10 #define x87CONTROLWORD_FLAG_PM 0x20 #define x87CONTROLWORD_FLAG_IEM 0x80 #define x87CONTROLWORD_FLAG_IC 0x1000 #define X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(flag_name) { #flag_name, x87CONTROLWORD_FLAG_##flag_name } /** \brief Gets the x87 control word flag AND value from a string. \param string The name of the control word. \return The value to AND the control word with to get the flag. 0 when not found. */ static unsigned int getx87controlwordflagfromstring(const char* string) { static FLAG_NAME_VALUE_TABLE_t controlwordflagtable[] = { X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(IM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(DM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(ZM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(OM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(UM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(PM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(IEM), X87CONTROLWORD_NAME_FLAG_TABLE_ENTRY(IC) }; for(int i = 0; i < (sizeof(controlwordflagtable) / sizeof(*controlwordflagtable)); i++) { if(scmp(string, controlwordflagtable[i].name)) return controlwordflagtable[i].flag; } return 0; } /** \brief Get an x87 control word flag from a string. \param controlword The control word to get the flag from. \param string The flag name. \return true if the flag is 1, false when the flag is 0. */ bool valx87controlwordflagfromstring(duint controlword, const char* string) { unsigned int flag = getx87controlwordflagfromstring(string); if(flag == 0) return false; return (bool)((int)(controlword & flag) != 0); } /** \brief Gets the MXCSR field from a string. \param mxcsrflags The mxcsrflags to get the field from. \param string The name of the field (should be "RC"). \return The MXCSR field word. */ unsigned short valmxcsrfieldfromstring(duint mxcsrflags, const char* string) { if(scmp(string, "RC")) return ((mxcsrflags & 0x6000) >> 13); return 0; } /** \brief Gets the x87 status word field from a string. \param statusword The status word to get the field from. \param string The name of the field (should be "TOP"). \return The x87 status word field. */ unsigned short valx87statuswordfieldfromstring(duint statusword, const char* string) { if(scmp(string, "TOP")) return ((statusword & 0x3800) >> 11); return 0; } /** \brief Gets the x87 control word field from a string. \param controlword The control word to get the field from. \param string The name of the field. \return The x87 control word field. */ unsigned short valx87controlwordfieldfromstring(duint controlword, const char* string) { if(scmp(string, "PC")) return ((controlword & 0x300) >> 8); if(scmp(string, "RC")) return ((controlword & 0xC00) >> 10); return 0; } /** \brief Gets a flag from a string. \param eflags The eflags value to get the flag from. \param string The name of the flag. \return true if the flag equals to 1, false if the flag is 0 or not found. */ bool valflagfromstring(duint eflags, const char* string) { if(scmp(string, "cf")) return (bool)((int)(eflags & 0x1) != 0); if(scmp(string, "pf")) return (bool)((int)(eflags & 0x4) != 0); if(scmp(string, "af")) return (bool)((int)(eflags & 0x10) != 0); if(scmp(string, "zf")) return (bool)((int)(eflags & 0x40) != 0); if(scmp(string, "sf")) return (bool)((int)(eflags & 0x80) != 0); if(scmp(string, "tf")) return (bool)((int)(eflags & 0x100) != 0); if(scmp(string, "if")) return (bool)((int)(eflags & 0x200) != 0); if(scmp(string, "df")) return (bool)((int)(eflags & 0x400) != 0); if(scmp(string, "of")) return (bool)((int)(eflags & 0x800) != 0); if(scmp(string, "rf")) return (bool)((int)(eflags & 0x10000) != 0); if(scmp(string, "vm")) return (bool)((int)(eflags & 0x20000) != 0); if(scmp(string, "ac")) return (bool)((int)(eflags & 0x40000) != 0); if(scmp(string, "vif")) return (bool)((int)(eflags & 0x80000) != 0); if(scmp(string, "vip")) return (bool)((int)(eflags & 0x100000) != 0); if(scmp(string, "id")) return (bool)((int)(eflags & 0x200000) != 0); return false; } /** \brief Sets a flag value. \param string The name of the flag. \param set The value of the flag. \return true if the flag was successfully set, false otherwise. */ bool setflag(const char* string, bool set) { duint eflags = GetContextDataEx(hActiveThread, UE_CFLAGS); duint xorval = 0; duint flag = 0; if(scmp(string, "cf")) flag = 0x1; else if(scmp(string, "pf")) flag = 0x4; else if(scmp(string, "af")) flag = 0x10; else if(scmp(string, "zf")) flag = 0x40; else if(scmp(string, "sf")) flag = 0x80; else if(scmp(string, "tf")) flag = 0x100; else if(scmp(string, "if")) flag = 0x200; else if(scmp(string, "df")) flag = 0x400; else if(scmp(string, "of")) flag = 0x800; else if(scmp(string, "rf")) flag = 0x10000; else if(scmp(string, "vm")) flag = 0x20000; else if(scmp(string, "ac")) flag = 0x40000; else if(scmp(string, "vif")) flag = 0x80000; else if(scmp(string, "vip")) flag = 0x100000; else if(scmp(string, "id")) flag = 0x200000; if(set) eflags |= flag; else eflags &= ~flag; return SetContextDataEx(hActiveThread, UE_CFLAGS, eflags); } /** \brief Gets a register from a string. \param [out] size This function can store the register size in bytes in this parameter. Can be null, in that case it will be ignored. \param string The name of the register to get. Cannot be null. \return The register value. */ duint getregister(int* size, const char* string) { if(size) *size = 4; if(scmp(string, "eax")) { return GetContextDataEx(hActiveThread, UE_EAX); } if(scmp(string, "ebx")) { return GetContextDataEx(hActiveThread, UE_EBX); } if(scmp(string, "ecx")) { return GetContextDataEx(hActiveThread, UE_ECX); } if(scmp(string, "edx")) { return GetContextDataEx(hActiveThread, UE_EDX); } if(scmp(string, "edi")) { return GetContextDataEx(hActiveThread, UE_EDI); } if(scmp(string, "esi")) { return GetContextDataEx(hActiveThread, UE_ESI); } if(scmp(string, "ebp")) { return GetContextDataEx(hActiveThread, UE_EBP); } if(scmp(string, "esp")) { return GetContextDataEx(hActiveThread, UE_ESP); } if(scmp(string, "eip")) { return GetContextDataEx(hActiveThread, UE_EIP); } if(scmp(string, "eflags")) { return GetContextDataEx(hActiveThread, UE_EFLAGS); } if(scmp(string, "gs")) { return GetContextDataEx(hActiveThread, UE_SEG_GS); } if(scmp(string, "fs")) { return GetContextDataEx(hActiveThread, UE_SEG_FS); } if(scmp(string, "es")) { return GetContextDataEx(hActiveThread, UE_SEG_ES); } if(scmp(string, "ds")) { return GetContextDataEx(hActiveThread, UE_SEG_DS); } if(scmp(string, "cs")) { return GetContextDataEx(hActiveThread, UE_SEG_CS); } if(scmp(string, "ss")) { return GetContextDataEx(hActiveThread, UE_SEG_SS); } if(scmp(string, "lasterror")) { duint error = 0; MemReadUnsafe((duint)GetTEBLocation(hActiveThread) + ArchValue(0x34, 0x68), &error, 4); return error; } if(scmp(string, "laststatus")) { duint status = 0; MemReadUnsafe((duint)GetTEBLocation(hActiveThread) + ArchValue(0xBF4, 0x1250), &status, 4); return status; } if(size) *size = 2; if(scmp(string, "ax")) { duint val = GetContextDataEx(hActiveThread, UE_EAX); return val & 0xFFFF; } if(scmp(string, "bx")) { duint val = GetContextDataEx(hActiveThread, UE_EBX); return val & 0xFFFF; } if(scmp(string, "cx")) { duint val = GetContextDataEx(hActiveThread, UE_ECX); return val & 0xFFFF; } if(scmp(string, "dx")) { duint val = GetContextDataEx(hActiveThread, UE_EDX); return val & 0xFFFF; } if(scmp(string, "si")) { duint val = GetContextDataEx(hActiveThread, UE_ESI); return val & 0xFFFF; } if(scmp(string, "di")) { duint val = GetContextDataEx(hActiveThread, UE_EDI); return val & 0xFFFF; } if(scmp(string, "bp")) { duint val = GetContextDataEx(hActiveThread, UE_EBP); return val & 0xFFFF; } if(scmp(string, "sp")) { duint val = GetContextDataEx(hActiveThread, UE_ESP); return val & 0xFFFF; } if(scmp(string, "ip")) { duint val = GetContextDataEx(hActiveThread, UE_EIP); return val & 0xFFFF; } if(size) *size = 1; if(scmp(string, "ah")) { duint val = GetContextDataEx(hActiveThread, UE_EAX); return (val >> 8) & 0xFF; } if(scmp(string, "al")) { duint val = GetContextDataEx(hActiveThread, UE_EAX); return val & 0xFF; } if(scmp(string, "bh")) { duint val = GetContextDataEx(hActiveThread, UE_EBX); return (val >> 8) & 0xFF; } if(scmp(string, "bl")) { duint val = GetContextDataEx(hActiveThread, UE_EBX); return val & 0xFF; } if(scmp(string, "ch")) { duint val = GetContextDataEx(hActiveThread, UE_ECX); return (val >> 8) & 0xFF; } if(scmp(string, "cl")) { duint val = GetContextDataEx(hActiveThread, UE_ECX); return val & 0xFF; } if(scmp(string, "dh")) { duint val = GetContextDataEx(hActiveThread, UE_EDX); return (val >> 8) & 0xFF; } if(scmp(string, "dl")) { duint val = GetContextDataEx(hActiveThread, UE_EDX); return val & 0xFF; } if(scmp(string, "sih")) { duint val = GetContextDataEx(hActiveThread, UE_ESI); return (val >> 8) & 0xFF; } if(scmp(string, "sil")) { duint val = GetContextDataEx(hActiveThread, UE_ESI); return val & 0xFF; } if(scmp(string, "dih")) { duint val = GetContextDataEx(hActiveThread, UE_EDI); return (val >> 8) & 0xFF; } if(scmp(string, "dil")) { duint val = GetContextDataEx(hActiveThread, UE_EDI); return val & 0xFF; } if(scmp(string, "bph")) { duint val = GetContextDataEx(hActiveThread, UE_EBP); return (val >> 8) & 0xFF; } if(scmp(string, "bpl")) { duint val = GetContextDataEx(hActiveThread, UE_EBP); return val & 0xFF; } if(scmp(string, "sph")) { duint val = GetContextDataEx(hActiveThread, UE_ESP); return (val >> 8) & 0xFF; } if(scmp(string, "spl")) { duint val = GetContextDataEx(hActiveThread, UE_ESP); return val & 0xFF; } if(scmp(string, "iph")) { duint val = GetContextDataEx(hActiveThread, UE_EIP); return (val >> 8) & 0xFF; } if(scmp(string, "ipl")) { duint val = GetContextDataEx(hActiveThread, UE_EIP); return val & 0xFF; } if(size) *size = sizeof(duint); if(scmp(string, "dr0")) { return GetContextDataEx(hActiveThread, UE_DR0); } if(scmp(string, "dr1")) { return GetContextDataEx(hActiveThread, UE_DR1); } if(scmp(string, "dr2")) { return GetContextDataEx(hActiveThread, UE_DR2); } if(scmp(string, "dr3")) { return GetContextDataEx(hActiveThread, UE_DR3); } if(scmp(string, "dr6") || scmp(string, "dr4")) { return GetContextDataEx(hActiveThread, UE_DR6); } if(scmp(string, "dr7") || scmp(string, "dr5")) { return GetContextDataEx(hActiveThread, UE_DR7); } if(scmp(string, "cax")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RAX); #else return GetContextDataEx(hActiveThread, UE_EAX); #endif //_WIN64 } if(scmp(string, "cbx")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RBX); #else return GetContextDataEx(hActiveThread, UE_EBX); #endif //_WIN64 } if(scmp(string, "ccx")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RCX); #else return GetContextDataEx(hActiveThread, UE_ECX); #endif //_WIN64 } if(scmp(string, "cdx")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RDX); #else return GetContextDataEx(hActiveThread, UE_EDX); #endif //_WIN64 } if(scmp(string, "csi")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RSI); #else return GetContextDataEx(hActiveThread, UE_ESI); #endif //_WIN64 } if(scmp(string, "cdi")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RDI); #else return GetContextDataEx(hActiveThread, UE_EDI); #endif //_WIN64 } if(scmp(string, "cip")) { return GetContextDataEx(hActiveThread, UE_CIP); } if(scmp(string, "csp")) { return GetContextDataEx(hActiveThread, UE_CSP); } if(scmp(string, "cbp")) { #ifdef _WIN64 return GetContextDataEx(hActiveThread, UE_RBP); #else return GetContextDataEx(hActiveThread, UE_EBP); #endif //_WIN64 } if(scmp(string, "cflags")) { return GetContextDataEx(hActiveThread, UE_CFLAGS); } #ifdef _WIN64 if(size) *size = 8; if(scmp(string, "rax")) { return GetContextDataEx(hActiveThread, UE_RAX); } if(scmp(string, "rbx")) { return GetContextDataEx(hActiveThread, UE_RBX); } if(scmp(string, "rcx")) { return GetContextDataEx(hActiveThread, UE_RCX); } if(scmp(string, "rdx")) { return GetContextDataEx(hActiveThread, UE_RDX); } if(scmp(string, "rdi")) { return GetContextDataEx(hActiveThread, UE_RDI); } if(scmp(string, "rsi")) { return GetContextDataEx(hActiveThread, UE_RSI); } if(scmp(string, "rbp")) { return GetContextDataEx(hActiveThread, UE_RBP); } if(scmp(string, "rsp")) { return GetContextDataEx(hActiveThread, UE_RSP); } if(scmp(string, "rip")) { return GetContextDataEx(hActiveThread, UE_RIP); } if(scmp(string, "rflags")) { return GetContextDataEx(hActiveThread, UE_RFLAGS); } if(scmp(string, "r8")) { return GetContextDataEx(hActiveThread, UE_R8); } if(scmp(string, "r9")) { return GetContextDataEx(hActiveThread, UE_R9); } if(scmp(string, "r10")) { return GetContextDataEx(hActiveThread, UE_R10); } if(scmp(string, "r11")) { return GetContextDataEx(hActiveThread, UE_R11); } if(scmp(string, "r12")) { return GetContextDataEx(hActiveThread, UE_R12); } if(scmp(string, "r13")) { return GetContextDataEx(hActiveThread, UE_R13); } if(scmp(string, "r14")) { return GetContextDataEx(hActiveThread, UE_R14); } if(scmp(string, "r15")) { return GetContextDataEx(hActiveThread, UE_R15); } if(size) *size = 4; if(scmp(string, "r8d")) { return GetContextDataEx(hActiveThread, UE_R8) & 0xFFFFFFFF; } if(scmp(string, "r9d")) { return GetContextDataEx(hActiveThread, UE_R9) & 0xFFFFFFFF; } if(scmp(string, "r10d")) { return GetContextDataEx(hActiveThread, UE_R10) & 0xFFFFFFFF; } if(scmp(string, "r11d")) { return GetContextDataEx(hActiveThread, UE_R11) & 0xFFFFFFFF; } if(scmp(string, "r12d")) { return GetContextDataEx(hActiveThread, UE_R12) & 0xFFFFFFFF; } if(scmp(string, "r13d")) { return GetContextDataEx(hActiveThread, UE_R13) & 0xFFFFFFFF; } if(scmp(string, "r14d")) { return GetContextDataEx(hActiveThread, UE_R14) & 0xFFFFFFFF; } if(scmp(string, "r15d")) { return GetContextDataEx(hActiveThread, UE_R15) & 0xFFFFFFFF; } if(size) *size = 2; if(scmp(string, "r8w")) { return GetContextDataEx(hActiveThread, UE_R8) & 0xFFFF; } if(scmp(string, "r9w")) { return GetContextDataEx(hActiveThread, UE_R9) & 0xFFFF; } if(scmp(string, "r10w")) { return GetContextDataEx(hActiveThread, UE_R10) & 0xFFFF; } if(scmp(string, "r11w")) { return GetContextDataEx(hActiveThread, UE_R11) & 0xFFFF; } if(scmp(string, "r12w")) { return GetContextDataEx(hActiveThread, UE_R12) & 0xFFFF; } if(scmp(string, "r13w")) { return GetContextDataEx(hActiveThread, UE_R13) & 0xFFFF; } if(scmp(string, "r14w")) { return GetContextDataEx(hActiveThread, UE_R14) & 0xFFFF; } if(scmp(string, "r15w")) { return GetContextDataEx(hActiveThread, UE_R15) & 0xFFFF; } if(size) *size = 1; if(scmp(string, "r8b")) { return GetContextDataEx(hActiveThread, UE_R8) & 0xFF; } if(scmp(string, "r9b")) { return GetContextDataEx(hActiveThread, UE_R9) & 0xFF; } if(scmp(string, "r10b")) { return GetContextDataEx(hActiveThread, UE_R10) & 0xFF; } if(scmp(string, "r11b")) { return GetContextDataEx(hActiveThread, UE_R11) & 0xFF; } if(scmp(string, "r12b")) { return GetContextDataEx(hActiveThread, UE_R12) & 0xFF; } if(scmp(string, "r13b")) { return GetContextDataEx(hActiveThread, UE_R13) & 0xFF; } if(scmp(string, "r14b")) { return GetContextDataEx(hActiveThread, UE_R14) & 0xFF; } if(scmp(string, "r15b")) { return GetContextDataEx(hActiveThread, UE_R15) & 0xFF; } #endif //_WIN64 if(size) *size = 0; return 0; } /** \brief Sets a register value based on the register name. \param string The name of the register to set. \param value The new register value. \return true if the register was set, false otherwise. */ bool setregister(const char* string, duint value) { if(scmp(string, "eax")) return SetContextDataEx(hActiveThread, UE_EAX, value & 0xFFFFFFFF); if(scmp(string, "ebx")) return SetContextDataEx(hActiveThread, UE_EBX, value & 0xFFFFFFFF); if(scmp(string, "ecx")) return SetContextDataEx(hActiveThread, UE_ECX, value & 0xFFFFFFFF); if(scmp(string, "edx")) return SetContextDataEx(hActiveThread, UE_EDX, value & 0xFFFFFFFF); if(scmp(string, "edi")) return SetContextDataEx(hActiveThread, UE_EDI, value & 0xFFFFFFFF); if(scmp(string, "esi")) return SetContextDataEx(hActiveThread, UE_ESI, value & 0xFFFFFFFF); if(scmp(string, "ebp")) return SetContextDataEx(hActiveThread, UE_EBP, value & 0xFFFFFFFF); if(scmp(string, "esp")) return SetContextDataEx(hActiveThread, UE_ESP, value & 0xFFFFFFFF); if(scmp(string, "eip")) return SetContextDataEx(hActiveThread, UE_EIP, value & 0xFFFFFFFF); if(scmp(string, "eflags")) return SetContextDataEx(hActiveThread, UE_EFLAGS, value & 0xFFFFFFFF); if(scmp(string, "lasterror")) return MemWrite((duint)GetTEBLocation(hActiveThread) + ArchValue(0x34, 0x68), &value, 4); if(scmp(string, "laststatus")) return MemWrite((duint)GetTEBLocation(hActiveThread) + ArchValue(0xBF4, 0x1250), &value, 4); if(scmp(string, "gs")) return SetContextDataEx(hActiveThread, UE_SEG_GS, value & 0xFFFF); if(scmp(string, "fs")) return SetContextDataEx(hActiveThread, UE_SEG_FS, value & 0xFFFF); if(scmp(string, "es")) return SetContextDataEx(hActiveThread, UE_SEG_ES, value & 0xFFFF); if(scmp(string, "ds")) return SetContextDataEx(hActiveThread, UE_SEG_DS, value & 0xFFFF); if(scmp(string, "cs")) return SetContextDataEx(hActiveThread, UE_SEG_CS, value & 0xFFFF); if(scmp(string, "ss")) return SetContextDataEx(hActiveThread, UE_SEG_SS, value & 0xFFFF); if(scmp(string, "ax")) return SetContextDataEx(hActiveThread, UE_EAX, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EAX) & 0xFFFF0000)); if(scmp(string, "bx")) return SetContextDataEx(hActiveThread, UE_EBX, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EBX) & 0xFFFF0000)); if(scmp(string, "cx")) return SetContextDataEx(hActiveThread, UE_ECX, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_ECX) & 0xFFFF0000)); if(scmp(string, "dx")) return SetContextDataEx(hActiveThread, UE_EDX, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EDX) & 0xFFFF0000)); if(scmp(string, "si")) return SetContextDataEx(hActiveThread, UE_ESI, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_ESI) & 0xFFFF0000)); if(scmp(string, "di")) return SetContextDataEx(hActiveThread, UE_EDI, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EDI) & 0xFFFF0000)); if(scmp(string, "bp")) return SetContextDataEx(hActiveThread, UE_EBP, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EBP) & 0xFFFF0000)); if(scmp(string, "sp")) return SetContextDataEx(hActiveThread, UE_ESP, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_ESP) & 0xFFFF0000)); if(scmp(string, "ip")) return SetContextDataEx(hActiveThread, UE_EIP, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_EIP) & 0xFFFF0000)); if(scmp(string, "ah")) return SetContextDataEx(hActiveThread, UE_EAX, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EAX) & 0xFFFF00FF)); if(scmp(string, "al")) return SetContextDataEx(hActiveThread, UE_EAX, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EAX) & 0xFFFFFF00)); if(scmp(string, "bh")) return SetContextDataEx(hActiveThread, UE_EBX, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EBX) & 0xFFFF00FF)); if(scmp(string, "bl")) return SetContextDataEx(hActiveThread, UE_EBX, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EBX) & 0xFFFFFF00)); if(scmp(string, "ch")) return SetContextDataEx(hActiveThread, UE_ECX, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_ECX) & 0xFFFF00FF)); if(scmp(string, "cl")) return SetContextDataEx(hActiveThread, UE_ECX, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_ECX) & 0xFFFFFF00)); if(scmp(string, "dh")) return SetContextDataEx(hActiveThread, UE_EDX, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EDX) & 0xFFFF00FF)); if(scmp(string, "dl")) return SetContextDataEx(hActiveThread, UE_EDX, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EDX) & 0xFFFFFF00)); if(scmp(string, "sih")) return SetContextDataEx(hActiveThread, UE_ESI, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_ESI) & 0xFFFF00FF)); if(scmp(string, "sil")) return SetContextDataEx(hActiveThread, UE_ESI, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_ESI) & 0xFFFFFF00)); if(scmp(string, "dih")) return SetContextDataEx(hActiveThread, UE_EDI, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EDI) & 0xFFFF00FF)); if(scmp(string, "dil")) return SetContextDataEx(hActiveThread, UE_EDI, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EDI) & 0xFFFFFF00)); if(scmp(string, "bph")) return SetContextDataEx(hActiveThread, UE_EBP, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EBP) & 0xFFFF00FF)); if(scmp(string, "bpl")) return SetContextDataEx(hActiveThread, UE_EBP, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EBP) & 0xFFFFFF00)); if(scmp(string, "sph")) return SetContextDataEx(hActiveThread, UE_ESP, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_ESP) & 0xFFFF00FF)); if(scmp(string, "spl")) return SetContextDataEx(hActiveThread, UE_ESP, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_ESP) & 0xFFFFFF00)); if(scmp(string, "iph")) return SetContextDataEx(hActiveThread, UE_EIP, ((value & 0xFF) << 8) | (GetContextDataEx(hActiveThread, UE_EIP) & 0xFFFF00FF)); if(scmp(string, "ipl")) return SetContextDataEx(hActiveThread, UE_EIP, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_EIP) & 0xFFFFFF00)); if(scmp(string, "dr0")) return SetContextDataEx(hActiveThread, UE_DR0, value); if(scmp(string, "dr1")) return SetContextDataEx(hActiveThread, UE_DR1, value); if(scmp(string, "dr2")) return SetContextDataEx(hActiveThread, UE_DR2, value); if(scmp(string, "dr3")) return SetContextDataEx(hActiveThread, UE_DR3, value); if(scmp(string, "dr6") || scmp(string, "dr4")) return SetContextDataEx(hActiveThread, UE_DR6, value); if(scmp(string, "dr7") || scmp(string, "dr5")) return SetContextDataEx(hActiveThread, UE_DR7, value); if(scmp(string, "cax")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RAX, value); #else return SetContextDataEx(hActiveThread, UE_EAX, value); #endif //_WIN64 if(scmp(string, "cbx")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RBX, value); #else return SetContextDataEx(hActiveThread, UE_EBX, value); #endif //_WIN64 if(scmp(string, "ccx")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RCX, value); #else return SetContextDataEx(hActiveThread, UE_ECX, value); #endif //_WIN64 if(scmp(string, "cdx")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RDX, value); #else return SetContextDataEx(hActiveThread, UE_EDX, value); #endif //_WIN64 if(scmp(string, "csi")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RSI, value); #else return SetContextDataEx(hActiveThread, UE_ESI, value); #endif //_WIN64 if(scmp(string, "cdi")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RDI, value); #else return SetContextDataEx(hActiveThread, UE_EDI, value); #endif //_WIN64 if(scmp(string, "cip")) return SetContextDataEx(hActiveThread, UE_CIP, value); if(scmp(string, "csp")) return SetContextDataEx(hActiveThread, UE_CSP, value); if(scmp(string, "cbp")) #ifdef _WIN64 return SetContextDataEx(hActiveThread, UE_RBP, value); #else return SetContextDataEx(hActiveThread, UE_EBP, value); #endif //_WIN64 if(scmp(string, "cflags")) return SetContextDataEx(hActiveThread, UE_CFLAGS, value); #ifdef _WIN64 if(scmp(string, "rax")) return SetContextDataEx(hActiveThread, UE_RAX, value); if(scmp(string, "rbx")) return SetContextDataEx(hActiveThread, UE_RBX, value); if(scmp(string, "rcx")) return SetContextDataEx(hActiveThread, UE_RCX, value); if(scmp(string, "rdx")) return SetContextDataEx(hActiveThread, UE_RDX, value); if(scmp(string, "rdi")) return SetContextDataEx(hActiveThread, UE_RDI, value); if(scmp(string, "rsi")) return SetContextDataEx(hActiveThread, UE_RSI, value); if(scmp(string, "rbp")) return SetContextDataEx(hActiveThread, UE_RBP, value); if(scmp(string, "rsp")) return SetContextDataEx(hActiveThread, UE_RSP, value); if(scmp(string, "rip")) return SetContextDataEx(hActiveThread, UE_RIP, value); if(scmp(string, "rflags")) return SetContextDataEx(hActiveThread, UE_RFLAGS, value); if(scmp(string, "r8")) return SetContextDataEx(hActiveThread, UE_R8, value); if(scmp(string, "r9")) return SetContextDataEx(hActiveThread, UE_R9, value); if(scmp(string, "r10")) return SetContextDataEx(hActiveThread, UE_R10, value); if(scmp(string, "r11")) return SetContextDataEx(hActiveThread, UE_R11, value); if(scmp(string, "r12")) return SetContextDataEx(hActiveThread, UE_R12, value); if(scmp(string, "r13")) return SetContextDataEx(hActiveThread, UE_R13, value); if(scmp(string, "r14")) return SetContextDataEx(hActiveThread, UE_R14, value); if(scmp(string, "r15")) return SetContextDataEx(hActiveThread, UE_R15, value); if(scmp(string, "r8d")) return SetContextDataEx(hActiveThread, UE_R8, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R8) & 0xFFFFFFFF00000000)); if(scmp(string, "r9d")) return SetContextDataEx(hActiveThread, UE_R9, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R9) & 0xFFFFFFFF00000000)); if(scmp(string, "r10d")) return SetContextDataEx(hActiveThread, UE_R10, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R10) & 0xFFFFFFFF00000000)); if(scmp(string, "r11d")) return SetContextDataEx(hActiveThread, UE_R11, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R11) & 0xFFFFFFFF00000000)); if(scmp(string, "r12d")) return SetContextDataEx(hActiveThread, UE_R12, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R12) & 0xFFFFFFFF00000000)); if(scmp(string, "r13d")) return SetContextDataEx(hActiveThread, UE_R13, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R13) & 0xFFFFFFFF00000000)); if(scmp(string, "r14d")) return SetContextDataEx(hActiveThread, UE_R14, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R14) & 0xFFFFFFFF00000000)); if(scmp(string, "r15d")) return SetContextDataEx(hActiveThread, UE_R15, (value & 0xFFFFFFFF) | (GetContextDataEx(hActiveThread, UE_R15) & 0xFFFFFFFF00000000)); if(scmp(string, "r8w")) return SetContextDataEx(hActiveThread, UE_R8, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R8) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r9w")) return SetContextDataEx(hActiveThread, UE_R9, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R9) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r10w")) return SetContextDataEx(hActiveThread, UE_R10, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R10) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r11w")) return SetContextDataEx(hActiveThread, UE_R11, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R11) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r12w")) return SetContextDataEx(hActiveThread, UE_R12, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R12) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r13w")) return SetContextDataEx(hActiveThread, UE_R13, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R13) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r14w")) return SetContextDataEx(hActiveThread, UE_R14, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R14) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r15w")) return SetContextDataEx(hActiveThread, UE_R15, (value & 0xFFFF) | (GetContextDataEx(hActiveThread, UE_R15) & 0xFFFFFFFFFFFF0000)); if(scmp(string, "r8b")) return SetContextDataEx(hActiveThread, UE_R8, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R8) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r9b")) return SetContextDataEx(hActiveThread, UE_R9, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R9) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r10b")) return SetContextDataEx(hActiveThread, UE_R10, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R10) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r11b")) return SetContextDataEx(hActiveThread, UE_R11, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R11) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r12b")) return SetContextDataEx(hActiveThread, UE_R12, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R12) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r13b")) return SetContextDataEx(hActiveThread, UE_R13, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R13) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r14b")) return SetContextDataEx(hActiveThread, UE_R14, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R14) & 0xFFFFFFFFFFFFFF00)); if(scmp(string, "r15b")) return SetContextDataEx(hActiveThread, UE_R15, (value & 0xFF) | (GetContextDataEx(hActiveThread, UE_R15) & 0xFFFFFFFFFFFFFF00)); #endif // _WIN64 return false; } /** \brief Gets the address of an API from a name. \param name The name of the API, see the command help for more information about valid constructions. \param [out] value The address of the retrieved API. Cannot be null. \param silent true to have no console output. \return true if the API was found and a value retrieved, false otherwise. */ bool valapifromstring(const char* name, duint* value, bool silent) { if(!value || !DbgIsDebugging()) return false; //explicit API handling 'module:export' const char* apiname = strchr(name, ':'); //the ':' character cannot be in a path: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions bool resolveForwards = true; if(!apiname) //not found { apiname = strstr(name, "..") ? strchr(name, '.') : strrchr(name, '.'); //kernel32.GetProcAddress support if(!apiname) //not found { apiname = strchr(name, '?'); //the '?' character cannot be in a path either resolveForwards = false; } } if(apiname) { char modname[MAX_MODULE_SIZE] = ""; if(name == apiname) //:[expression] <= currently selected module { SELECTIONDATA seldata; memset(&seldata, 0, sizeof(seldata)); GuiSelectionGet(GUI_DISASSEMBLY, &seldata); if(!ModNameFromAddr(seldata.start, modname, true)) return false; } else { strncpy_s(modname, name, _TRUNCATE); auto idx = apiname - name; if(idx < _countof(modname)) modname[idx] = '\0'; } apiname++; if(!strlen(apiname)) return false; SHARED_ACQUIRE(LockModules); duint modbase = ModBaseFromName(modname); auto modInfo = ModInfoFromAddr(modbase); if(modInfo == nullptr) return false; duint addr = resolveForwards ? modInfo->getProcAddress(apiname) : 0; if(addr != 0) { *value = addr; return true; } if(scmp(apiname, "base") || scmp(apiname, "imagebase") || scmp(apiname, "header")) //get loaded base addr = modbase; else if(scmp(apiname, "entrypoint") || scmp(apiname, "entry") || scmp(apiname, "oep") || scmp(apiname, "ep")) //get entry point addr = modInfo->entry; else if(*apiname == '$') //RVA { duint rva; if(valfromstring(apiname + 1, &rva)) addr = modbase + rva; } else if(*apiname == '#') //File Offset { duint offset; if(valfromstring(apiname + 1, &offset)) addr = valfileoffsettova(modname, offset); } else { if(!resolveForwards) //get the exported functions with the '?' delimiter { addr = modInfo->getProcAddress(apiname, 0); } else { // module:ordinal duint ordinal; auto radix = 16; if(*apiname == '.') //decimal radix = 10, apiname++; if(convertNumber(apiname, ordinal, radix) && ordinal <= 0xFFFF) { auto index = ordinal - modInfo->exportOrdinalBase; if(index < modInfo->exports.size()) //found exported function addr = modbase + modInfo->exports[index].rva; else if(ordinal == 0) //support for getting the image base using <modname>:0 addr = modbase; } } } if(addr == 0) return false; *value = addr; return true; } else { // enumerate all modules and look for the export by name size_t kernel32 = -1; std::vector<duint> addrfound; ModEnum([&](const MODINFO & info) { duint funcAddress = info.getProcAddress(name); if(funcAddress != 0) { if(std::find(addrfound.begin(), addrfound.end(), funcAddress) == addrfound.end()) { if(scmp(info.name, "kernel32") && scmp(info.extension, ".dll")) kernel32 = addrfound.size(); addrfound.push_back(funcAddress); } } }); if(addrfound.empty()) return false; // prioritize kernel32 exports if(kernel32 != -1) std::swap(addrfound[0], addrfound[kernel32]); *value = addrfound[0]; if(!silent) { // print the other exports we found to the log for(size_t i = 1; i < addrfound.size(); i++) { auto symbolicName = SymGetSymbolicName(addrfound[i], false); dprintf_untranslated("%p %s\n", addrfound[i], symbolicName.c_str()); } } } return true; } /** \brief Check if a string is a valid decimal number. This function also accepts "-" or "." as prefix. \param string The string to check. \return true if the string is a valid decimal number. */ static bool isdecnumber(const char* string) { if(*string != '.' || !string[1]) //dec indicator/no number return false; int decAdd = 1; if(string[1] == '-') //minus { if(!string[2]) //no number return false; decAdd++; } int len = (int)strlen(string + decAdd); for(int i = 0; i < len; i++) if(!isdigit(string[i + decAdd])) return false; return true; } /** \brief Check if a string is a valid hexadecimal number. This function also accepts "0x" or "x" as prefix. \param string The string to check. \return true if the string is a valid hexadecimal number. */ static bool ishexnumber(const char* string) { int add = 0; if(*string == '0' && string[1] == 'x') //0x prefix add = 2; else if(*string == 'x') //hex indicator add = 1; if(!string[add]) //only an indicator, no number return false; int len = (int)strlen(string + add); for(int i = 0; i < len; i++) if(!isxdigit(string[i + add])) //all must be hex digits return false; return true; } bool convertNumber(const char* str, duint & result, int radix) { unsigned long long llr; if(!convertLongLongNumber(str, llr, radix)) return false; result = duint(llr); return true; } bool convertLongLongNumber(const char* str, unsigned long long & result, int radix) { errno = 0; char* end; result = strtoull(str, &end, radix); if(!result && end == str) return false; if(result == ULLONG_MAX && errno) return false; if(*end) return false; return true; } /** \brief Check if a character is a valid hexadecimal digit that is smaller than the size of a pointer. \param digit The character to check. \return true if the character is a valid hexadecimal digit. */ static bool isdigitduint(char digit) { #ifdef _WIN64 return digit >= '1' && digit <= '8'; #else //x86 return digit >= '1' && digit <= '4'; #endif //_WIN64 } /** \brief Gets a value from a string. This function can parse expressions, memory locations, registers, flags, API names, labels, symbols and variables. \param string The string to parse. \param [out] value The value of the expression. This value cannot be null. \param silent true to not output anything to the console. \param baseonly true to skip parsing API names, labels and symbols (basic expressions only). \param [out] value_size This function can output the value size parsed (for example memory location size or register size). Can be null. \param [out] isvar This function can output if the expression is variable (for example memory locations, registers or variables are variable). Can be null. \param [out] hexonly This function can output if the output value should only be printed as hexadecimal (for example addresses). Can be null. \return true if the expression was parsed successful, false otherwise. */ bool valfromstring_noexpr(const char* string, duint* value, bool silent, bool baseonly, int* value_size, bool* isvar, bool* hexonly) { if(!value || !string || !*string) return false; if(string[0] == '[' || (isdigitduint(string[0]) && string[1] == ':' && string[2] == '[') || (string[1] == 's' && (string[0] == 'c' || string[0] == 'd' || string[0] == 'e' || string[0] == 'f' || string[0] == 'g' || string[0] == 's') && string[2] == ':' && string[3] == '[') //memory location || strstr(string, "byte:[") || strstr(string, "word:[") ) { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging")); *value = 0; if(value_size) *value_size = 0; if(isvar) *isvar = true; return true; } int len = (int)strlen(string); int read_size = sizeof(duint); int prefix_size = 1; size_t seg_offset = 0; if(string[1] == ':') //n:[ (number of bytes to read) { prefix_size = 3; int new_size = string[0] - '0'; if(new_size < read_size) read_size = new_size; } else if(string[1] == 's' && string[2] == ':') { prefix_size = 4; if(string[0] == 'f') // fs:[...] { // TODO: get real segment offset instead of assuming them #ifdef _WIN64 seg_offset = 0; #else //x86 seg_offset = (size_t)GetTEBLocation(hActiveThread); #endif //_WIN64 } else if(string[0] == 'g') // gs:[...] { #ifdef _WIN64 seg_offset = (size_t)GetTEBLocation(hActiveThread); #else //x86 seg_offset = 0; #endif //_WIN64 } } else if(string[0] == 'b' && string[1] == 'y' && string[2] == 't' && string[3] == 'e' && string[4] == ':' ) // byte:[...] { prefix_size = 6; int new_size = 1; if(new_size < read_size) read_size = new_size; } else if(string[0] == 'w' && string[1] == 'o' && string[2] == 'r' && string[3] == 'd' && string[4] == ':' ) // word:[...] { prefix_size = 6; int new_size = 2; if(new_size < read_size) read_size = new_size; } else if(string[0] == 'd' && string[1] == 'w' && string[2] == 'o' && string[3] == 'r' && string[4] == 'd' && string[5] == ':' ) // dword:[...] { prefix_size = 7; int new_size = 4; if(new_size < read_size) read_size = new_size; } #ifdef _WIN64 else if(string[0] == 'q' && string[1] == 'w' && string[2] == 'o' && string[3] == 'r' && string[4] == 'd' && string[5] == ':' ) // qword:[...] { prefix_size = 7; int new_size = 8; if(new_size < read_size) read_size = new_size; } #endif //_WIN64 String ptrstring; for(auto i = prefix_size, depth = 1; i < len; i++) { if(string[i] == '[') depth++; else if(string[i] == ']') { depth--; if(!depth) break; } ptrstring += string[i]; } if(!valfromstring(ptrstring.c_str(), value, silent)) { if(!silent) dprintf(QT_TRANSLATE_NOOP("DBG", "valfromstring_noexpr failed on %s\n"), ptrstring.c_str()); return false; } duint addr = *value; *value = 0; if(!MemRead(addr + seg_offset, value, read_size)) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Failed to read memory")); return false; } if(value_size) *value_size = read_size; if(isvar) *isvar = true; return true; } else if(varget(string, value, value_size, 0)) //then come variables { if(isvar) *isvar = true; return true; } else if(isregister(string)) //register { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging!")); *value = 0; if(value_size) *value_size = 0; if(isvar) *isvar = true; return true; } *value = getregister(value_size, string); if(isvar) *isvar = true; return true; } else if(*string == '_' && isflag(string + 1)) //flag { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging")); *value = 0; if(value_size) *value_size = 0; if(isvar) *isvar = true; return true; } duint eflags = GetContextDataEx(hActiveThread, UE_CFLAGS); if(valflagfromstring(eflags, string + 1)) *value = 1; else *value = 0; if(value_size) *value_size = 0; if(isvar) *isvar = true; return true; } else if(isdecnumber(string)) //decimal numbers come 'first' { if(value_size) *value_size = 0; if(isvar) *isvar = false; return convertNumber(string + 1, *value, 10); } else if(ishexnumber(string)) //then hex numbers { if(value_size) *value_size = 0; if(isvar) *isvar = false; //hexadecimal value int inc = 0; if(*string == 'x') inc = 1; return convertNumber(string + inc, *value, 16); } if(isvar) *isvar = false; if(hexonly) *hexonly = true; if(value_size) *value_size = sizeof(duint); if(ConstantFromName(string, *value)) return true; PLUG_CB_VALFROMSTRING info; info.string = string; info.value = 0; info.value_size = value_size; info.isvar = isvar; info.hexonly = hexonly; info.retval = false; plugincbcall(CB_VALFROMSTRING, &info); if(info.retval) { *value = info.value; return true; } if(baseonly) return false; if(valapifromstring(string, value, silent)) //then come APIs return true; else if(LabelFromString(string, value)) //then come labels return true; else if(SymAddrFromName(string, value)) //then come symbols return true; else if(strstr(string, "sub_") == string) //then come sub_ functions { #ifdef _WIN64 bool result = sscanf_s(string, "sub_%llX", value) == 1; #else //x86 bool result = sscanf_s(string, "sub_%X", value) == 1; #endif //_WIN64 duint start; return result && FunctionGet(*value, &start, nullptr) && *value == start; } else if(*value = ModBaseFromName(string)) // then come modules return true; if(!silent) dprintf(QT_TRANSLATE_NOOP("DBG", "Invalid value: \"%s\"!\n"), string); return false; //nothing was OK } /** \brief Gets a value from a string. This function can parse expressions, memory locations, registers, flags, API names, labels, symbols and variables. \param string The string to parse. \param [out] value The value of the expression. This value cannot be null. When the expression is invalid, value is not changed. \param silent true to not output anything to the console. \param baseonly true to skip parsing API names, labels, symbols and variables (basic expressions only). \param [out] value_size This function can output the value size parsed (for example memory location size or register size). Can be null. \param [out] isvar This function can output if the expression is variable (for example memory locations, registers or variables are variable). Can be null. \param [out] hexonly This function can output if the output value should only be printed as hexadecimal (for example addresses). Can be null. \return true if the expression was parsed successful, false otherwise. */ bool valfromstring(const char* string, duint* value, bool silent, bool baseonly, int* value_size, bool* isvar, bool* hexonly, bool allowassign) { if(!value || !string) return false; if(!*string) { *value = 0; return true; } ExpressionParser parser(string); duint result; if(!parser.Calculate(result, valuesignedcalc(), allowassign, silent, baseonly, value_size, isvar, hexonly)) return false; *value = result; return true; } /** \brief Checks if a string is long enough. \param str The string to check. \param min_length The minimum length of \p str. \return true if the string is long enough, false otherwise. */ static bool longEnough(const char* str, size_t min_length) { size_t length = 0; while(length < min_length && str[length]) length++; if(length == min_length) return true; return false; } /** \brief Checks if a string starts with another string. \param pre The desired prefix of the string. \param str The complete string. \return true if \p str starts with \p pre. */ static bool startsWith(const char* pre, const char* str) { size_t lenpre = strlen(pre); return longEnough(str, lenpre) ? _strnicmp(str, pre, (int) lenpre) == 0 : false; } #define MxCsr_PRE_FIELD_STRING "MxCsr_" #define x87SW_PRE_FIELD_STRING "x87SW_" #define x87CW_PRE_FIELD_STRING "x87CW_" #define x87TW_PRE_FIELD_STRING "x87TW_" #define MMX_PRE_FIELD_STRING "MM" #define XMM_PRE_FIELD_STRING "XMM" #define YMM_PRE_FIELD_STRING "YMM" #define x8780BITFPU_PRE_FIELD_STRING "x87r" #define x8780BITFPU_PRE_FIELD_STRING_ST "st" #define STRLEN_USING_SIZEOF(string) (sizeof(string) - 1) /** \brief Sets an FPU value (MXCSR fields, MMX fields, etc.) by name. \param string The name of the FPU value to set. \param value The value to set. */ static void setfpuvalue(const char* string, duint value) { duint xorval = 0; duint flags = 0; duint flag = 0; bool set = false; if(value) set = true; if(startsWith(MxCsr_PRE_FIELD_STRING, string)) { if(_strnicmp(string + STRLEN_USING_SIZEOF(MxCsr_PRE_FIELD_STRING), "RC", (int)strlen("RC")) == 0) { flags = GetContextDataEx(hActiveThread, UE_MXCSR); int i = 3; i <<= 13; flags &= ~i; value <<= 13; flags |= value; SetContextDataEx(hActiveThread, UE_MXCSR, flags); } else { flags = GetContextDataEx(hActiveThread, UE_MXCSR); flag = getmxcsrflagfromstring(string + STRLEN_USING_SIZEOF(MxCsr_PRE_FIELD_STRING)); if(flags & flag && !set) xorval = flag; else if(set) xorval = flag; SetContextDataEx(hActiveThread, UE_MXCSR, flags ^ xorval); } } else if(startsWith(x87TW_PRE_FIELD_STRING, string)) { unsigned int i; string += STRLEN_USING_SIZEOF(x87TW_PRE_FIELD_STRING); i = atoi(string); if(i > 7) return; flags = GetContextDataEx(hActiveThread, UE_X87_TAGWORD); flag = 3; flag <<= i * 2; flags &= ~flag; flag = value; flag <<= i * 2; flags |= flag; SetContextDataEx(hActiveThread, UE_X87_TAGWORD, (unsigned short) flags); } else if(startsWith(x87SW_PRE_FIELD_STRING, string)) { if(_strnicmp(string + STRLEN_USING_SIZEOF(x87SW_PRE_FIELD_STRING), "TOP", (int)strlen("TOP")) == 0) { flags = GetContextDataEx(hActiveThread, UE_X87_STATUSWORD); int i = 7; i <<= 11; flags &= ~i; value <<= 11; flags |= value; SetContextDataEx(hActiveThread, UE_X87_STATUSWORD, flags); } else { flags = GetContextDataEx(hActiveThread, UE_X87_STATUSWORD); flag = getx87statuswordflagfromstring(string + STRLEN_USING_SIZEOF(x87SW_PRE_FIELD_STRING)); if(flags & flag && !set) xorval = flag; else if(set) xorval = flag; SetContextDataEx(hActiveThread, UE_X87_STATUSWORD, flags ^ xorval); } } else if(startsWith(x87CW_PRE_FIELD_STRING, string)) { if(_strnicmp(string + STRLEN_USING_SIZEOF(x87CW_PRE_FIELD_STRING), "RC", (int)strlen("RC")) == 0) { flags = GetContextDataEx(hActiveThread, UE_X87_CONTROLWORD); int i = 3; i <<= 10; flags &= ~i; value <<= 10; flags |= value; SetContextDataEx(hActiveThread, UE_X87_CONTROLWORD, flags); } else if(_strnicmp(string + STRLEN_USING_SIZEOF(x87CW_PRE_FIELD_STRING), "PC", (int)strlen("PC")) == 0) { flags = GetContextDataEx(hActiveThread, UE_X87_CONTROLWORD); int i = 3; i <<= 8; flags &= ~i; value <<= 8; flags |= value; SetContextDataEx(hActiveThread, UE_X87_CONTROLWORD, flags); } else { flags = GetContextDataEx(hActiveThread, UE_X87_CONTROLWORD); flag = getx87controlwordflagfromstring(string + STRLEN_USING_SIZEOF(x87CW_PRE_FIELD_STRING)); if(flags & flag && !set) xorval = flag; else if(set) xorval = flag; SetContextDataEx(hActiveThread, UE_X87_CONTROLWORD, flags ^ xorval); } } else if(_strnicmp(string, "x87TagWord", (int)strlen(string)) == 0) { SetContextDataEx(hActiveThread, UE_X87_TAGWORD, (unsigned short) value); } else if(_strnicmp(string, "x87StatusWord", (int)strlen(string)) == 0) { SetContextDataEx(hActiveThread, UE_X87_STATUSWORD, (unsigned short) value); } else if(_strnicmp(string, "x87ControlWord", (int)strlen(string)) == 0) { SetContextDataEx(hActiveThread, UE_X87_CONTROLWORD, (unsigned short) value); } else if(_strnicmp(string, "MxCsr", (int)strlen(string)) == 0) { SetContextDataEx(hActiveThread, UE_MXCSR, value); } else if(startsWith(x8780BITFPU_PRE_FIELD_STRING, string)) { string += STRLEN_USING_SIZEOF(x8780BITFPU_PRE_FIELD_STRING); DWORD registerindex; bool found = true; switch(*string) { case '0': registerindex = UE_x87_r0; break; case '1': registerindex = UE_x87_r1; break; case '2': registerindex = UE_x87_r2; break; case '3': registerindex = UE_x87_r3; break; case '4': registerindex = UE_x87_r4; break; case '5': registerindex = UE_x87_r5; break; case '6': registerindex = UE_x87_r6; break; case '7': registerindex = UE_x87_r7; break; default: found = false; break; } if(found) SetContextDataEx(hActiveThread, registerindex, value); } else if(startsWith(x8780BITFPU_PRE_FIELD_STRING_ST, string)) { flags = GetContextDataEx(hActiveThread, UE_X87_STATUSWORD); flags >>= 11; flags &= 7; string += STRLEN_USING_SIZEOF(x8780BITFPU_PRE_FIELD_STRING_ST); bool found = true; DWORD registerindex; switch(*string) { case '0': registerindex = (DWORD)flags; break; case '1': registerindex = ((1 + flags) & 7); break; case '2': registerindex = ((2 + flags) & 7); break; case '3': registerindex = ((3 + flags) & 7); break; case '4': registerindex = ((4 + flags) & 7); break; case '5': registerindex = ((5 + flags) & 7); break; case '6': registerindex = ((6 + flags) & 7); break; case '7': registerindex = ((7 + flags) & 7); break; default: found = false; break; } if(found) { registerindex += UE_x87_r0; SetContextDataEx(hActiveThread, registerindex, value); } } else if(startsWith(MMX_PRE_FIELD_STRING, string)) { string += STRLEN_USING_SIZEOF(MMX_PRE_FIELD_STRING); DWORD registerindex; bool found = true; switch(*string) { case '0': registerindex = UE_MMX0; break; case '1': registerindex = UE_MMX1; break; case '2': registerindex = UE_MMX2; break; case '3': registerindex = UE_MMX3; break; case '4': registerindex = UE_MMX4; break; case '5': registerindex = UE_MMX5; break; case '6': registerindex = UE_MMX6; break; case '7': registerindex = UE_MMX7; break; default: found = false; break; } if(found) SetContextDataEx(hActiveThread, registerindex, value); } else if(startsWith(XMM_PRE_FIELD_STRING, string)) { string += STRLEN_USING_SIZEOF(XMM_PRE_FIELD_STRING); DWORD registerindex; bool found = true; registerindex = atoi(string); if(registerindex < ArchValue(8, 16)) { registerindex += UE_XMM0; } else { found = false; } if(found) SetContextDataEx(hActiveThread, registerindex, value); } else if(startsWith(YMM_PRE_FIELD_STRING, string)) { string += STRLEN_USING_SIZEOF(YMM_PRE_FIELD_STRING); DWORD registerindex; bool found = true; switch(atoi(string)) { case 0: registerindex = UE_YMM0; break; case 1: registerindex = UE_YMM1; break; case 2: registerindex = UE_YMM2; break; case 3: registerindex = UE_YMM3; break; case 4: registerindex = UE_YMM4; break; case 5: registerindex = UE_YMM5; break; case 6: registerindex = UE_YMM6; break; case 7: registerindex = UE_YMM7; break; #ifdef _WIN64 case 8: registerindex = UE_YMM8; break; case 9: registerindex = UE_YMM9; break; case 10: registerindex = UE_YMM10; break; case 11: registerindex = UE_YMM11; break; case 12: registerindex = UE_YMM12; break; case 13: registerindex = UE_YMM13; break; case 14: registerindex = UE_YMM14; break; case 15: registerindex = UE_YMM15; break; #endif default: registerindex = 0; found = false; break; } if(found) SetContextDataEx(hActiveThread, registerindex, value); } } /** \brief Sets a register, variable, flag, memory location or FPU value by name. \param string The name of the thing to set. \param value The value to set. \param silent true to not have output to the console. \return true if the value was set successfully, false otherwise. */ bool valtostring(const char* string, duint value, bool silent) { if(!*string) return false; if(string[0] == '[' || (isdigitduint(string[0]) && string[1] == ':' && string[2] == '[') || (string[1] == 's' && (string[0] == 'c' || string[0] == 'd' || string[0] == 'e' || string[0] == 'f' || string[0] == 'g' || string[0] == 's') && string[2] == ':' && string[3] == '[') //memory location || strstr(string, "byte:[") || strstr(string, "word:[") ) { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging")); return false; } int len = (int)strlen(string); int read_size = sizeof(duint); int prefix_size = 1; size_t seg_offset = 0; if(string[1] == ':') //n:[ (number of bytes to read) { prefix_size = 3; int new_size = string[0] - '0'; if(new_size < read_size) read_size = new_size; } else if(string[1] == 's' && string[2] == ':') { prefix_size = 4; if(string[0] == 'f') // fs:[...] { // TODO: get real segment offset instead of assuming them #ifdef _WIN64 seg_offset = 0; #else //x86 seg_offset = (size_t)GetTEBLocation(hActiveThread); #endif //_WIN64 } else if(string[0] == 'g') // gs:[...] { #ifdef _WIN64 seg_offset = (size_t)GetTEBLocation(hActiveThread); #else //x86 seg_offset = 0; #endif //_WIN64 } } else if(string[0] == 'b' && string[1] == 'y' && string[2] == 't' && string[3] == 'e' && string[4] == ':' ) // byte:[...] { prefix_size = 6; int new_size = 1; if(new_size < read_size) read_size = new_size; } else if(string[0] == 'w' && string[1] == 'o' && string[2] == 'r' && string[3] == 'd' && string[4] == ':' ) // word:[...] { prefix_size = 6; int new_size = 2; if(new_size < read_size) read_size = new_size; } else if(string[0] == 'd' && string[1] == 'w' && string[2] == 'o' && string[3] == 'r' && string[4] == 'd' && string[5] == ':' ) // dword:[...] { prefix_size = 7; int new_size = 4; if(new_size < read_size) read_size = new_size; } #ifdef _WIN64 else if(string[0] == 'q' && string[1] == 'w' && string[2] == 'o' && string[3] == 'r' && string[4] == 'd' && string[5] == ':' ) // qword:[...] { prefix_size = 7; int new_size = 8; if(new_size < read_size) read_size = new_size; } #endif //_WIN64 String ptrstring; for(auto i = prefix_size, depth = 1; i < len; i++) { if(string[i] == '[') depth++; else if(string[i] == ']') { depth--; if(!depth) break; } ptrstring += string[i]; } duint temp; if(!valfromstring(ptrstring.c_str(), &temp, silent)) return false; duint value_ = value; if(!MemPatch(temp + seg_offset, &value_, read_size)) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Failed to write memory")); return false; } GuiUpdateAllViews(); //repaint gui GuiUpdatePatches(); //update patch dialog return true; } else if(isregister(string)) //register { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging!")); return false; } bool ok = setregister(string, value); int len = (int)strlen(string); Memory<char*> regName(len + 1, "valtostring:regname"); strcpy_s(regName(), len + 1, string); _strlwr_s(regName(), regName.size()); if(strstr(regName(), "ip")) { auto cip = GetContextDataEx(hActiveThread, UE_CIP); dbgtraceexecute(cip); DebugUpdateGuiAsync(cip, false); //update disassembly + register view } else if(strstr(regName(), "sp")) //update stack { duint csp = GetContextDataEx(hActiveThread, UE_CSP); DebugUpdateStack(csp, csp); GuiUpdateRegisterView(); } else GuiUpdateAllViews(); //repaint gui return ok; } else if(*string == '_' && isflag(string + 1)) //flag { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging")); return false; } bool set = false; if(value) set = true; setflag(string + 1, set); GuiUpdateAllViews(); //repaint gui return true; } else if((*string == '_')) //FPU values { if(!DbgIsDebugging()) { if(!silent) dputs(QT_TRANSLATE_NOOP("DBG", "Not debugging!")); return false; } setfpuvalue(string + 1, value); GuiUpdateAllViews(); //repaint gui return true; } PLUG_CB_VALTOSTRING info; info.string = string; info.value = value; info.retval = false; plugincbcall(CB_VALTOSTRING, &info); if(info.retval) return true; return varset(string, value, false); //variable } /** \brief Converts a file offset to a virtual address. \param modname The name (not the path) of the module the file offset is in. \param offset The file offset. \return The VA of the file offset, 0 when there was a problem with the conversion. */ duint valfileoffsettova(const char* modname, duint offset) { SHARED_ACQUIRE(LockModules); const auto modInfo = ModInfoFromAddr(ModBaseFromName(modname)); if(modInfo && modInfo->fileMapVA) { ULONGLONG rva = ConvertFileOffsetToVA(modInfo->fileMapVA, //FileMapVA modInfo->fileMapVA + (ULONG_PTR)offset, //Offset inside FileMapVA false); //Return without ImageBase return offset < modInfo->loadedSize ? (duint)rva + ModBaseFromName(modname) : 0; } return 0; } /** \brief Converts a virtual address to a file offset. \param va The virtual address (must be inside a module). \return The file offset. 0 when there was a problem with the conversion. */ duint valvatofileoffset(duint va) { SHARED_ACQUIRE(LockModules); const auto modInfo = ModInfoFromAddr(va); if(modInfo && modInfo->fileMapVA) { ULONGLONG offset = ConvertVAtoFileOffsetEx(modInfo->fileMapVA, modInfo->loadedSize, 0, va - modInfo->base, true, false); return (duint)offset; } return 0; }
C/C++
x64dbg-development/src/dbg/value.h
#ifndef _VALUE_H #define _VALUE_H #include "_global.h" //functions bool valuesignedcalc(); void valuesetsignedcalc(bool a); bool valapifromstring(const char* name, duint* value, bool silent); bool convertNumber(const char* str, duint & result, int radix); bool convertLongLongNumber(const char* str, unsigned long long & result, int radix); bool valfromstring_noexpr(const char* string, duint* value, bool silent = true, bool baseonly = false, int* value_size = nullptr, bool* isvar = nullptr, bool* hexonly = nullptr); bool valfromstring(const char* string, duint* value, bool silent = true, bool baseonly = false, int* value_size = nullptr, bool* isvar = nullptr, bool* hexonly = nullptr, bool allowassign = false); bool valflagfromstring(duint eflags, const char* string); bool valtostring(const char* string, duint value, bool silent); bool valmxcsrflagfromstring(duint mxcsrflags, const char* string); bool valx87statuswordflagfromstring(duint statusword, const char* string); bool valx87controlwordflagfromstring(duint controlword, const char* string); unsigned short valmxcsrfieldfromstring(duint mxcsrflags, const char* string); unsigned short valx87statuswordfieldfromstring(duint statusword, const char* string); unsigned short valx87controlwordfieldfromstring(duint controlword, const char* string); duint valfileoffsettova(const char* modname, duint offset); duint valvatofileoffset(duint va); bool setregister(const char* string, duint value); bool setflag(const char* string, bool set); duint getregister(int* size, const char* string); #endif // _VALUE_H
C++
x64dbg-development/src/dbg/variable.cpp
/** @file variable.cpp @brief Implements the variable class. */ #include "variable.h" #include "threading.h" #include <map> /** \brief The container that stores all variables. */ std::map<String, VAR, CaseInsensitiveCompare> variables; /** \brief Sets a variable with a value. \param [in,out] Var The variable to set the value of. The previous value will be freed. Cannot be null. \param [in] Value The new value. Cannot be null. */ void varsetvalue(VAR* Var, VAR_VALUE* Value) { // VAR_STRING needs to be freed before destroying it if(Var->value.type == VAR_STRING) delete Var->value.u.data; // Replace all information in the struct memcpy(&Var->value, Value, sizeof(VAR_VALUE)); } /** \brief Sets a variable by name. \param Name The name of the variable. Cannot be null. \param Value The new value. Cannot be null. \param ReadOnly true to set read-only variables (like $hProcess etc.). \return true if the variable was set correctly, false otherwise. */ bool varset(const char* Name, VAR_VALUE* Value, bool ReadOnly) { EXCLUSIVE_ACQUIRE(LockVariables); String name_; if(*Name != '$') name_ = "$"; name_ += Name; auto found = variables.find(name_); if(found == variables.end()) //not found return false; if(found->second.alias.length()) return varset(found->second.alias.c_str(), Value, ReadOnly); if(!ReadOnly && (found->second.type == VAR_READONLY || found->second.type == VAR_HIDDEN)) return false; varsetvalue(&found->second, Value); return true; } /** \brief Initializes various default variables. */ void varinit() { varfree(); // General variables varnew("$result\1$res", 0, VAR_SYSTEM); varnew("$result1\1$res1", 0, VAR_SYSTEM); varnew("$result2\1$res2", 0, VAR_SYSTEM); varnew("$result3\1$res3", 0, VAR_SYSTEM); varnew("$result4\1$res4", 0, VAR_SYSTEM); varnew("$__disasm_refindex", 0, VAR_SYSTEM); varnew("$__dump_refindex", 0, VAR_SYSTEM); // InitDebug variables varnew("$hProcess\1$hp", 0, VAR_READONLY); // Process handle varnew("$pid", 0, VAR_READONLY); // Process ID // Hidden variables varnew("$ans\1$an", 0, VAR_HIDDEN); // Breakpoint variables varnew("$breakpointcounter", 0, VAR_READONLY); varnew("$breakpointcondition", 0, VAR_SYSTEM); varnew("$breakpointlogcondition", 0, VAR_READONLY); varnew("$breakpointexceptionaddress", 0, VAR_READONLY); // Tracing variables varnew("$tracecounter", 0, VAR_READONLY); varnew("$tracecondition", 0, VAR_SYSTEM); varnew("$tracelogcondition", 0, VAR_READONLY); // Read-only variables varnew("$lastalloc", 0, VAR_READONLY); // Last memory allocation varnew("$_EZ_FLAG", 0, VAR_READONLY); // Equal/zero flag for internal use (1 = equal, 0 = unequal) varnew("$_BS_FLAG", 0, VAR_READONLY); // Bigger/smaller flag for internal use (1 = bigger, 0 = smaller) } /** \brief Clears all variables. */ void varfree() { EXCLUSIVE_ACQUIRE(LockVariables); // Each variable must be deleted manually; strings especially // because there are sub-allocations VAR_VALUE emptyValue; memset(&emptyValue, 0, sizeof(VAR_VALUE)); for(auto & itr : variables) varsetvalue(&itr.second, &emptyValue); // Now clear all vector elements variables.clear(); } /** \brief Creates a new variable. \param Name The name of the variable. You can specify alias names by separating the names by '\1'. Cannot be null. \param Value The new variable value. \param Type The variable type. \return true if the new variables was created and set successfully, false otherwise. */ bool varnew(const char* Name, duint Value, VAR_TYPE Type) { if(!Name) return false; EXCLUSIVE_ACQUIRE(LockVariables); std::vector<String> names = StringUtils::Split(Name, '\1'); String firstName; for(int i = 0; i < (int)names.size(); i++) { String name_; Name = names.at(i).c_str(); if(*Name == '$') { name_ = Name; } else { name_ = "$"; name_ += Name; } if(!i) firstName = name_; if(variables.find(name_) != variables.end()) //found return false; VAR var; var.name = name_; if(i) var.alias = firstName; var.type = Type; var.value.size = sizeof(duint); var.value.type = VAR_UINT; var.value.u.value = Value; variables.insert(std::make_pair(name_, var)); } return true; } /** \brief Gets a variable value. \param Name The name of the variable. \param [out] Value This function can get the variable value. If this value is null, it is ignored. \param [out] Size This function can get the variable size. If this value is null, it is ignored. \param [out] Type This function can get the variable type. If this value is null, it is ignored. \return true if the variable was found and the optional values were retrieved successfully, false otherwise. */ bool varget(const char* Name, VAR_VALUE* Value, int* Size, VAR_TYPE* Type) { SHARED_ACQUIRE(LockVariables); String name_; if(*Name == '$') { name_ = Name; } else { name_ = "$"; name_ += Name; } auto found = variables.find(name_); if(found == variables.end()) //not found return false; if(found->second.alias.length()) return varget(found->second.alias.c_str(), Value, Size, Type); if(Type) *Type = found->second.type; if(Size) *Size = found->second.value.size; if(Value) *Value = found->second.value; return true; } /** \brief Gets a variable value. \param Name The name of the variable. \param [out] Value This function can get the variable value. If this value is null, it is ignored. \param [out] Size This function can get the variable size. If this value is null, it is ignored. \param [out] Type This function can get the variable type. If this value is null, it is ignored. \return true if the variable was found and the optional values were retrieved successfully, false otherwise. */ bool varget(const char* Name, duint* Value, int* Size, VAR_TYPE* Type) { VAR_VALUE varvalue; int varsize; VAR_TYPE vartype; if(!varget(Name, &varvalue, &varsize, &vartype) || varvalue.type != VAR_UINT) return false; if(Size) *Size = varsize; if(Type) *Type = vartype; if(Value) *Value = varvalue.u.value; return true; } /** \brief Gets a variable value. \param Name The name of the variable. \param [out] String This function can get the variable value. If this value is null, it is ignored. \param [out] Size This function can get the variable size. If this value is null, it is ignored. \param [out] Type This function can get the variable type. If this value is null, it is ignored. \return true if the variable was found and the optional values were retrieved successfully, false otherwise. */ bool varget(const char* Name, char* String, int* Size, VAR_TYPE* Type) { VAR_VALUE varvalue; int varsize; VAR_TYPE vartype; if(!varget(Name, &varvalue, &varsize, &vartype) || varvalue.type != VAR_STRING) return false; if(Size) *Size = varsize; if(Type) *Type = vartype; if(String) memcpy(String, varvalue.u.data->data(), Size ? min(*Size, varsize) : varsize); return true; } /** \brief Sets a variable by name. \param Name The name of the variable. Cannot be null. \param Value The new value. \param ReadOnly true to set read-only variables (like $hProcess etc.). \return true if the variable was set successfully, false otherwise. */ bool varset(const char* Name, duint Value, bool ReadOnly) { // Insert variable as an unsigned integer VAR_VALUE varValue; varValue.size = sizeof(duint); varValue.type = VAR_UINT; varValue.u.value = Value; return varset(Name, &varValue, ReadOnly); } /** \brief Sets a variable by name. \param Name The name of the variable. Cannot be null. \param Value The new value. Cannot be null. \param ReadOnly true to set read-only variables (like $hProcess etc.). \return true if the variable was set successfully, false otherwise. */ bool varset(const char* Name, const char* Value, bool ReadOnly) { VAR_VALUE varValue; int stringLen = (int)strlen(Value); varValue.size = stringLen; varValue.type = VAR_STRING; varValue.u.data = new std::vector<unsigned char>; // Allocate space for the string varValue.u.data->resize(stringLen); // Copy directly to vector array memcpy(varValue.u.data->data(), Value, stringLen); // Try to register variable if(!varset(Name, &varValue, ReadOnly)) { delete varValue.u.data; return false; } return true; } /** \brief Deletes a variable. \param Name The name of the variable to delete. Cannot be null. \param DelSystem true to allow deleting system variables. \return 0 if the variable was deleted successfully, -1 when variable doesn't exist, -2 when a user could not delete a system variable, -3 when unknown reason caused a variable couldn't be deleted */ int vardel(const char* Name, bool DelSystem) { EXCLUSIVE_ACQUIRE(LockVariables); String name_; if(*Name != '$') name_ = "$"; name_ += Name; auto found = variables.find(name_); if(found == variables.end()) //not found return -1; if(found->second.alias.length()) { // Release the lock (potential deadlock here) EXCLUSIVE_RELEASE(); return vardel(found->second.alias.c_str(), DelSystem); } if(!DelSystem && found->second.type != VAR_USER) return -2; found = variables.begin(); String NameString(name_); bool deleted = false; while(found != variables.end()) { if(found->first == NameString || found->second.alias == NameString) { found = variables.erase(found); // Invalidate iterators deleted = true; } else found++; } return deleted ? 0 : -3; //We should have deleted a variable, failing at here is a bug } /** \brief Gets a variable type. \param Name The name of the variable. Cannot be null. \param [out] Type This function can retrieve the variable type. If null it is ignored. \param [out] ValueType This function can retrieve the variable value type. If null it is ignored. \return true if getting the type was successful, false otherwise. */ bool vargettype(const char* Name, VAR_TYPE* Type, VAR_VALUE_TYPE* ValueType) { SHARED_ACQUIRE(LockVariables); String name_; if(*Name != '$') name_ = "$"; name_ += Name; auto found = variables.find(name_); if(found == variables.end()) //not found return false; if(found->second.alias.length()) return vargettype(found->second.alias.c_str(), Type, ValueType); if(ValueType) *ValueType = found->second.value.type; if(Type) *Type = found->second.type; return true; } /** \brief Enumerates all variables. \param [in,out] List A pointer to place the variables in. If null, \p cbsize will be filled to the number of bytes required. \param [in,out] Size This function retrieves the number of bytes required to store all variables. Can be null if \p entries is not null. \return true if it succeeds, false if it fails. */ bool varenum(VAR* List, size_t* Size) { // A list or size must be requested if(!List && !Size) return false; SHARED_ACQUIRE(LockVariables); if(Size) { // Size requested, so return it *Size = variables.size() * sizeof(VAR); if(!List) return true; } // Fill out all list entries for(auto & itr : variables) { *List = VAR(itr.second); List++; } return true; }
C/C++
x64dbg-development/src/dbg/variable.h
#ifndef _VARIABLE_H #define _VARIABLE_H #include "_global.h" //enums enum VAR_TYPE { VAR_SYSTEM = 1, VAR_USER = 2, VAR_READONLY = 3, VAR_HIDDEN = 4 }; enum VAR_VALUE_TYPE { VAR_UINT, VAR_STRING, }; //structures struct VAR_VALUE { union { duint value = 0; std::vector<unsigned char>* data; } u; VAR_VALUE_TYPE type = VAR_UINT; int size = 0; }; struct VAR { String name; String alias; VAR_TYPE type = VAR_SYSTEM; VAR_VALUE value; }; struct CaseInsensitiveCompare { bool operator()(const String & str1, const String & str2) const { return _stricmp(str1.c_str(), str2.c_str()) < 0; } }; //functions void varsetvalue(VAR* Var, VAR_VALUE* Value); bool varset(const char* Name, VAR_VALUE* Value, bool ReadOnly); void varinit(); void varfree(); bool varnew(const char* Name, duint Value, VAR_TYPE Type); bool varget(const char* Name, VAR_VALUE* Value, int* Size, VAR_TYPE* Type); bool varget(const char* Name, duint* Value, int* Size, VAR_TYPE* Type); bool varget(const char* Name, char* String, int* Size, VAR_TYPE* Type); bool varset(const char* Name, duint Value, bool ReadOnly); bool varset(const char* Name, const char* Value, bool ReadOnly); int vardel(const char* Name, bool DelSystem); bool vargettype(const char* Name, VAR_TYPE* Type = nullptr, VAR_VALUE_TYPE* ValueType = nullptr); bool varenum(VAR* List, size_t* Size); #endif // _VARIABLE_H
C++
x64dbg-development/src/dbg/watch.cpp
#include "watch.h" #include "console.h" #include "threading.h" #include "debugger.h" #include "taskthread.h" #include <Windows.h> std::map<unsigned int, WatchExpr*> watchexpr; unsigned int idCounter = 1; WatchExpr::WatchExpr(const char* name, const char* expression, WATCHVARTYPE type) : expr(expression), haveCurrValue(false), varType(type), currValue(0), watchdogTriggered(false), watchWindow(0), watchdogMode(MODE_DISABLED) { if(!expr.IsValidExpression()) varType = WATCHVARTYPE::TYPE_INVALID; strcpy_s(this->WatchName, name); } duint WatchExpr::getIntValue() { duint origVal = currValue; if(varType == WATCHVARTYPE::TYPE_UINT || varType == WATCHVARTYPE::TYPE_INT || varType == WATCHVARTYPE::TYPE_FLOAT || varType == WATCHVARTYPE::TYPE_ASCII || varType == WATCHVARTYPE::TYPE_UNICODE) { duint val; bool ok = expr.Calculate(val, varType == WATCHVARTYPE::TYPE_INT, false); if(ok) { currValue = val; haveCurrValue = true; if(getType() != WATCHVARTYPE::TYPE_INVALID) { switch(getWatchdogMode()) { default: case WATCHDOGMODE::MODE_DISABLED: break; case WATCHDOGMODE::MODE_ISTRUE: if(currValue != 0) { duint cip = GetContextDataEx(hActiveThread, UE_CIP); dprintf(QT_TRANSLATE_NOOP("DBG", "Watchdog %s (expression \"%s\") is triggered at %p ! Original value: %p, New value: %p\n"), WatchName, getExpr().c_str(), cip, origVal, currValue); watchdogTriggered = 1; } break; case WATCHDOGMODE::MODE_ISFALSE: if(currValue == 0) { duint cip = GetContextDataEx(hActiveThread, UE_CIP); dprintf(QT_TRANSLATE_NOOP("DBG", "Watchdog %s (expression \"%s\") is triggered at %p ! Original value: %p, New value: %p\n"), WatchName, getExpr().c_str(), cip, origVal, currValue); watchdogTriggered = 1; } break; case WATCHDOGMODE::MODE_CHANGED: if(currValue != origVal || !haveCurrValue) { duint cip = GetContextDataEx(hActiveThread, UE_CIP); dprintf(QT_TRANSLATE_NOOP("DBG", "Watchdog %s (expression \"%s\") is triggered at %p ! Original value: %p, New value: %p\n"), WatchName, getExpr().c_str(), cip, origVal, currValue); watchdogTriggered = 1; } break; case WATCHDOGMODE::MODE_UNCHANGED: if(currValue == origVal || !haveCurrValue) { duint cip = GetContextDataEx(hActiveThread, UE_CIP); dprintf(QT_TRANSLATE_NOOP("DBG", "Watchdog %s (expression \"%s\") is triggered at %p ! Original value: %p, New value: %p\n"), WatchName, getExpr().c_str(), cip, origVal, currValue); watchdogTriggered = 1; } break; } } return val; } } currValue = 0; haveCurrValue = false; return 0; } bool WatchExpr::modifyExpr(const char* expression, WATCHVARTYPE type) { ExpressionParser b(expression); if(b.IsValidExpression()) { expr = b; varType = type; this->getIntValue(); haveCurrValue = false; return true; } else return false; } void WatchExpr::modifyName(const char* newName) { strcpy_s(WatchName, newName); } // Update GUI void GuiUpdateWatchViewAsync() { static TaskThread_<decltype(&GuiUpdateWatchView)> task(&GuiUpdateWatchView); task.WakeUp(); } // Global functions // Clear all watch void WatchClear() { if(!watchexpr.empty()) { for(auto i : watchexpr) delete i.second; watchexpr.clear(); } } unsigned int WatchAddExprUnlocked(const char* expr, WATCHVARTYPE type) { unsigned int newid = InterlockedExchangeAdd((volatile long*)&idCounter, 1); char DefaultName[MAX_WATCH_NAME_SIZE]; sprintf_s(DefaultName, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Watch %u")), newid); WatchExpr* newWatch = new WatchExpr(DefaultName, expr, type); auto temp = watchexpr.emplace(std::make_pair(newid, newWatch)); if(temp.second) { newWatch->getIntValue(); return newid; } else { delete newWatch; return 0; } } unsigned int WatchAddExpr(const char* expr, WATCHVARTYPE type) { EXCLUSIVE_ACQUIRE(LockWatch); unsigned int id = WatchAddExprUnlocked(expr, type); EXCLUSIVE_RELEASE(); GuiUpdateWatchView(); return id; } bool WatchModifyExpr(unsigned int id, const char* expr, WATCHVARTYPE type) { EXCLUSIVE_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) { bool success = obj->second->modifyExpr(expr, type); EXCLUSIVE_RELEASE(); GuiUpdateWatchView(); return success; } else return false; } void WatchModifyNameUnlocked(unsigned int id, const char* newName) { auto obj = watchexpr.find(id); if(obj != watchexpr.end()) { obj->second->modifyName(newName); } } void WatchModifyName(unsigned int id, const char* newName) { EXCLUSIVE_ACQUIRE(LockWatch); WatchModifyNameUnlocked(id, newName); EXCLUSIVE_RELEASE(); GuiUpdateWatchViewAsync(); } void WatchDelete(unsigned int id) { EXCLUSIVE_ACQUIRE(LockWatch); auto x = watchexpr.find(id); if(x != watchexpr.end()) { delete x->second; watchexpr.erase(x); EXCLUSIVE_RELEASE(); GuiUpdateWatchViewAsync(); } } void WatchSetWatchdogModeUnlocked(unsigned int id, WATCHDOGMODE mode) { auto obj = watchexpr.find(id); if(obj != watchexpr.end()) obj->second->setWatchdogMode(mode); } void WatchSetWatchdogMode(unsigned int id, WATCHDOGMODE mode) { EXCLUSIVE_ACQUIRE(LockWatch); WatchSetWatchdogModeUnlocked(id, mode); EXCLUSIVE_RELEASE(); GuiUpdateWatchViewAsync(); } WATCHDOGMODE WatchGetWatchdogEnabled(unsigned int id) { SHARED_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) return obj->second->getWatchdogMode(); else return WATCHDOGMODE::MODE_DISABLED; } duint WatchGetUnsignedValue(unsigned int id) { EXCLUSIVE_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) return obj->second->getIntValue(); else return 0; } WATCHVARTYPE WatchGetType(unsigned int id) { SHARED_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) return obj->second->getType(); else return WATCHVARTYPE::TYPE_INVALID; } void WatchSetTypeUnlocked(unsigned int id, WATCHVARTYPE type) { auto obj = watchexpr.find(id); if(obj != watchexpr.end()) obj->second->setType(type); } void WatchSetType(unsigned int id, WATCHVARTYPE type) { EXCLUSIVE_ACQUIRE(LockWatch); WatchSetTypeUnlocked(id, type); EXCLUSIVE_RELEASE(); GuiUpdateWatchViewAsync(); } unsigned int WatchGetWindow(unsigned int id) { SHARED_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) return obj->second->watchWindow; else return WATCHVARTYPE::TYPE_INVALID; } bool WatchIsWatchdogTriggered(unsigned int id) { SHARED_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) return obj->second->watchdogTriggered; else return false; } void WatchSetWindow(unsigned int id, unsigned int window) { EXCLUSIVE_ACQUIRE(LockWatch); auto obj = watchexpr.find(id); if(obj != watchexpr.end()) obj->second->watchWindow = window; EXCLUSIVE_RELEASE(); GuiUpdateWatchViewAsync(); } std::vector<WATCHINFO> WatchGetList() { EXCLUSIVE_ACQUIRE(LockWatch); std::vector<WATCHINFO> watchList; for(auto & i : watchexpr) { WATCHINFO info; info.value = i.second->getCurrIntValue(); strcpy_s(info.WatchName, i.second->getName()); strcpy_s(info.Expression, i.second->getExpr().c_str()); info.varType = i.second->getType(); info.id = i.first; info.watchdogMode = i.second->getWatchdogMode(); info.watchdogTriggered = i.second->watchdogTriggered; info.window = i.second->watchWindow; watchList.push_back(info); } return watchList; } // Initialize id counter so that it begin with a unused value void WatchInitIdCounter() { idCounter = 1; for(auto i : watchexpr) if(i.first > idCounter) idCounter = i.first + 1; } void WatchCacheSave(JSON root) { EXCLUSIVE_ACQUIRE(LockWatch); JSON watchroot = json_array(); for(auto i : watchexpr) { if(i.second->getType() == WATCHVARTYPE::TYPE_INVALID) continue; JSON watchitem = json_object(); json_object_set_new(watchitem, "Expression", json_string(i.second->getExpr().c_str())); json_object_set_new(watchitem, "Name", json_string(i.second->getName())); switch(i.second->getType()) { case WATCHVARTYPE::TYPE_INT: json_object_set_new(watchitem, "DataType", json_string("int")); break; case WATCHVARTYPE::TYPE_UINT: json_object_set_new(watchitem, "DataType", json_string("uint")); break; case WATCHVARTYPE::TYPE_FLOAT: json_object_set_new(watchitem, "DataType", json_string("float")); break; case WATCHVARTYPE::TYPE_ASCII: json_object_set_new(watchitem, "DataType", json_string("ascii")); break; case WATCHVARTYPE::TYPE_UNICODE: json_object_set_new(watchitem, "DataType", json_string("unicode")); break; default: break; } switch(i.second->getWatchdogMode()) { case WATCHDOGMODE::MODE_DISABLED: json_object_set_new(watchitem, "WatchdogMode", json_string("Disabled")); break; case WATCHDOGMODE::MODE_CHANGED: json_object_set_new(watchitem, "WatchdogMode", json_string("Changed")); break; case WATCHDOGMODE::MODE_UNCHANGED: json_object_set_new(watchitem, "WatchdogMode", json_string("Unchanged")); break; case WATCHDOGMODE::MODE_ISTRUE: json_object_set_new(watchitem, "WatchdogMode", json_string("IsTrue")); break; case WATCHDOGMODE::MODE_ISFALSE: json_object_set_new(watchitem, "WatchdogMode", json_string("IsFalse")); break; default: break; } json_array_append_new(watchroot, watchitem); } if(json_array_size(watchroot)) json_object_set(root, "watch", watchroot); json_decref(watchroot); } void WatchCacheLoad(JSON root) { EXCLUSIVE_ACQUIRE(LockWatch); JSON watchroot = json_object_get(root, "watch"); if(!watchroot) watchroot = json_object_get(root, "Watch"); unsigned int i; JSON val; if(!watchroot) return; json_array_foreach(watchroot, i, val) { const char* expr = json_string_value(json_object_get(val, "Expression")); if(!expr) continue; const char* datatype = json_string_value(json_object_get(val, "DataType")); if(!datatype) datatype = "uint"; const char* WatchdogMode = json_string_value(json_object_get(val, "WatchdogMode")); if(!WatchdogMode) WatchdogMode = "Disabled"; const char* watchname = json_string_value(json_object_get(val, "Name")); if(!watchname) watchname = "Watch"; WATCHVARTYPE varType; WATCHDOGMODE watchdog_mode; if(strcmp(datatype, "int") == 0) varType = WATCHVARTYPE::TYPE_INT; else if(strcmp(datatype, "uint") == 0) varType = WATCHVARTYPE::TYPE_UINT; else if(strcmp(datatype, "float") == 0) varType = WATCHVARTYPE::TYPE_FLOAT; else if(strcmp(datatype, "ascii") == 0) varType = WATCHVARTYPE::TYPE_ASCII; else if(strcmp(datatype, "unicode") == 0) varType = WATCHVARTYPE::TYPE_UNICODE; else continue; if(strcmp(WatchdogMode, "Disabled") == 0) watchdog_mode = WATCHDOGMODE::MODE_DISABLED; else if(strcmp(WatchdogMode, "Changed") == 0) watchdog_mode = WATCHDOGMODE::MODE_CHANGED; else if(strcmp(WatchdogMode, "Unchanged") == 0) watchdog_mode = WATCHDOGMODE::MODE_UNCHANGED; else if(strcmp(WatchdogMode, "IsTrue") == 0) watchdog_mode = WATCHDOGMODE::MODE_ISTRUE; else if(strcmp(WatchdogMode, "IsFalse") == 0) watchdog_mode = WATCHDOGMODE::MODE_ISFALSE; else continue; unsigned int id = WatchAddExprUnlocked(expr, varType); WatchModifyNameUnlocked(id, watchname); WatchSetWatchdogModeUnlocked(id, watchdog_mode); } WatchInitIdCounter(); // Initialize id counter so that it begin with a unused value }
C/C++
x64dbg-development/src/dbg/watch.h
#pragma once #include "_global.h" #include "jansson/jansson_x64dbg.h" #include "expressionparser.h" #include <map> class WatchExpr { protected: char WatchName[MAX_WATCH_NAME_SIZE]; ExpressionParser expr; WATCHDOGMODE watchdogMode; bool haveCurrValue; WATCHVARTYPE varType; duint currValue; // last result of getIntValue() public: bool watchdogTriggered; unsigned int watchWindow; WatchExpr(const char* name, const char* expression, WATCHVARTYPE type); ~WatchExpr() {}; duint getIntValue(); // evaluate the expression as integer bool modifyExpr(const char* expression, WATCHVARTYPE type); // modify the expression and data type void modifyName(const char* newName); inline WATCHDOGMODE getWatchdogMode() { return watchdogMode; }; inline char* getName() { return WatchName; }; inline void setWatchdogMode(WATCHDOGMODE mode) { watchdogMode = mode; }; inline WATCHVARTYPE getType() { return varType; }; inline duint getCurrIntValue() { return currValue; }; inline const String & getExpr() { return expr.GetExpression(); }; inline const bool HaveCurrentValue() { return haveCurrValue; }; inline void setType(WATCHVARTYPE type) { varType = type; }; }; extern std::map<unsigned int, WatchExpr*> watchexpr; void GuiUpdateWatchViewAsync(); void WatchClear(); unsigned int WatchAddExpr(const char* expr, WATCHVARTYPE type); bool WatchModifyExpr(unsigned int id, const char* expr, WATCHVARTYPE type); void WatchModifyName(unsigned int id, const char* newName); void WatchDelete(unsigned int id); void WatchSetWatchdogMode(unsigned int id, WATCHDOGMODE mode); bool WatchIsWatchdogTriggered(unsigned int id); WATCHDOGMODE WatchGetWatchdogMode(unsigned int id); WATCHDOGMODE WatchGetWatchdogEnabled(unsigned int id); duint WatchGetUnsignedValue(unsigned int id); WATCHVARTYPE WatchGetType(unsigned int id); void WatchSetType(unsigned int id, WATCHVARTYPE type); std::vector<WATCHINFO> WatchGetList(); void WatchCacheSave(JSON root); // Save watch data to database void WatchCacheLoad(JSON root); // Load watch data from database
C++
x64dbg-development/src/dbg/x64dbg.cpp
/** @file x64dbg.cpp @brief Implements the 64 debug class. */ #include "_global.h" #include "command.h" #include "variable.h" #include "debugger.h" #include "simplescript.h" #include "console.h" #include "x64dbg.h" #include "msgqueue.h" #include "threading.h" #include "watch.h" #include "plugin_loader.h" #include "_dbgfunctions.h" #include <zydis_wrapper.h> #include "_scriptapi_gui.h" #include "filehelper.h" #include "database.h" #include "mnemonichelp.h" #include "datainst_helper.h" #include "exception.h" #include "expressionfunctions.h" #include "formatfunctions.h" #include "stringformat.h" #include "dbghelp_safe.h" static MESSAGE_STACK* gMsgStack = 0; static HANDLE hCommandLoopThread = 0; static bool bStopCommandLoopThread = false; static char alloctrace[MAX_PATH] = ""; static bool bIsStopped = true; static char scriptDllDir[MAX_PATH] = ""; static String notesFile; static bool cbStrLen(int argc, char* argv[]) { if(IsArgumentsLessThan(argc, 2)) return false; dprintf_untranslated("\"%s\"[%d]\n", argv[1], int(strlen(argv[1]))); return true; } static bool cbClearLog(int argc, char* argv[]) { GuiLogClear(); return true; } static bool cbSaveLog(int argc, char* argv[]) { if(argc < 2) GuiLogSave(nullptr); else GuiLogSave(argv[1]); return true; } static bool cbRedirectLog(int argc, char* argv[]) { if(IsArgumentsLessThan(argc, 2)) return false; GuiLogRedirect(argv[1]); return true; } static bool cbStopRedirectLog(int argc, char* argv[]) { GuiLogRedirectStop(); return true; } static bool cbPrintf(int argc, char* argv[]) { if(argc < 2) dprintf("\n"); else dprintf("%s", argv[1]); return true; } static bool DbgScriptDllExec(const char* dll); static bool cbScriptDll(int argc, char* argv[]) { if(IsArgumentsLessThan(argc, 2)) return false; return DbgScriptDllExec(argv[1]); } #include "cmd-all.h" /** \brief register the all the commands */ static void registercommands() { cmdinit(); //general purpose dbgcmdnew("inc", cbInstrInc, false); dbgcmdnew("dec", cbInstrDec, false); dbgcmdnew("add", cbInstrAdd, false); dbgcmdnew("sub", cbInstrSub, false); dbgcmdnew("mul", cbInstrMul, false); dbgcmdnew("div", cbInstrDiv, false); dbgcmdnew("and", cbInstrAnd, false); dbgcmdnew("or", cbInstrOr, false); dbgcmdnew("xor", cbInstrXor, false); dbgcmdnew("neg", cbInstrNeg, false); dbgcmdnew("not", cbInstrNot, false); dbgcmdnew("bswap", cbInstrBswap, false); dbgcmdnew("rol", cbInstrRol, false); dbgcmdnew("ror", cbInstrRor, false); dbgcmdnew("shl,sal", cbInstrShl, false); dbgcmdnew("shr", cbInstrShr, false); dbgcmdnew("sar", cbInstrSar, false); dbgcmdnew("push", cbInstrPush, true); dbgcmdnew("pop", cbInstrPop, true); dbgcmdnew("test", cbInstrTest, false); dbgcmdnew("cmp", cbInstrCmp, false); dbgcmdnew("mov,set", cbInstrMov, false); //mov a variable, arg1:dest,arg2:src //general purpose (SSE/AVX) dbgcmdnew("movdqu,movups,movupd", cbInstrMovdqu, true); //move from and to XMM register //debug control dbgcmdnew("InitDebug,init,initdbg", cbDebugInit, false); //init debugger arg1:exefile,[arg2:commandline] dbgcmdnew("StopDebug,stop,dbgstop", cbDebugStop, true); //stop debugger dbgcmdnew("AttachDebugger,attach", cbDebugAttach, false); //attach dbgcmdnew("DetachDebugger,detach", cbDebugDetach, true); //detach dbgcmdnew("run,go,r,g", cbDebugRun, true); //unlock WAITID_RUN dbgcmdnew("erun,egun,er,eg", cbDebugErun, true); //run + skip first chance exceptions dbgcmdnew("serun,sego", cbDebugSerun, true); //run + swallow exception dbgcmdnew("pause", cbDebugPause, false); //pause debugger dbgcmdnew("DebugContinue,con", cbDebugContinue, true); //set continue status dbgcmdnew("StepInto,sti,SingleStep,sstep,sst", cbDebugStepInto, true); //StepInto dbgcmdnew("eStepInto,esti", cbDebugeStepInto, true); //StepInto + skip first chance exceptions dbgcmdnew("seStepInto,sesti,eSingleStep,esstep,esst", cbDebugseStepInto, true); //StepInto + swallow exception dbgcmdnew("StepOver,step,sto,st", cbDebugStepOver, true); //StepOver dbgcmdnew("eStepOver,estep,esto,est", cbDebugeStepOver, true); //StepOver + skip first chance exceptions dbgcmdnew("seStepOver,sestep,sesto,sest", cbDebugseStepOver, true); //StepOver + swallow exception dbgcmdnew("StepOut,rtr", cbDebugStepOut, true); //StepOut dbgcmdnew("eStepOut,ertr", cbDebugeStepOut, true); //rtr + skip first chance exceptions dbgcmdnew("skip", cbDebugSkip, true); //skip one instruction dbgcmdnew("InstrUndo", cbInstrInstrUndo, true); //Instruction undo dbgcmdnew("StepUser,StepUserInto", cbDebugStepUserInto, true); // step into until reaching user code dbgcmdnew("StepSystem,StepUserInto", cbDebugStepSystemInto, true); // step into until reaching system code //breakpoint control dbgcmdnew("SetBPX,bp,bpx", cbDebugSetBPX, true); //breakpoint dbgcmdnew("DeleteBPX,bpc,bc", cbDebugDeleteBPX, true); //breakpoint delete dbgcmdnew("EnableBPX,bpe,be", cbDebugEnableBPX, true); //breakpoint enable dbgcmdnew("DisableBPX,bpd,bd", cbDebugDisableBPX, true); //breakpoint disable dbgcmdnew("SetHardwareBreakpoint,bph,bphws", cbDebugSetHardwareBreakpoint, true); //hardware breakpoint dbgcmdnew("DeleteHardwareBreakpoint,bphc,bphwc", cbDebugDeleteHardwareBreakpoint, true); //delete hardware breakpoint dbgcmdnew("EnableHardwareBreakpoint,bphe,bphwe", cbDebugEnableHardwareBreakpoint, true); //enable hardware breakpoint dbgcmdnew("DisableHardwareBreakpoint,bphd,bphwd", cbDebugDisableHardwareBreakpoint, true); //disable hardware breakpoint dbgcmdnew("SetMemoryBPX,membp,bpm", cbDebugSetMemoryBpx, true); //SetMemoryBPX dbgcmdnew("DeleteMemoryBPX,membpc,bpmc", cbDebugDeleteMemoryBreakpoint, true); //delete memory breakpoint dbgcmdnew("EnableMemoryBreakpoint,membpe,bpme", cbDebugEnableMemoryBreakpoint, true); //enable memory breakpoint dbgcmdnew("DisableMemoryBreakpoint,membpd,bpmd", cbDebugDisableMemoryBreakpoint, true); //enable memory breakpoint dbgcmdnew("LibrarianSetBreakpoint,bpdll", cbDebugBpDll, true); //set dll breakpoint dbgcmdnew("LibrarianRemoveBreakpoint,bcdll", cbDebugBcDll, true); //remove dll breakpoint dbgcmdnew("LibrarianEnableBreakpoint,bpedll", cbDebugBpDllEnable, true); //enable dll breakpoint dbgcmdnew("LibrarianDisableBreakpoint,bpddll", cbDebugBpDllDisable, true); //disable dll breakpoint dbgcmdnew("SetExceptionBPX", cbDebugSetExceptionBPX, true); //set exception breakpoint dbgcmdnew("DeleteExceptionBPX", cbDebugDeleteExceptionBPX, true); //delete exception breakpoint dbgcmdnew("EnableExceptionBPX", cbDebugEnableExceptionBPX, true); //enable exception breakpoint dbgcmdnew("DisableExceptionBPX", cbDebugDisableExceptionBPX, true); //disable exception breakpoint dbgcmdnew("bpgoto", cbDebugSetBPGoto, true); dbgcmdnew("bplist", cbDebugBplist, true); //breakpoint list dbgcmdnew("SetBPXOptions,bptype", cbDebugSetBPXOptions, false); //breakpoint type //conditional breakpoint control dbgcmdnew("SetBreakpointName,bpname", cbDebugSetBPXName, true); //set breakpoint name dbgcmdnew("SetBreakpointCondition,bpcond,bpcnd", cbDebugSetBPXCondition, true); //set breakpoint breakCondition dbgcmdnew("SetBreakpointLog,bplog,bpl", cbDebugSetBPXLog, true); //set breakpoint logText dbgcmdnew("SetBreakpointLogCondition,bplogcondition", cbDebugSetBPXLogCondition, true); //set breakpoint logCondition dbgcmdnew("SetBreakpointCommand", cbDebugSetBPXCommand, true); //set breakpoint command on hit dbgcmdnew("SetBreakpointCommandCondition", cbDebugSetBPXCommandCondition, true); //set breakpoint commandCondition dbgcmdnew("SetBreakpointFastResume", cbDebugSetBPXFastResume, true); //set breakpoint fast resume dbgcmdnew("SetBreakpointSingleshoot", cbDebugSetBPXSingleshoot, true); //set breakpoint singleshoot dbgcmdnew("SetBreakpointSilent", cbDebugSetBPXSilent, true); //set breakpoint fast resume dbgcmdnew("GetBreakpointHitCount", cbDebugGetBPXHitCount, true); //get breakpoint hit count dbgcmdnew("ResetBreakpointHitCount", cbDebugResetBPXHitCount, true); //reset breakpoint hit count dbgcmdnew("SetHardwareBreakpointName,bphwname", cbDebugSetBPXHardwareName, true); //set breakpoint name dbgcmdnew("SetHardwareBreakpointCondition,bphwcond", cbDebugSetBPXHardwareCondition, true); //set breakpoint breakCondition dbgcmdnew("SetHardwareBreakpointLog,bphwlog", cbDebugSetBPXHardwareLog, true); //set breakpoint logText dbgcmdnew("SetHardwareBreakpointLogCondition,bphwlogcondition", cbDebugSetBPXHardwareLogCondition, true); //set breakpoint logText dbgcmdnew("SetHardwareBreakpointCommand", cbDebugSetBPXHardwareCommand, true); //set breakpoint command on hit dbgcmdnew("SetHardwareBreakpointCommandCondition", cbDebugSetBPXHardwareCommandCondition, true); //set breakpoint commandCondition dbgcmdnew("SetHardwareBreakpointFastResume", cbDebugSetBPXHardwareFastResume, true); //set breakpoint fast resume dbgcmdnew("SetHardwareBreakpointSingleshoot", cbDebugSetBPXHardwareSingleshoot, true); //set breakpoint singleshoot dbgcmdnew("SetHardwareBreakpointSilent", cbDebugSetBPXHardwareSilent, true); //set breakpoint fast resume dbgcmdnew("GetHardwareBreakpointHitCount", cbDebugGetBPXHardwareHitCount, true); //get breakpoint hit count dbgcmdnew("ResetHardwareBreakpointHitCount", cbDebugResetBPXHardwareHitCount, true); //reset breakpoint hit count dbgcmdnew("SetMemoryBreakpointName,bpmname", cbDebugSetBPXMemoryName, true); //set breakpoint name dbgcmdnew("SetMemoryBreakpointCondition,bpmcond", cbDebugSetBPXMemoryCondition, true); //set breakpoint breakCondition dbgcmdnew("SetMemoryBreakpointLog,bpmlog", cbDebugSetBPXMemoryLog, true); //set breakpoint log dbgcmdnew("SetMemoryBreakpointLogCondition,bpmlogcondition", cbDebugSetBPXMemoryLogCondition, true); //set breakpoint logCondition dbgcmdnew("SetMemoryBreakpointCommand", cbDebugSetBPXMemoryCommand, true); //set breakpoint command on hit dbgcmdnew("SetMemoryBreakpointCommandCondition", cbDebugSetBPXMemoryCommandCondition, true); //set breakpoint commandCondition dbgcmdnew("SetMemoryBreakpointFastResume", cbDebugSetBPXMemoryFastResume, true); //set breakpoint fast resume dbgcmdnew("SetMemoryBreakpointSingleshoot", cbDebugSetBPXMemorySingleshoot, true); //set breakpoint singleshoot dbgcmdnew("SetMemoryBreakpointSilent", cbDebugSetBPXMemorySilent, true); //set breakpoint fast resume dbgcmdnew("GetMemoryBreakpointHitCount", cbDebugGetBPXMemoryHitCount, true); //get breakpoint hit count dbgcmdnew("ResetMemoryBreakpointHitCount", cbDebugResetBPXMemoryHitCount, true); //reset breakpoint hit count dbgcmdnew("SetLibrarianBreakpointName", cbDebugSetBPXDLLName, true); //set breakpoint name dbgcmdnew("SetLibrarianBreakpointCondition", cbDebugSetBPXDLLCondition, true); //set breakpoint breakCondition dbgcmdnew("SetLibrarianBreakpointLog", cbDebugSetBPXDLLLog, true); //set breakpoint log dbgcmdnew("SetLibrarianBreakpointLogCondition", cbDebugSetBPXDLLLogCondition, true); //set breakpoint logCondition dbgcmdnew("SetLibrarianBreakpointCommand", cbDebugSetBPXDLLCommand, true); //set breakpoint command on hit dbgcmdnew("SetLibrarianBreakpointCommandCondition", cbDebugSetBPXDLLCommandCondition, true); //set breakpoint commandCondition dbgcmdnew("SetLibrarianBreakpointFastResume", cbDebugSetBPXDLLFastResume, true); //set breakpoint fast resume dbgcmdnew("SetLibrarianBreakpointSingleshoot", cbDebugSetBPXDLLSingleshoot, true); //set breakpoint singleshoot dbgcmdnew("SetLibrarianBreakpointSilent", cbDebugSetBPXDLLSilent, true); //set breakpoint fast resume dbgcmdnew("GetLibrarianBreakpointHitCount", cbDebugGetBPXDLLHitCount, true); //get breakpoint hit count dbgcmdnew("ResetLibrarianBreakpointHitCount", cbDebugResetBPXDLLHitCount, true); //reset breakpoint hit count dbgcmdnew("SetExceptionBreakpointName", cbDebugSetBPXExceptionName, true); //set breakpoint name dbgcmdnew("SetExceptionBreakpointCondition", cbDebugSetBPXExceptionCondition, true); //set breakpoint breakCondition dbgcmdnew("SetExceptionBreakpointLog", cbDebugSetBPXExceptionLog, true); //set breakpoint log dbgcmdnew("SetExceptionBreakpointLogCondition", cbDebugSetBPXExceptionLogCondition, true); //set breakpoint logCondition dbgcmdnew("SetExceptionBreakpointCommand", cbDebugSetBPXExceptionCommand, true); //set breakpoint command on hit dbgcmdnew("SetExceptionBreakpointCommandCondition", cbDebugSetBPXExceptionCommandCondition, true); //set breakpoint commandCondition dbgcmdnew("SetExceptionBreakpointFastResume", cbDebugSetBPXExceptionFastResume, true); //set breakpoint fast resume dbgcmdnew("SetExceptionBreakpointSingleshoot", cbDebugSetBPXExceptionSingleshoot, true); //set breakpoint singleshoot dbgcmdnew("SetExceptionBreakpointSilent", cbDebugSetBPXExceptionSilent, true); //set breakpoint fast resume dbgcmdnew("GetExceptionBreakpointHitCount", cbDebugGetBPXExceptionHitCount, true); //get breakpoint hit count dbgcmdnew("ResetExceptionBreakpointHitCount", cbDebugResetBPXExceptionHitCount, true); //reset breakpoint hit count //tracing dbgcmdnew("TraceIntoConditional,ticnd", cbDebugTraceIntoConditional, true); //Trace into conditional dbgcmdnew("TraceOverConditional,tocnd", cbDebugTraceOverConditional, true); //Trace over conditional dbgcmdnew("TraceIntoBeyondTraceCoverage,TraceIntoBeyondTraceRecord,tibt", cbDebugTraceIntoBeyondTraceRecord, true); //Trace into beyond trace record dbgcmdnew("TraceOverBeyondTraceCoverage,TraceOverBeyondTraceRecord,tobt", cbDebugTraceOverBeyondTraceRecord, true); //Trace over beyond trace record dbgcmdnew("TraceIntoIntoTraceCoverage,TraceIntoIntoTraceRecord,tiit", cbDebugTraceIntoIntoTraceRecord, true); //Trace into into trace record dbgcmdnew("TraceOverIntoTraceCoverage,TraceOverIntoTraceRecord,toit", cbDebugTraceOverIntoTraceRecord, true); //Trace over into trace record dbgcmdnew("RunToParty", cbDebugRunToParty, true); //Run to code in a party dbgcmdnew("RunToUserCode,rtu", cbDebugRunToUserCode, true); //Run to user code dbgcmdnew("TraceSetLog,SetTraceLog", cbDebugTraceSetLog, true); //Set trace log text + condition dbgcmdnew("TraceSetCommand,SetTraceCommand", cbDebugTraceSetCommand, true); //Set trace command text + condition dbgcmdnew("TraceSetLogFile,SetTraceLogFile", cbDebugTraceSetLogFile, true); //Set trace log file dbgcmdnew("StartTraceRecording,StartRunTrace,opentrace", cbDebugStartTraceRecording, true); //start run trace (Ollyscript command "opentrace" "opens run trace window") dbgcmdnew("StopTraceRecording,StopRunTrace,tc", cbDebugStopTraceRecording, true); //stop run trace (and Ollyscript command) //thread control dbgcmdnew("createthread,threadcreate,newthread,threadnew", cbDebugCreatethread, true); //create thread dbgcmdnew("switchthread,threadswitch", cbDebugSwitchthread, true); //switch thread dbgcmdnew("suspendthread,threadsuspend", cbDebugSuspendthread, true); //suspend thread dbgcmdnew("resumethread,threadresume", cbDebugResumethread, true); //resume thread dbgcmdnew("killthread,threadkill", cbDebugKillthread, true); //kill thread dbgcmdnew("suspendallthreads,threadsuspendall", cbDebugSuspendAllThreads, true); //suspend all threads dbgcmdnew("resumeallthreads,threadresumeall", cbDebugResumeAllThreads, true); //resume all threads dbgcmdnew("setthreadpriority,setprioritythread,threadsetpriority", cbDebugSetPriority, true); //set thread priority dbgcmdnew("threadsetname,setthreadname", cbDebugSetthreadname, true); //set thread name //memory operations dbgcmdnew("alloc", cbDebugAlloc, true); //allocate memory dbgcmdnew("free", cbDebugFree, true); //free memory dbgcmdnew("Fill,memset", cbDebugMemset, true); //memset dbgcmdnew("memcpy", cbDebugMemcpy, true); //memcpy dbgcmdnew("getpagerights,getrightspage", cbDebugGetPageRights, true); dbgcmdnew("setpagerights,setrightspage", cbDebugSetPageRights, true); dbgcmdnew("savedata", cbInstrSavedata, true); //save data to disk dbgcmdnew("minidump", cbInstrMinidump, true); //create a minidump //operating system control dbgcmdnew("GetPrivilegeState", cbGetPrivilegeState, true); //get priv state dbgcmdnew("EnablePrivilege", cbEnablePrivilege, true); //enable priv dbgcmdnew("DisablePrivilege", cbDisablePrivilege, true); //disable priv dbgcmdnew("handleclose,closehandle", cbHandleClose, true); //close remote handle dbgcmdnew("EnableWindow", cbEnableWindow, true); //enable remote window dbgcmdnew("DisableWindow", cbDisableWindow, true); //disable remote window //watch control dbgcmdnew("AddWatch", cbAddWatch, true); // add watch dbgcmdnew("DelWatch", cbDelWatch, true); // delete watch dbgcmdnew("SetWatchdog", cbSetWatchdog, true); // Setup watchdog dbgcmdnew("SetWatchExpression", cbSetWatchExpression, true); // Set watch expression dbgcmdnew("SetWatchName", cbSetWatchName, true); // Set watch name dbgcmdnew("SetWatchType", cbSetWatchType, true); // Set watch type dbgcmdnew("CheckWatchdog", cbCheckWatchdog, true); // Watchdog //variables dbgcmdnew("varnew,var", cbInstrVar, false); //make a variable arg1:name,[arg2:value] dbgcmdnew("vardel", cbInstrVarDel, false); //delete a variable, arg1:variable name dbgcmdnew("varlist", cbInstrVarList, false); //list variables[arg1:type filter] //searching dbgcmdnew("find", cbInstrFind, true); //find a pattern dbgcmdnew("findall", cbInstrFindAll, true); //find all patterns dbgcmdnew("findallmem,findmemall", cbInstrFindAllMem, true); //memory map pattern find dbgcmdnew("findasm,asmfind", cbInstrFindAsm, true); //find instruction dbgcmdnew("reffind,findref,ref", cbInstrRefFind, true); //find references to a value dbgcmdnew("reffindrange,findrefrange,refrange", cbInstrRefFindRange, true); dbgcmdnew("refstr,strref", cbInstrRefStr, true); //find string references dbgcmdnew("reffunctionpointer", cbInstrRefFuncionPointer, true); //find function pointers dbgcmdnew("modcallfind", cbInstrModCallFind, true); //find intermodular calls dbgcmdnew("setmaxfindresult,findsetmaxresult", cbInstrSetMaxFindResult, false); //set the maximum number of occurences found dbgcmdnew("guidfind,findguid", cbInstrGUIDFind, true); //find GUID references TODO: undocumented //user database dbgcmdnew("dbsave,savedb", cbInstrDbsave, true); //save program database dbgcmdnew("dbload,loaddb", cbInstrDbload, true); //load program database dbgcmdnew("dbclear,cleardb", cbInstrDbclear, true); //clear program database dbgcmdnew("commentset,cmt,cmtset", cbInstrCommentSet, true); //set/edit comment dbgcmdnew("commentdel,cmtc,cmtdel", cbInstrCommentDel, true); //delete comment dbgcmdnew("commentlist", cbInstrCommentList, true); //list comments dbgcmdnew("commentclear", cbInstrCommentClear, true); //clear comments dbgcmdnew("labelset,lbl,lblset", cbInstrLabelSet, true); //set/edit label dbgcmdnew("labeldel,lblc,lbldel", cbInstrLabelDel, true); //delete label dbgcmdnew("labellist", cbInstrLabelList, true); //list labels dbgcmdnew("labelclear", cbInstrLabelClear, true); //clear labels dbgcmdnew("bookmarkset,bookmark", cbInstrBookmarkSet, true); //set bookmark dbgcmdnew("bookmarkdel,bookmarkc", cbInstrBookmarkDel, true); //delete bookmark dbgcmdnew("bookmarklist", cbInstrBookmarkList, true); //list bookmarks dbgcmdnew("bookmarkclear", cbInstrBookmarkClear, true); //clear bookmarks dbgcmdnew("functionadd,func", cbInstrFunctionAdd, true); //function dbgcmdnew("functiondel,funcc", cbInstrFunctionDel, true); //function dbgcmdnew("functionlist", cbInstrFunctionList, true); //list functions dbgcmdnew("functionclear", cbInstrFunctionClear, false); //delete all functions dbgcmdnew("argumentadd", cbInstrArgumentAdd, true); //add argument dbgcmdnew("argumentdel", cbInstrArgumentDel, true); //delete argument dbgcmdnew("argumentlist", cbInstrArgumentList, true); //list arguments dbgcmdnew("argumentclear", cbInstrArgumentClear, false); //delete all arguments dbgcmdnew("loopadd", cbInstrLoopAdd, true); //add loop TODO: undocumented dbgcmdnew("loopdel", cbInstrLoopDel, true); //delete loop TODO: undocumented dbgcmdnew("looplist", cbInstrLoopList, true); //list loops TODO: undocumented dbgcmdnew("loopclear", cbInstrLoopClear, true); //clear loops TODO: undocumented //analysis dbgcmdnew("analyse,analyze,anal", cbInstrAnalyse, true); //secret analysis command dbgcmdnew("exanal,exanalyse,exanalyze", cbInstrExanalyse, true); //exception directory analysis dbgcmdnew("cfanal,cfanalyse,cfanalyze", cbInstrCfanalyse, true); //control flow analysis dbgcmdnew("analyse_nukem,analyze_nukem,anal_nukem", cbInstrAnalyseNukem, true); //secret analysis command #2 dbgcmdnew("analxrefs,analx", cbInstrAnalxrefs, true); //analyze xrefs dbgcmdnew("analrecur,analr", cbInstrAnalrecur, true); //analyze a single function dbgcmdnew("analadv", cbInstrAnalyseadv, true); //analyze xref,function and data dbgcmdnew("traceexecute", cbInstrTraceexecute, true); //execute trace record on address TODO: undocumented dbgcmdnew("virtualmod", cbInstrVirtualmod, true); //virtual module dbgcmdnew("symdownload,downloadsym", cbDebugDownloadSymbol, true); //download symbols dbgcmdnew("symload,loadsym", cbDebugLoadSymbol, true); //load symbols dbgcmdnew("symunload,unloadsym", cbDebugUnloadSymbol, true); //unload symbols dbgcmdnew("imageinfo,modimageinfo", cbInstrImageinfo, true); //print module image information dbgcmdnew("GetRelocSize,grs", cbInstrGetRelocSize, true); //get relocation table size dbgcmdnew("exhandlers", cbInstrExhandlers, true); //enumerate exception handlers dbgcmdnew("exinfo", cbInstrExinfo, true); //dump last exception information //types dbgcmdnew("DataUnknown", cbInstrDataUnknown, true); //mark as Unknown dbgcmdnew("DataByte,db", cbInstrDataByte, true); //mark as Byte dbgcmdnew("DataWord,dw", cbInstrDataWord, true); //mark as Word dbgcmdnew("DataDword,dd", cbInstrDataDword, true); //mark as Dword dbgcmdnew("DataFword", cbInstrDataFword, true); //mark as Fword dbgcmdnew("DataQword,dq", cbInstrDataQword, true); //mark as Qword dbgcmdnew("DataTbyte", cbInstrDataTbyte, true); //mark as Tbyte dbgcmdnew("DataOword", cbInstrDataOword, true); //mark as Oword dbgcmdnew("DataMmword", cbInstrDataMmword, true); //mark as Mmword dbgcmdnew("DataXmmword", cbInstrDataXmmword, true); //mark as Xmmword dbgcmdnew("DataYmmword", cbInstrDataYmmword, true); //mark as Ymmword dbgcmdnew("DataFloat,DataReal4,df", cbInstrDataFloat, true); //mark as Float dbgcmdnew("DataDouble,DataReal8", cbInstrDataDouble, true); //mark as Double dbgcmdnew("DataLongdouble,DataReal10", cbInstrDataLongdouble, true); //mark as Longdouble dbgcmdnew("DataAscii,da", cbInstrDataAscii, true); //mark as Ascii dbgcmdnew("DataUnicode,du", cbInstrDataUnicode, true); //mark as Unicode dbgcmdnew("DataCode,dc", cbInstrDataCode, true); //mark as Code dbgcmdnew("DataJunk", cbInstrDataJunk, true); //mark as Junk dbgcmdnew("DataMiddle", cbInstrDataMiddle, true); //mark as Middle dbgcmdnew("AddType", cbInstrAddType, false); //AddType dbgcmdnew("AddStruct", cbInstrAddStruct, false); //AddStruct dbgcmdnew("AddUnion", cbInstrAddUnion, false); //AddUnion dbgcmdnew("AddMember", cbInstrAddMember, false); //AddMember dbgcmdnew("AppendMember", cbInstrAppendMember, false); //AppendMember dbgcmdnew("AddFunction", cbInstrAddFunction, false); //AddFunction dbgcmdnew("AddArg", cbInstrAddArg, false); //AddArg dbgcmdnew("AppendArg", cbInstrAppendArg, false); //AppendArg dbgcmdnew("SizeofType", cbInstrSizeofType, false); //SizeofType dbgcmdnew("VisitType", cbInstrVisitType, false); //VisitType dbgcmdnew("ClearTypes", cbInstrClearTypes, false); //ClearTypes dbgcmdnew("RemoveType", cbInstrRemoveType, false); //RemoveType dbgcmdnew("EnumTypes", cbInstrEnumTypes, false); //EnumTypes dbgcmdnew("LoadTypes", cbInstrLoadTypes, false); //LoadTypes dbgcmdnew("ParseTypes", cbInstrParseTypes, false); //ParseTypes //plugins dbgcmdnew("StartScylla,scylla,imprec", cbDebugStartScylla, false); //start scylla dbgcmdnew("plugload,pluginload,loadplugin", cbInstrPluginLoad, false); //load plugin dbgcmdnew("plugunload,pluginunload,unloadplugin", cbInstrPluginUnload, false); //unload plugin dbgcmdnew("plugreload,pluginreload,reloadplugin", cbInstrPluginReload, false); //reload plugin //script dbgcmdnew("scriptload", cbScriptLoad, false); dbgcmdnew("msg", cbScriptMsg, false); dbgcmdnew("msgyn", cbScriptMsgyn, false); dbgcmdnew("log", cbInstrLog, false); //log command with superawesome hax dbgcmdnew("htmllog", cbInstrHtmlLog, false); //command for testing dbgcmdnew("scriptdll,dllscript", cbScriptDll, false); //execute a script DLL dbgcmdnew("scriptcmd", cbScriptCmd, false); // execute a script command TODO: undocumented //gui dbgcmdnew("disasm,dis,d", cbDebugDisasm, true); //doDisasm dbgcmdnew("dump", cbDebugDump, true); //dump at address dbgcmdnew("sdump", cbDebugStackDump, true); //dump at stack address dbgcmdnew("memmapdump", cbDebugMemmapdump, true); dbgcmdnew("graph", cbInstrGraph, true); //graph function dbgcmdnew("guiupdateenable", cbInstrEnableGuiUpdate, true); //enable gui message dbgcmdnew("guiupdatedisable", cbInstrDisableGuiUpdate, true); //disable gui message dbgcmdnew("setfreezestack", cbDebugSetfreezestack, false); //freeze the stack from auto updates dbgcmdnew("refinit", cbInstrRefinit, false); dbgcmdnew("refadd", cbInstrRefadd, false); dbgcmdnew("refget", cbInstrRefGet, false); dbgcmdnew("EnableLog,LogEnable", cbInstrEnableLog, false); //enable log dbgcmdnew("DisableLog,LogDisable", cbInstrDisableLog, false); //disable log dbgcmdnew("ClearLog,cls,lc,lclr", cbClearLog, false); //clear the log dbgcmdnew("SaveLog,LogSave", cbSaveLog, false); //save the log dbgcmdnew("RedirectLog,LogRedirect", cbRedirectLog, false); //redirect the log dbgcmdnew("StopRedirectLog,LogRedirectStop", cbStopRedirectLog, false); //stop redirecting the log dbgcmdnew("AddFavouriteTool", cbInstrAddFavTool, false); //add favourite tool dbgcmdnew("AddFavouriteCommand", cbInstrAddFavCmd, false); //add favourite command dbgcmdnew("AddFavouriteToolShortcut,SetFavouriteToolShortcut", cbInstrSetFavToolShortcut, false); //set favourite tool shortcut dbgcmdnew("FoldDisassembly", cbInstrFoldDisassembly, true); //fold disassembly segment dbgcmdnew("guiupdatetitle", cbDebugUpdateTitle, true); // set relevant disassembly title dbgcmdnew("showref", cbShowReferences, false); // show references window dbgcmdnew("symfollow", cbSymbolsFollow, false); // follow address in symbols tab dbgcmdnew("gototrace,tracegoto", cbGotoTrace, false); // goto index in trace tab //misc dbgcmdnew("chd", cbInstrChd, false); //Change directory dbgcmdnew("zzz,doSleep", cbInstrZzz, false); //sleep dbgcmdnew("HideDebugger,dbh,hide", cbDebugHide, true); //HideDebugger dbgcmdnew("loadlib", cbDebugLoadLib, true); //Load DLL dbgcmdnew("freelib", cbDebugFreeLib, true); //Unload DLL TODO: undocumented dbgcmdnew("asm", cbInstrAssemble, true); //assemble instruction dbgcmdnew("gpa", cbInstrGpa, true); //get proc address dbgcmdnew("setjit,jitset", cbDebugSetJIT, false); //set JIT dbgcmdnew("getjit,jitget", cbDebugGetJIT, false); //get JIT dbgcmdnew("getjitauto,jitgetauto", cbDebugGetJITAuto, false); //get JIT Auto dbgcmdnew("setjitauto,jitsetauto", cbDebugSetJITAuto, false); //set JIT Auto dbgcmdnew("getcommandline,getcmdline", cbDebugGetCmdline, true); //Get CmdLine dbgcmdnew("setcommandline,setcmdline", cbDebugSetCmdline, true); //Set CmdLine dbgcmdnew("mnemonichelp", cbInstrMnemonichelp, false); //mnemonic help dbgcmdnew("mnemonicbrief", cbInstrMnemonicbrief, false); //mnemonic brief dbgcmdnew("config", cbInstrConfig, false); //get or set config uint dbgcmdnew("restartadmin,runas,adminrestart", cbInstrRestartadmin, false); //restart x64dbg as administrator //undocumented dbgcmdnew("bench", cbDebugBenchmark, true); //benchmark test (readmem etc) dbgcmdnew("dprintf", cbPrintf, false); //printf dbgcmdnew("setstr,strset", cbInstrSetstr, false); //set a string variable dbgcmdnew("getstr,strget", cbInstrGetstr, false); //get a string variable dbgcmdnew("copystr,strcpy", cbInstrCopystr, true); //write a string variable to memory dbgcmdnew("zydis", cbInstrZydis, true); //disassemble using zydis dbgcmdnew("visualize", cbInstrVisualize, true); //visualize analysis dbgcmdnew("meminfo", cbInstrMeminfo, true); //command to debug memory map bugs dbgcmdnew("briefcheck", cbInstrBriefcheck, true); //check if mnemonic briefs are missing dbgcmdnew("focusinfo", cbInstrFocusinfo, false); dbgcmdnew("printstack,logstack", cbInstrPrintStack, true); //print the call stack dbgcmdnew("flushlog", cbInstrFlushlog, false); //flush the log dbgcmdnew("AnimateWait", cbInstrAnimateWait, true); //Wait for the debuggee to pause. dbgcmdnew("dbdecompress", cbInstrDbdecompress, false); //Decompress a database. dbgcmdnew("DebugFlags", cbInstrDebugFlags, false); //Set ntdll LdrpDebugFlags dbgcmdnew("LabelRuntimeFunctions", cbInstrLabelRuntimeFunctions, true); //Label exception directory entries dbgcmdnew("cmdtest", cbInstrCmdTest, false); //log argv verbatim }; bool cbCommandProvider(char* cmd, int maxlen) { MESSAGE msg; MsgWait(gMsgStack, &msg); if(bStopCommandLoopThread) return false; char* newcmd = (char*)msg.param1; if(strlen(newcmd) >= deflen) { dprintf(QT_TRANSLATE_NOOP("DBG", "command cut at ~%d characters\n"), deflen); newcmd[deflen - 2] = 0; } strcpy_s(cmd, deflen, newcmd); efree(newcmd, "cbCommandProvider:newcmd"); //free allocated command return true; } /** \brief Execute command asynchronized. */ extern "C" DLL_EXPORT bool _dbg_dbgcmdexec(const char* cmd) { int len = (int)strlen(cmd); char* newcmd = (char*)emalloc((len + 1) * sizeof(char), "_dbg_dbgcmdexec:newcmd"); strcpy_s(newcmd, len + 1, cmd); return MsgSend(gMsgStack, 0, (duint)newcmd, 0); } static DWORD WINAPI DbgCommandLoopThread(void* a) { cmdloop(); return 0; } typedef void(*SCRIPTDLLSTART)(); struct DLLSCRIPTEXECTHREADINFO { DLLSCRIPTEXECTHREADINFO(HINSTANCE hScriptDll, SCRIPTDLLSTART AsyncStart) : hScriptDll(hScriptDll), AsyncStart(AsyncStart) { } HINSTANCE hScriptDll; SCRIPTDLLSTART AsyncStart; }; static DWORD WINAPI DbgScriptDllExecThread(void* a) { auto info = (DLLSCRIPTEXECTHREADINFO*)a; auto AsyncStart = info->AsyncStart; auto hScriptDll = info->hScriptDll; delete info; dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Calling export \"AsyncStart\"...\n")); AsyncStart(); dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] \"AsyncStart\" returned!\n")); dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Calling FreeLibrary...")); if(FreeLibrary(hScriptDll)) dputs(QT_TRANSLATE_NOOP("DBG", "success!\n")); else { String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "failure (%s)...\n"), error.c_str()); } return 0; } static bool DbgScriptDllExec(const char* dll) { String dllPath = dll; if(dllPath.find('\\') == String::npos) dllPath = String(scriptDllDir) + String(dll); dprintf(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Loading Script DLL \"%s\"...\n"), dllPath.c_str()); auto hScriptDll = LoadLibraryW(StringUtils::Utf8ToUtf16(dllPath).c_str()); if(hScriptDll) { dprintf(QT_TRANSLATE_NOOP("DBG", "[Script DLL] DLL loaded on 0x%p!\n"), hScriptDll); auto AsyncStart = SCRIPTDLLSTART(GetProcAddress(hScriptDll, "AsyncStart")); if(AsyncStart) { dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Creating thread to call the export \"AsyncStart\"...\n")); CloseHandle(CreateThread(nullptr, 0, DbgScriptDllExecThread, new DLLSCRIPTEXECTHREADINFO(hScriptDll, AsyncStart), 0, nullptr)); //on-purpose memory leak here } else { auto Start = SCRIPTDLLSTART(GetProcAddress(hScriptDll, "Start")); if(Start) { dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Calling export \"Start\"...\n")); Start(); dputs(QT_TRANSLATE_NOOP("DBG", "[Script DLL] \"Start\" returned!\n")); } else { String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Failed to find the exports \"AsyncStart\" or \"Start\" (%s)!\n"), error.c_str()); } dprintf(QT_TRANSLATE_NOOP("DBG", "[Script DLL] Calling FreeLibrary...")); if(FreeLibrary(hScriptDll)) dputs(QT_TRANSLATE_NOOP("DBG", "success!\n")); else { String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "failure (%s)...\n"), error.c_str()); } } } else { String error = stringformatinline(StringUtils::sprintf("{winerror@%x}", GetLastError())); dprintf(QT_TRANSLATE_NOOP("DBG", "[Script DLL] LoadLibary failed (%s)!\n"), error.c_str()); } return true; } static DWORD WINAPI loadDbThread(LPVOID hEvent) { { // Take exclusive ownership over the modules to prevent a race condition with cbCreateProcess EXCLUSIVE_ACQUIRE(LockModules); // Signal the startup thread that we have the lock SetEvent(hEvent); // Load syscall indices dputs(QT_TRANSLATE_NOOP("DBG", "Retrieving syscall indices...")); if(SyscallInit()) dputs(QT_TRANSLATE_NOOP("DBG", "Syscall indices loaded!")); else dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load syscall indices...")); } // Load error codes if(ErrorCodeInit(StringUtils::sprintf("%s\\..\\errordb.txt", szProgramDir))) dputs(QT_TRANSLATE_NOOP("DBG", "Error codes database loaded!")); else dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load error codes...")); // Load exception codes if(ExceptionCodeInit(StringUtils::sprintf("%s\\..\\exceptiondb.txt", szProgramDir))) dputs(QT_TRANSLATE_NOOP("DBG", "Exception codes database loaded!")); else dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load exception codes...")); // Load NTSTATUS codes if(NtStatusCodeInit(StringUtils::sprintf("%s\\..\\ntstatusdb.txt", szProgramDir))) dputs(QT_TRANSLATE_NOOP("DBG", "NTSTATUS codes database loaded!")); else dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load NTSTATUS codes...")); // Load Windows constants if(ConstantCodeInit(StringUtils::sprintf("%s\\..\\winconstants.txt", szProgramDir))) dputs(QT_TRANSLATE_NOOP("DBG", "Windows constant database loaded!")); else dputs(QT_TRANSLATE_NOOP("DBG", "Failed to load Windows constants...")); // Load global notes dputs(QT_TRANSLATE_NOOP("DBG", "Reading notes file...")); notesFile = String(szUserDir) + "\\notes.txt"; String text; if(!FileExists(notesFile.c_str()) || FileHelper::ReadAllText(notesFile, text)) GuiSetGlobalNotes(text.c_str()); else dputs(QT_TRANSLATE_NOOP("DBG", "Reading notes failed...")); dputs(QT_TRANSLATE_NOOP("DBG", "File read thread finished!")); return 0; } static WString escape(WString cmdline) { StringUtils::ReplaceAll(cmdline, L"\\", L"\\\\"); StringUtils::ReplaceAll(cmdline, L"\"", L"\\\""); return cmdline; } extern "C" DLL_EXPORT const char* _dbg_dbginit() { if(!EngineCheckStructAlignment(UE_STRUCT_TITAN_ENGINE_CONTEXT, sizeof(TITAN_ENGINE_CONTEXT_t))) return "Invalid TITAN_ENGINE_CONTEXT_t alignment!"; static_assert(sizeof(TITAN_ENGINE_CONTEXT_t) == sizeof(REGISTERCONTEXT), "Invalid REGISTERCONTEXT alignment!"); strcpy_s(szDllLoaderPath, szProgramDir); strcat_s(szDllLoaderPath, "\\loaddll.exe"); #ifdef ENABLE_MEM_TRACE strcpy_s(alloctrace, szUserDir); strcat_s(alloctrace, "\\alloctrace.txt"); DeleteFileW(StringUtils::Utf8ToUtf16(alloctrace).c_str()); setalloctrace(alloctrace); #endif //ENABLE_MEM_TRACE dputs(QT_TRANSLATE_NOOP("DBG", "Initializing wait objects...")); waitinitialize(); SafeDbghelpInitialize(); dputs(QT_TRANSLATE_NOOP("DBG", "Initializing debugger...")); dbginit(); dputs(QT_TRANSLATE_NOOP("DBG", "Initializing debugger functions...")); dbgfunctionsinit(); //#ifdef ENABLE_MEM_TRACE dputs(QT_TRANSLATE_NOOP("DBG", "Setting JSON memory management functions...")); json_set_alloc_funcs(json_malloc, json_free); //#endif //ENABLE_MEM_TRACE dputs(QT_TRANSLATE_NOOP("DBG", "Initializing Zydis...")); Zydis::GlobalInitialize(); dputs(QT_TRANSLATE_NOOP("DBG", "Getting directory information...")); strcpy_s(scriptDllDir, szUserDir); strcat_s(scriptDllDir, "\\scripts\\"); initDataInstMap(); dputs(QT_TRANSLATE_NOOP("DBG", "Start file read thread...")); { auto hEvent = CreateEventW(nullptr, false, FALSE, nullptr); CloseHandle(CreateThread(nullptr, 0, loadDbThread, hEvent, 0, nullptr)); // Wait until the loadDbThread signals it's finished WaitForSingleObject(hEvent, INFINITE); CloseHandle(hEvent); } // Create database directory in the local debugger folder DbSetPath(StringUtils::sprintf("%s\\db", szUserDir).c_str(), nullptr); char szLocalSymbolPath[MAX_PATH] = ""; strcpy_s(szLocalSymbolPath, szUserDir); strcat_s(szLocalSymbolPath, "\\symbols"); Memory<char*> cachePath(MAX_SETTING_SIZE + 1); if(!BridgeSettingGet("Symbols", "CachePath", cachePath()) || !*cachePath()) { strcpy_s(szSymbolCachePath, szLocalSymbolPath); BridgeSettingSet("Symbols", "CachePath", ".\\symbols"); } else { if(_strnicmp(cachePath(), ".\\", 2) == 0) { strncpy_s(szSymbolCachePath, szUserDir, _TRUNCATE); strncat_s(szSymbolCachePath, cachePath() + 1, _TRUNCATE); } else { // Trim the buffer to fit inside MAX_PATH strncpy_s(szSymbolCachePath, cachePath(), _TRUNCATE); } if(strstr(szSymbolCachePath, "http://") || strstr(szSymbolCachePath, "https://")) { if(Script::Gui::MessageYesNo(GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "It is strongly discouraged to use symbol servers in your path directly (use the store option instead).\n\nDo you want me to fix this?")))) { strcpy_s(szSymbolCachePath, szLocalSymbolPath); BridgeSettingSet("Symbols", "CachePath", ".\\symbols"); } } } dprintf(QT_TRANSLATE_NOOP("DBG", "Symbol Path: %s\n"), szSymbolCachePath); dputs(QT_TRANSLATE_NOOP("DBG", "Allocating message stack...")); gMsgStack = MsgAllocStack(); if(!gMsgStack) return "Could not allocate message stack!"; dputs(QT_TRANSLATE_NOOP("DBG", "Initializing global script variables...")); varinit(); dputs(QT_TRANSLATE_NOOP("DBG", "Registering debugger commands...")); registercommands(); dputs(QT_TRANSLATE_NOOP("DBG", "Registering GUI command handler...")); ExpressionFunctions::Init(); dputs(QT_TRANSLATE_NOOP("DBG", "Registering expression functions...")); FormatFunctions::Init(); dputs(QT_TRANSLATE_NOOP("DBG", "Registering format functions...")); SCRIPTTYPEINFO info; strcpy_s(info.name, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Default"))); info.id = 0; info.execute = [](const char* cmd) { if(!DbgCmdExec(cmd)) return false; GuiFlushLog(); return true; }; info.completeCommand = nullptr; GuiRegisterScriptLanguage(&info); dputs(QT_TRANSLATE_NOOP("DBG", "Registering Script DLL command handler...")); strcpy_s(info.name, GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "Script DLL"))); info.execute = DbgScriptDllExec; GuiRegisterScriptLanguage(&info); dputs(QT_TRANSLATE_NOOP("DBG", "Starting command loop...")); hCommandLoopThread = CreateThread(nullptr, 0, DbgCommandLoopThread, nullptr, 0, nullptr); char plugindir[deflen] = ""; strcpy_s(plugindir, szProgramDir); strcat_s(plugindir, "\\plugins"); CreateDirectoryW(StringUtils::Utf8ToUtf16(plugindir).c_str(), nullptr); CreateDirectoryW(StringUtils::Utf8ToUtf16(StringUtils::sprintf("%s\\memdumps", szUserDir)).c_str(), nullptr); dputs(QT_TRANSLATE_NOOP("DBG", "Initialization successful!")); bIsStopped = false; dputs(QT_TRANSLATE_NOOP("DBG", "Loading plugins...")); pluginloadall(plugindir); dputs(QT_TRANSLATE_NOOP("DBG", "Handling command line...")); dprintf(" %s\n", StringUtils::Utf16ToUtf8(GetCommandLineW()).c_str()); //handle command line int argc = 0; wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); //MessageBoxW(0, GetCommandLineW(), StringUtils::sprintf(L"%d", argc).c_str(), MB_SYSTEMMODAL); if(argc == 2) //1 argument (init filename) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"init \"%s\"", escape(argv[1]).c_str())).c_str()); else if(argc == 3 && !_wcsicmp(argv[1], L"-p")) //2 arguments (-p PID) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"attach .%s", argv[2])).c_str()); //attach pid else if(argc == 3) //2 arguments (init filename, cmdline) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"init \"%s\", \"%s\"", escape(argv[1]).c_str(), escape(argv[2]).c_str())).c_str()); else if(argc == 4) //3 arguments (init filename, cmdline, currentdir) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"init \"%s\", \"%s\", \"%s\"", escape(argv[1]).c_str(), escape(argv[2]).c_str(), escape(argv[3]).c_str())).c_str()); else if(argc == 5 && (!_wcsicmp(argv[1], L"-a") || !_wcsicmp(argv[1], L"-p")) && !_wcsicmp(argv[3], L"-e")) //4 arguments (JIT) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"attach .%s, .%s", argv[2], argv[4])).c_str()); //attach pid, event else if(argc == 5 && !_wcsicmp(argv[1], L"-p") && !_wcsicmp(argv[3], L"-tid")) //4 arguments (PLMDebug) DbgCmdExec(StringUtils::Utf16ToUtf8(StringUtils::sprintf(L"attach .%s, 0, .%s", argv[2], argv[4])).c_str()); //attach pid, 0, tid LocalFree(argv); return nullptr; } /** @brief This function is called when the user closes the debugger. */ extern "C" DLL_EXPORT void _dbg_dbgexitsignal() { dputs(QT_TRANSLATE_NOOP("DBG", "Stopping command thread...")); bStopCommandLoopThread = true; MsgFreeStack(gMsgStack); WaitForThreadTermination(hCommandLoopThread); dputs(QT_TRANSLATE_NOOP("DBG", "Stopping running debuggee...")); cbDebugStop(0, 0); //after this, debugging stopped dputs(QT_TRANSLATE_NOOP("DBG", "Aborting scripts...")); scriptabort(); dputs(QT_TRANSLATE_NOOP("DBG", "Unloading plugins...")); pluginunloadall(); dputs(QT_TRANSLATE_NOOP("DBG", "Cleaning up allocated data...")); cmdfree(); varfree(); Zydis::GlobalFinalize(); dputs(QT_TRANSLATE_NOOP("DBG", "Cleaning up wait objects...")); waitdeinitialize(); SafeDbghelpDeinitialize(); dputs(QT_TRANSLATE_NOOP("DBG", "Cleaning up debugger threads...")); dbgstop(); dputs(QT_TRANSLATE_NOOP("DBG", "Saving notes...")); char* text = nullptr; GuiGetGlobalNotes(&text); if(text) { FileHelper::WriteAllText(notesFile, String(text)); BridgeFree(text); } else DeleteFileW(StringUtils::Utf8ToUtf16(notesFile).c_str()); dputs(QT_TRANSLATE_NOOP("DBG", "Exit signal processed successfully!")); #ifdef ENABLE_MEM_TRACE if(!memleaks()) DeleteFileW(StringUtils::Utf8ToUtf16(alloctrace).c_str()); #endif //ENABLE_MEM_TRACE bIsStopped = true; } extern "C" DLL_EXPORT bool _dbg_dbgcmddirectexec(const char* cmd) { return cmddirectexec(cmd); } bool dbgisstopped() { return bIsStopped; }
C/C++
x64dbg-development/src/dbg/x64dbg.h
#pragma once #include "_global.h" #ifdef __cplusplus extern "C" { #endif DLL_EXPORT const char* _dbg_dbginit(); DLL_EXPORT bool _dbg_dbgcmdexec(const char* cmd); DLL_EXPORT bool _dbg_dbgcmddirectexec(const char* cmd); DLL_EXPORT void _dbg_dbgexitsignal(); #ifdef __cplusplus } #endif bool dbgisstopped();
Visual C++ Project
x64dbg-development/src/dbg/x64dbg_dbg.vcxproj
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ClCompile Include="addrinfo.cpp" /> <ClCompile Include="analysis\advancedanalysis.cpp" /> <ClCompile Include="analysis\analysis.cpp" /> <ClCompile Include="analysis\AnalysisPass.cpp" /> <ClCompile Include="analysis\analysis_nukem.cpp" /> <ClCompile Include="analysis\CodeFollowPass.cpp" /> <ClCompile Include="analysis\controlflowanalysis.cpp" /> <ClCompile Include="analysis\exceptiondirectoryanalysis.cpp" /> <ClCompile Include="analysis\FunctionPass.cpp" /> <ClCompile Include="analysis\linearanalysis.cpp" /> <ClCompile Include="analysis\LinearPass.cpp" /> <ClCompile Include="analysis\recursiveanalysis.cpp" /> <ClCompile Include="analysis\xrefsanalysis.cpp" /> <ClCompile Include="animate.cpp" /> <ClCompile Include="argument.cpp" /> <ClCompile Include="assemble.cpp" /> <ClCompile Include="bookmark.cpp" /> <ClCompile Include="breakpoint.cpp" /> <ClCompile Include="btparser\btparser\lexer.cpp" /> <ClCompile Include="btparser\btparser\parser.cpp" /> <ClCompile Include="command.cpp" /> <ClCompile Include="commandline.cpp" /> <ClCompile Include="commandparser.cpp" /> <ClCompile Include="commands\cmd-analysis.cpp" /> <ClCompile Include="commands\cmd-breakpoint-control.cpp" /> <ClCompile Include="commands\cmd-conditional-breakpoint-control.cpp" /> <ClCompile Include="commands\cmd-searching.cpp" /> <ClCompile Include="commands\cmd-debug-control.cpp" /> <ClCompile Include="commands\cmd-general-purpose.cpp" /> <ClCompile Include="commands\cmd-gui.cpp" /> <ClCompile Include="commands\cmd-memory-operations.cpp" /> <ClCompile Include="commands\cmd-misc.cpp" /> <ClCompile Include="commands\cmd-operating-system-control.cpp" /> <ClCompile Include="commands\cmd-plugins.cpp" /> <ClCompile Include="commands\cmd-script.cpp" /> <ClCompile Include="commands\cmd-thread-control.cpp" /> <ClCompile Include="commands\cmd-tracing.cpp" /> <ClCompile Include="commands\cmd-types.cpp" /> <ClCompile Include="commands\cmd-undocumented.cpp" /> <ClCompile Include="commands\cmd-user-database.cpp" /> <ClCompile Include="commands\cmd-variables.cpp" /> <ClCompile Include="commands\cmd-watch-control.cpp" /> <ClCompile Include="comment.cpp" /> <ClCompile Include="console.cpp" /> <ClCompile Include="database.cpp" /> <ClCompile Include="datainst_helper.cpp" /> <ClCompile Include="dbghelp_safe.cpp" /> <ClCompile Include="debugger.cpp" /> <ClCompile Include="encodemap.cpp" /> <ClCompile Include="disasm_fast.cpp" /> <ClCompile Include="disasm_helper.cpp" /> <ClCompile Include="expressionfunctions.cpp" /> <ClCompile Include="exprfunc.cpp" /> <ClCompile Include="formatfunctions.cpp" /> <ClCompile Include="handles.cpp" /> <ClCompile Include="exception.cpp" /> <ClCompile Include="exhandlerinfo.cpp" /> <ClCompile Include="expressionparser.cpp" /> <ClCompile Include="filehelper.cpp" /> <ClCompile Include="function.cpp" /> <ClCompile Include="historycontext.cpp" /> <ClCompile Include="jit.cpp" /> <ClCompile Include="label.cpp" /> <ClCompile Include="loop.cpp" /> <ClCompile Include="main.cpp" /> <ClCompile Include="memory.cpp" /> <ClCompile Include="mnemonichelp.cpp" /> <ClCompile Include="module.cpp" /> <ClCompile Include="msdia\diacreate.cpp" /> <ClCompile Include="msgqueue.cpp" /> <ClCompile Include="murmurhash.cpp" /> <ClCompile Include="patches.cpp" /> <ClCompile Include="patternfind.cpp" /> <ClCompile Include="pdbdiafile.cpp" /> <ClCompile Include="plugin_loader.cpp" /> <ClCompile Include="reference.cpp" /> <ClCompile Include="simplescript.cpp" /> <ClCompile Include="stackinfo.cpp" /> <ClCompile Include="stringformat.cpp" /> <ClCompile Include="stringutils.cpp" /> <ClCompile Include="symbolinfo.cpp" /> <ClCompile Include="symbolsourcebase.cpp" /> <ClCompile Include="symbolsourcedia.cpp" /> <ClCompile Include="tcpconnections.cpp" /> <ClCompile Include="thread.cpp" /> <ClCompile Include="threading.cpp" /> <ClCompile Include="TraceRecord.cpp" /> <ClCompile Include="types.cpp" /> <ClCompile Include="typesparser.cpp" /> <ClCompile Include="value.cpp" /> <ClCompile Include="variable.cpp" /> <ClCompile Include="watch.cpp" /> <ClCompile Include="WinInet-Downloader\downslib.cpp" /> <ClCompile Include="x64dbg.cpp" /> <ClCompile Include="xrefs.cpp" /> <ClCompile Include="_exports.cpp" /> <ClCompile Include="_dbgfunctions.cpp" /> <ClCompile Include="_global.cpp" /> <ClCompile Include="_plugins.cpp" /> <ClCompile Include="_scriptapi_argument.cpp" /> <ClCompile Include="_scriptapi_assembler.cpp" /> <ClCompile Include="_scriptapi_bookmark.cpp" /> <ClCompile Include="_scriptapi_comment.cpp" /> <ClCompile Include="_scriptapi_debug.cpp" /> <ClCompile Include="_scriptapi_flag.cpp" /> <ClCompile Include="_scriptapi_function.cpp" /> <ClCompile Include="_scriptapi_gui.cpp" /> <ClCompile Include="_scriptapi_label.cpp" /> <ClCompile Include="_scriptapi_misc.cpp" /> <ClCompile Include="_scriptapi_pattern.cpp" /> <ClCompile Include="_scriptapi_memory.cpp" /> <ClCompile Include="_scriptapi_module.cpp" /> <ClCompile Include="_scriptapi_register.cpp" /> <ClCompile Include="_scriptapi_stack.cpp" /> <ClCompile Include="_scriptapi_symbol.cpp" /> </ItemGroup> <ItemGroup> <ClInclude Include="addrinfo.h" /> <ClInclude Include="analysis\advancedanalysis.h" /> <ClInclude Include="analysis\analysis.h" /> <ClInclude Include="analysis\AnalysisPass.h" /> <ClInclude Include="analysis\analysis_nukem.h" /> <ClInclude Include="analysis\BasicBlock.h" /> <ClInclude Include="analysis\CodeFollowPass.h" /> <ClInclude Include="analysis\controlflowanalysis.h" /> <ClInclude Include="analysis\exceptiondirectoryanalysis.h" /> <ClInclude Include="analysis\FunctionPass.h" /> <ClInclude Include="analysis\linearanalysis.h" /> <ClInclude Include="analysis\LinearPass.h" /> <ClInclude Include="analysis\recursiveanalysis.h" /> <ClInclude Include="analysis\xrefsanalysis.h" /> <ClInclude Include="animate.h" /> <ClInclude Include="argument.h" /> <ClInclude Include="assemble.h" /> <ClInclude Include="bookmark.h" /> <ClInclude Include="breakpoint.h" /> <ClInclude Include="btparser\btparser\ast.h" /> <ClInclude Include="btparser\btparser\helpers.h" /> <ClInclude Include="btparser\btparser\keywords.h" /> <ClInclude Include="btparser\btparser\lexer.h" /> <ClInclude Include="btparser\btparser\operators.h" /> <ClInclude Include="btparser\btparser\parser.h" /> <ClInclude Include="command.h" /> <ClInclude Include="commandline.h" /> <ClInclude Include="commandparser.h" /> <ClInclude Include="commands\cmd-all.h" /> <ClInclude Include="commands\cmd-analysis.h" /> <ClInclude Include="commands\cmd-breakpoint-control.h" /> <ClInclude Include="commands\cmd-conditional-breakpoint-control.h" /> <ClInclude Include="commands\cmd-searching.h" /> <ClInclude Include="commands\cmd-debug-control.h" /> <ClInclude Include="commands\cmd-general-purpose.h" /> <ClInclude Include="commands\cmd-gui.h" /> <ClInclude Include="commands\cmd-memory-operations.h" /> <ClInclude Include="commands\cmd-misc.h" /> <ClInclude Include="commands\cmd-operating-system-control.h" /> <ClInclude Include="commands\cmd-plugins.h" /> <ClInclude Include="commands\cmd-script.h" /> <ClInclude Include="commands\cmd-thread-control.h" /> <ClInclude Include="commands\cmd-tracing.h" /> <ClInclude Include="commands\cmd-types.h" /> <ClInclude Include="commands\cmd-undocumented.h" /> <ClInclude Include="commands\cmd-user-database.h" /> <ClInclude Include="commands\cmd-variables.h" /> <ClInclude Include="commands\cmd-watch-control.h" /> <ClInclude Include="comment.h" /> <ClInclude Include="console.h" /> <ClInclude Include="database.h" /> <ClInclude Include="datainst_helper.h" /> <ClInclude Include="dbghelp\dbghelp.h" /> <ClInclude Include="dbghelp_safe.h" /> <ClInclude Include="debugger.h" /> <ClInclude Include="debugger_cookie.h" /> <ClInclude Include="debugger_tracing.h" /> <ClInclude Include="encodemap.h" /> <ClInclude Include="DeviceNameResolver\DeviceNameResolver.h" /> <ClInclude Include="disasm_fast.h" /> <ClInclude Include="disasm_helper.h" /> <ClInclude Include="dynamicmem.h" /> <ClInclude Include="expressionfunctions.h" /> <ClInclude Include="exprfunc.h" /> <ClInclude Include="filemap.h" /> <ClInclude Include="formatfunctions.h" /> <ClInclude Include="GetPeArch.h" /> <ClInclude Include="handles.h" /> <ClInclude Include="exception.h" /> <ClInclude Include="exhandlerinfo.h" /> <ClInclude Include="expressionparser.h" /> <ClInclude Include="filehelper.h" /> <ClInclude Include="function.h" /> <ClInclude Include="historycontext.h" /> <ClInclude Include="jit.h" /> <ClInclude Include="handle.h" /> <ClInclude Include="jansson\jansson.h" /> <ClInclude Include="jansson\jansson_config.h" /> <ClInclude Include="jansson\jansson_x64dbg.h" /> <ClInclude Include="label.h" /> <ClInclude Include="LLVMDemangle\LLVMDemangle.h" /> <ClInclude Include="loop.h" /> <ClInclude Include="lz4\lz4.h" /> <ClInclude Include="lz4\lz4file.h" /> <ClInclude Include="lz4\lz4hc.h" /> <ClInclude Include="memory.h" /> <ClInclude Include="mnemonichelp.h" /> <ClInclude Include="module.h" /> <ClInclude Include="msdia\cvConst.h" /> <ClInclude Include="msdia\dia2.h" /> <ClInclude Include="msdia\diaCreate.h" /> <ClInclude Include="msgqueue.h" /> <ClInclude Include="murmurhash.h" /> <ClInclude Include="patches.h" /> <ClInclude Include="patternfind.h" /> <ClInclude Include="pdbdiafile.h" /> <ClInclude Include="pdbdiatypes.h" /> <ClInclude Include="plugin_loader.h" /> <ClInclude Include="reference.h" /> <ClInclude Include="serializablemap.h" /> <ClInclude Include="symbolsourcebase.h" /> <ClInclude Include="symbolsourcedia.h" /> <ClInclude Include="symbolundecorator.h" /> <ClInclude Include="syscalls.h" /> <ClInclude Include="taskthread.h" /> <ClInclude Include="tcpconnections.h" /> <ClInclude Include="TraceRecord.h" /> <ClInclude Include="types.h" /> <ClInclude Include="watch.h" /> <ClInclude Include="WinInet-Downloader\downslib.h" /> <ClInclude Include="xrefs.h" /> <ClInclude Include="_scriptapi.h" /> <ClInclude Include="simplescript.h" /> <ClInclude Include="stackinfo.h" /> <ClInclude Include="stringformat.h" /> <ClInclude Include="stringutils.h" /> <ClInclude Include="symbolinfo.h" /> <ClInclude Include="thread.h" /> <ClInclude Include="threading.h" /> <ClInclude Include="TitanEngine\TitanEngine.h" /> <ClInclude Include="ntdll\ntdll.h" /> <ClInclude Include="value.h" /> <ClInclude Include="variable.h" /> <ClInclude Include="x64dbg.h" /> <ClInclude Include="XEDParse\XEDParse.h" /> <ClInclude Include="_exports.h" /> <ClInclude Include="_dbgfunctions.h" /> <ClInclude Include="_global.h" /> <ClInclude Include="_plugins.h" /> <ClInclude Include="_plugin_types.h" /> <ClInclude Include="_scriptapi_argument.h" /> <ClInclude Include="_scriptapi_assembler.h" /> <ClInclude Include="_scriptapi_bookmark.h" /> <ClInclude Include="_scriptapi_comment.h" /> <ClInclude Include="_scriptapi_debug.h" /> <ClInclude Include="_scriptapi_flag.h" /> <ClInclude Include="_scriptapi_function.h" /> <ClInclude Include="_scriptapi_gui.h" /> <ClInclude Include="_scriptapi_label.h" /> <ClInclude Include="_scriptapi_misc.h" /> <ClInclude Include="_scriptapi_pattern.h" /> <ClInclude Include="_scriptapi_memory.h" /> <ClInclude Include="_scriptapi_module.h" /> <ClInclude Include="_scriptapi_register.h" /> <ClInclude Include="_scriptapi_stack.h" /> <ClInclude Include="_scriptapi_symbol.h" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\bridge\x64dbg_bridge.vcxproj"> <Project>{944d9923-cb1a-6f6c-bcbc-9e00a71954c1}</Project> <Private>true</Private> <ReferenceOutputAssembly>true</ReferenceOutputAssembly> <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies> <LinkLibraryDependencies>true</LinkLibraryDependencies> <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs> </ProjectReference> <ProjectReference Include="..\zydis_wrapper\zydis_wrapper.vcxproj"> <Project>{3b2c1ee1-fdec-4d85-be46-3c6a5ea69883}</Project> </ProjectReference> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{E6548308-401E-3A8A-5819-905DB90522A6}</ProjectGuid> <Keyword>Win32Proj</Keyword> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v120_xp</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x32\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <TargetName>x32dbg</TargetName> <IncludePath>$(ProjectDir)..\zydis_wrapper;$(ProjectDir)..\zydis_wrapper\zydis\include;$(ProjectDir);$(ProjectDir)analysis;$(ProjectDir)commands;$(IncludePath)</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x32d\</OutDir> <IntDir>$(Platform)\$(Configuration)\</IntDir> <TargetName>x32dbg</TargetName> <IncludePath>$(ProjectDir)..\zydis_wrapper;$(ProjectDir)..\zydis_wrapper\zydis\include;$(ProjectDir);$(ProjectDir)analysis;$(ProjectDir)commands;$(IncludePath)</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x64\</OutDir> <TargetName>x64dbg</TargetName> <IncludePath>$(ProjectDir)..\zydis_wrapper;$(ProjectDir)..\zydis_wrapper\zydis\include;$(ProjectDir);$(ProjectDir)analysis;$(ProjectDir)commands;$(IncludePath)</IncludePath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>false</LinkIncremental> <OutDir>$(ProjectDir)..\..\bin\x64d\</OutDir> <TargetName>x64dbg</TargetName> <IncludePath>$(ProjectDir)..\zydis_wrapper;$(ProjectDir)..\zydis_wrapper\zydis\include;$(ProjectDir);$(ProjectDir)analysis;$(ProjectDir)commands;$(IncludePath)</IncludePath> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;BUILD_DBG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <MultiProcessorCompilation>true</MultiProcessorCompilation> <InterproceduralOptimization>MultiFile</InterproceduralOptimization> <OptimizeForWindowsApplication>true</OptimizeForWindowsApplication> <UseIntelOptimizedHeaders>true</UseIntelOptimizedHeaders> <GenerateAlternateCodePaths>AVXI</GenerateAlternateCodePaths> <LevelOfStaticAnalysis>None</LevelOfStaticAnalysis> <ModeOfStaticAnalysis>None</ModeOfStaticAnalysis> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalDependencies>LLVMDemangle\LLVMDemangle_x86.lib;ntdll\ntdll_x86.lib;lz4\lz4_x86.lib;jansson\jansson_x86.lib;DeviceNameResolver\DeviceNameResolver_x86.lib;XEDParse\XEDParse_x86.lib;dbghelp\dbghelp_x86.lib;TitanEngine\TitanEngine_x86.lib;ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;BUILD_DBG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <MultiProcessorCompilation>true</MultiProcessorCompilation> <InterproceduralOptimization>NoIPO</InterproceduralOptimization> <OptimizeForWindowsApplication>false</OptimizeForWindowsApplication> <UseIntelOptimizedHeaders>true</UseIntelOptimizedHeaders> <Optimization>Disabled</Optimization> </ClCompile> <Link> <TargetMachine>MachineX86</TargetMachine> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>false</EnableCOMDATFolding> <OptimizeReferences>false</OptimizeReferences> <AdditionalDependencies>LLVMDemangle\LLVMDemangle_x86.lib;ntdll\ntdll_x86.lib;lz4\lz4_x86.lib;jansson\jansson_x86.lib;DeviceNameResolver\DeviceNameResolver_x86.lib;XEDParse\XEDParse_x86.lib;dbghelp\dbghelp_x86.lib;TitanEngine\TitanEngine_x86.lib;ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies> <DelayLoadDLLs>TitanEngine.dll</DelayLoadDLLs> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;BUILD_DBG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <MultiProcessorCompilation>true</MultiProcessorCompilation> <InterproceduralOptimization>MultiFile</InterproceduralOptimization> <OptimizeForWindowsApplication>true</OptimizeForWindowsApplication> <UseIntelOptimizedHeaders>true</UseIntelOptimizedHeaders> <GenerateAlternateCodePaths>AVXI</GenerateAlternateCodePaths> <LevelOfStaticAnalysis>None</LevelOfStaticAnalysis> <ModeOfStaticAnalysis>None</ModeOfStaticAnalysis> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <UseProcessorExtensions>AVXI</UseProcessorExtensions> <CheckUndimensionedArrays>false</CheckUndimensionedArrays> <CheckPointers>None</CheckPointers> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalDependencies>LLVMDemangle\LLVMDemangle_x64.lib;ntdll\ntdll_x64.lib;lz4\lz4_x64.lib;jansson\jansson_x64.lib;DeviceNameResolver\DeviceNameResolver_x64.lib;XEDParse\XEDParse_x64.lib;dbghelp\dbghelp_x64.lib;TitanEngine\TitanEngine_x64.lib;ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;BUILD_DBG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <MultiProcessorCompilation>true</MultiProcessorCompilation> <InterproceduralOptimization>NoIPO</InterproceduralOptimization> <OptimizeForWindowsApplication>false</OptimizeForWindowsApplication> <UseIntelOptimizedHeaders>false</UseIntelOptimizedHeaders> <Optimization>Disabled</Optimization> <CheckPointers>None</CheckPointers> <CheckDanglingPointers>None</CheckDanglingPointers> <CheckUndimensionedArrays>false</CheckUndimensionedArrays> <EnableExpandedLineNumberInfo>true</EnableExpandedLineNumberInfo> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>false</EnableCOMDATFolding> <OptimizeReferences>false</OptimizeReferences> <AdditionalDependencies>LLVMDemangle\LLVMDemangle_x64.lib;ntdll\ntdll_x64.lib;lz4\lz4_x64.lib;jansson\jansson_x64.lib;DeviceNameResolver\DeviceNameResolver_x64.lib;XEDParse\XEDParse_x64.lib;dbghelp\dbghelp_x64.lib;TitanEngine\TitanEngine_x64.lib;ws2_32.lib;psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies> <DelayLoadDLLs>TitanEngine.dll</DelayLoadDLLs> </Link> </ItemDefinitionGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
x64dbg-development/src/dbg/x64dbg_dbg.vcxproj.filters
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Source Files\Interfaces/Exports"> <UniqueIdentifier>{44fd9eb7-2017-49b8-8d9a-dec680632343}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Core"> <UniqueIdentifier>{148408a8-bfe7-4d36-a04a-64d645a3e713}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Information"> <UniqueIdentifier>{687e60a0-5c44-481b-9149-9bd4cc41aaf8}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Utilities"> <UniqueIdentifier>{abc27485-7d81-4847-8ffe-62b0838f4ba4}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Debugger Core"> <UniqueIdentifier>{52e2c3ae-0223-4216-b896-41d9f171f731}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Debugger Core"> <UniqueIdentifier>{164592cf-e2c9-4c98-abf6-ea47d37653a1}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party"> <UniqueIdentifier>{d2362bf7-ff20-493d-be01-0fb7e6dca8c9}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\ntdll"> <UniqueIdentifier>{aea02a5a-fad2-4cf4-a932-80c0d43f621e}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\TitanEngine"> <UniqueIdentifier>{23226861-3b20-42db-8dd6-c5d276ba7a83}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\XEDParse"> <UniqueIdentifier>{6b85ff77-8866-4618-9d46-006d8c349f8f}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\dbghelp"> <UniqueIdentifier>{5623fb24-3b6d-49a6-a0d3-1cfcc46f87bd}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\DeviceNameResolver"> <UniqueIdentifier>{f4eb1487-15d6-4836-9d20-339d0f18c31f}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\jansson"> <UniqueIdentifier>{b63305e2-2b10-46eb-839f-5e9080fa8ad8}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\lz4"> <UniqueIdentifier>{6a8d58f0-1417-4bff-aecd-0f9f5e0641f9}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Interfaces/Exports"> <UniqueIdentifier>{714f2eb1-20d7-47ed-a641-ba8a66da2e7a}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Utilities"> <UniqueIdentifier>{938130d5-63d6-44c2-9604-70f1f101890c}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Core"> <UniqueIdentifier>{ccf4c0a0-bb97-4090-acc5-bc6b343300bf}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Information"> <UniqueIdentifier>{b006b04c-d7ea-49cb-b097-0cac1388f98e}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Analysis"> <UniqueIdentifier>{3aba2399-cfdf-40be-9265-2062f983bbfd}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Analysis"> <UniqueIdentifier>{a2a92bf5-753d-4a01-be80-66cc61434fbf}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Interfaces/Exports\_scriptapi"> <UniqueIdentifier>{4d81f6f8-bb8a-457b-b372-932857e99035}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Interfaces/Exports\_scriptapi"> <UniqueIdentifier>{eb7d9981-6079-4b4b-af18-e44e63451d10}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Commands"> <UniqueIdentifier>{c753866f-f2d5-4469-b8b0-0c7a6cea607e}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Commands"> <UniqueIdentifier>{c42aba29-6104-475b-9838-ffa2034485aa}</UniqueIdentifier> </Filter> <Filter Include="Source Files\btparser"> <UniqueIdentifier>{3e5a02e2-62ad-4251-a53a-ab3f34fd7dd9}</UniqueIdentifier> </Filter> <Filter Include="Header Files\btparser"> <UniqueIdentifier>{d20554d2-b3de-4e73-ac55-217da06783ba}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\msdia"> <UniqueIdentifier>{638ee3a0-ab1a-4bb2-bb14-59461ddf86b2}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Symbols"> <UniqueIdentifier>{087f2c70-08a6-4b80-988e-81be42c80580}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Symbols"> <UniqueIdentifier>{1f9e6c1d-74b2-4f72-bbe2-5fa68094d5fd}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Third Party"> <UniqueIdentifier>{73b6410d-7eef-4131-a04f-56abc14d84f5}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Third Party\WinInet-Downloader"> <UniqueIdentifier>{e47a911a-a6f6-415d-9eec-4f79f478d0a0}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\WinInet-Downloader"> <UniqueIdentifier>{cdf955c6-b066-4b06-87f0-7a02b9bbfc55}</UniqueIdentifier> </Filter> <Filter Include="Source Files\Third Party\msdia"> <UniqueIdentifier>{dc4f0ea0-8d28-4d9e-a8ac-901dd274787d}</UniqueIdentifier> </Filter> <Filter Include="Header Files\Third Party\LLVMDemangle"> <UniqueIdentifier>{62118289-8fde-487b-b0db-0164e34ce3b4}</UniqueIdentifier> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="main.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="_dbgfunctions.cpp"> <Filter>Source Files\Interfaces/Exports</Filter> </ClCompile> <ClCompile Include="_exports.cpp"> <Filter>Source Files\Interfaces/Exports</Filter> </ClCompile> <ClCompile Include="_plugins.cpp"> <Filter>Source Files\Interfaces/Exports</Filter> </ClCompile> <ClCompile Include="_global.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="command.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="console.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="threading.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="value.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="variable.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="addrinfo.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="breakpoint.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="assemble.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="disasm_fast.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="disasm_helper.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="plugin_loader.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="reference.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="simplescript.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="stackinfo.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="debugger.cpp"> <Filter>Source Files\Debugger Core</Filter> </ClCompile> <ClCompile Include="stringutils.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="murmurhash.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="msgqueue.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="label.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="module.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="comment.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="bookmark.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="function.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="loop.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="exception.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="memory.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="patches.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="thread.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="patternfind.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="dbghelp_safe.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="stringformat.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="commandparser.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="expressionparser.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="_scriptapi_module.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_register.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_memory.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_debug.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_pattern.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_gui.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_assembler.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_misc.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_stack.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_flag.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="filehelper.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="database.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="jit.cpp"> <Filter>Source Files\Debugger Core</Filter> </ClCompile> <ClCompile Include="commandline.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="_scriptapi_label.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_comment.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_bookmark.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_function.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="_scriptapi_symbol.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="exhandlerinfo.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="TraceRecord.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="mnemonichelp.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="handles.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="tcpconnections.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="xrefs.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="argument.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="_scriptapi_argument.cpp"> <Filter>Source Files\Interfaces/Exports\_scriptapi</Filter> </ClCompile> <ClCompile Include="encodemap.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="datainst_helper.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="expressionfunctions.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="historycontext.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="watch.cpp"> <Filter>Source Files\Information</Filter> </ClCompile> <ClCompile Include="analysis\advancedanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\analysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\analysis_nukem.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\AnalysisPass.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\CodeFollowPass.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\controlflowanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\exceptiondirectoryanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\FunctionPass.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\linearanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\LinearPass.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\recursiveanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="analysis\xrefsanalysis.cpp"> <Filter>Source Files\Analysis</Filter> </ClCompile> <ClCompile Include="exprfunc.cpp"> <Filter>Source Files\Debugger Core</Filter> </ClCompile> <ClCompile Include="animate.cpp"> <Filter>Source Files\Utilities</Filter> </ClCompile> <ClCompile Include="commands\cmd-analysis.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-breakpoint-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-conditional-breakpoint-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-searching.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-debug-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-general-purpose.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-gui.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-memory-operations.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-misc.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-operating-system-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-plugins.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-script.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-thread-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-tracing.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-types.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-undocumented.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-user-database.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-variables.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="commands\cmd-watch-control.cpp"> <Filter>Source Files\Commands</Filter> </ClCompile> <ClCompile Include="x64dbg.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="types.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="btparser\btparser\lexer.cpp"> <Filter>Source Files\btparser</Filter> </ClCompile> <ClCompile Include="btparser\btparser\parser.cpp"> <Filter>Source Files\btparser</Filter> </ClCompile> <ClCompile Include="typesparser.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="formatfunctions.cpp"> <Filter>Source Files\Core</Filter> </ClCompile> <ClCompile Include="symbolinfo.cpp"> <Filter>Source Files\Symbols</Filter> </ClCompile> <ClCompile Include="pdbdiafile.cpp"> <Filter>Source Files\Symbols</Filter> </ClCompile> <ClCompile Include="symbolsourcedia.cpp"> <Filter>Source Files\Symbols</Filter> </ClCompile> <ClCompile Include="msdia\diacreate.cpp"> <Filter>Source Files\Third Party\msdia</Filter> </ClCompile> <ClCompile Include="WinInet-Downloader\downslib.cpp"> <Filter>Source Files\Third Party\WinInet-Downloader</Filter> </ClCompile> <ClCompile Include="symbolsourcebase.cpp"> <Filter>Source Files\Symbols</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="dbghelp\dbghelp.h"> <Filter>Header Files\Third Party\dbghelp</Filter> </ClInclude> <ClInclude Include="XEDParse\XEDParse.h"> <Filter>Header Files\Third Party\XEDParse</Filter> </ClInclude> <ClInclude Include="ntdll\ntdll.h"> <Filter>Header Files\Third Party\ntdll</Filter> </ClInclude> <ClInclude Include="TitanEngine\TitanEngine.h"> <Filter>Header Files\Third Party\TitanEngine</Filter> </ClInclude> <ClInclude Include="DeviceNameResolver\DeviceNameResolver.h"> <Filter>Header Files\Third Party\DeviceNameResolver</Filter> </ClInclude> <ClInclude Include="jansson\jansson.h"> <Filter>Header Files\Third Party\jansson</Filter> </ClInclude> <ClInclude Include="jansson\jansson_config.h"> <Filter>Header Files\Third Party\jansson</Filter> </ClInclude> <ClInclude Include="lz4\lz4.h"> <Filter>Header Files\Third Party\lz4</Filter> </ClInclude> <ClInclude Include="lz4\lz4file.h"> <Filter>Header Files\Third Party\lz4</Filter> </ClInclude> <ClInclude Include="lz4\lz4hc.h"> <Filter>Header Files\Third Party\lz4</Filter> </ClInclude> <ClInclude Include="_global.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="console.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="command.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="threading.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="value.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="variable.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="plugin_loader.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="debugger.h"> <Filter>Header Files\Debugger Core</Filter> </ClInclude> <ClInclude Include="addrinfo.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="breakpoint.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="stackinfo.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="_plugins.h"> <Filter>Header Files\Interfaces/Exports</Filter> </ClInclude> <ClInclude Include="_exports.h"> <Filter>Header Files\Interfaces/Exports</Filter> </ClInclude> <ClInclude Include="_dbgfunctions.h"> <Filter>Header Files\Interfaces/Exports</Filter> </ClInclude> <ClInclude Include="_plugin_types.h"> <Filter>Header Files\Interfaces/Exports</Filter> </ClInclude> <ClInclude Include="assemble.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="disasm_fast.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="disasm_helper.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="reference.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="simplescript.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="dynamicmem.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="handle.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="stringutils.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="murmurhash.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="msgqueue.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="module.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="comment.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="label.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="bookmark.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="function.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="loop.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="patches.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="exception.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="memory.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="thread.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="patternfind.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="dbghelp_safe.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="stringformat.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="commandparser.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="jansson\jansson_x64dbg.h"> <Filter>Header Files\Third Party\jansson</Filter> </ClInclude> <ClInclude Include="expressionparser.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="_scriptapi_debug.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_memory.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_module.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_register.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_pattern.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_gui.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_stack.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_assembler.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_misc.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_flag.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="filehelper.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="database.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="jit.h"> <Filter>Header Files\Debugger Core</Filter> </ClInclude> <ClInclude Include="commandline.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="_scriptapi_label.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_comment.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_bookmark.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_function.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="_scriptapi_symbol.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="exhandlerinfo.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="mnemonichelp.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="TraceRecord.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="handles.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="tcpconnections.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="xrefs.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="argument.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="serializablemap.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="_scriptapi_argument.h"> <Filter>Header Files\Interfaces/Exports\_scriptapi</Filter> </ClInclude> <ClInclude Include="encodemap.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="datainst_helper.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="historycontext.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="watch.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="taskthread.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="expressionfunctions.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="analysis\advancedanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\analysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\analysis_nukem.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\AnalysisPass.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\BasicBlock.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\CodeFollowPass.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\controlflowanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\exceptiondirectoryanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\FunctionPass.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\linearanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\LinearPass.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\recursiveanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="analysis\xrefsanalysis.h"> <Filter>Header Files\Analysis</Filter> </ClInclude> <ClInclude Include="exprfunc.h"> <Filter>Header Files\Debugger Core</Filter> </ClInclude> <ClInclude Include="animate.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="commands\cmd-breakpoint-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-conditional-breakpoint-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-debug-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-general-purpose.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-memory-operations.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-operating-system-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-thread-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-tracing.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-watch-control.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-variables.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-searching.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-user-database.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-analysis.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-types.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-plugins.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-script.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-misc.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-undocumented.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-all.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="commands\cmd-gui.h"> <Filter>Header Files\Commands</Filter> </ClInclude> <ClInclude Include="x64dbg.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="types.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="btparser\btparser\ast.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="btparser\btparser\keywords.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="btparser\btparser\lexer.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="btparser\btparser\operators.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="btparser\btparser\parser.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="btparser\btparser\helpers.h"> <Filter>Header Files\btparser</Filter> </ClInclude> <ClInclude Include="filemap.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="formatfunctions.h"> <Filter>Header Files\Core</Filter> </ClInclude> <ClInclude Include="GetPeArch.h"> <Filter>Header Files\Utilities</Filter> </ClInclude> <ClInclude Include="debugger_cookie.h"> <Filter>Header Files\Debugger Core</Filter> </ClInclude> <ClInclude Include="debugger_tracing.h"> <Filter>Header Files\Debugger Core</Filter> </ClInclude> <ClInclude Include="msdia\cvConst.h"> <Filter>Header Files\Third Party\msdia</Filter> </ClInclude> <ClInclude Include="msdia\dia2.h"> <Filter>Header Files\Third Party\msdia</Filter> </ClInclude> <ClInclude Include="msdia\diaCreate.h"> <Filter>Header Files\Third Party\msdia</Filter> </ClInclude> <ClInclude Include="symbolsourcebase.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="symbolinfo.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="pdbdiatypes.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="pdbdiafile.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="symbolsourcedia.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="WinInet-Downloader\downslib.h"> <Filter>Header Files\Third Party\WinInet-Downloader</Filter> </ClInclude> <ClInclude Include="symbolundecorator.h"> <Filter>Header Files\Symbols</Filter> </ClInclude> <ClInclude Include="syscalls.h"> <Filter>Header Files\Information</Filter> </ClInclude> <ClInclude Include="LLVMDemangle\LLVMDemangle.h"> <Filter>Header Files\Third Party\LLVMDemangle</Filter> </ClInclude> </ItemGroup> </Project>
C++
x64dbg-development/src/dbg/xrefs.cpp
#include "xrefs.h" #include "addrinfo.h" struct XREFSINFO : AddrInfo { XREFTYPE type = XREF_NONE; std::unordered_map<duint, XREF_RECORD> references; }; struct XrefSerializer : AddrInfoSerializer<XREFSINFO> { bool Save(const XREFSINFO & value) override { AddrInfoSerializer::Save(value); auto references = json_array(); for(const auto & itr : value.references) { auto reference = json_object(); json_object_set_new(reference, "addr", json_hex(itr.second.addr)); json_object_set_new(reference, "type", json_hex(itr.second.type)); json_array_append_new(references, reference); } set("references", references); return true; } bool Load(XREFSINFO & value) override { if(!AddrInfoSerializer::Load(value)) return false; auto references = get("references"); if(!references) return false; value.type = XREF_DATA; size_t i; JSON reference; json_array_foreach(references, i, reference) { XREF_RECORD record; record.addr = duint(json_hex_value(json_object_get(reference, "addr"))); record.type = XREFTYPE(json_hex_value(json_object_get(reference, "type"))); value.type = max(record.type, value.type); value.references.emplace(record.addr, record); } return true; } }; struct Xrefs : AddrInfoHashMap<LockCrossReferences, XREFSINFO, XrefSerializer> { const char* jsonKey() const override { return "xrefs"; } }; static Xrefs xrefs; bool XrefAdd(duint Address, duint From) { XREF_EDGE edge = { Address, From }; return XrefAddMulti(&edge, 1) == 1; } duint XrefAddMulti(const XREF_EDGE* Edges, duint Count) { // These types are used in a cache to improve performance struct FromInfo { bool valid = false; duint moduleBase = 0; duint moduleSize = 0; XREF_RECORD xrefRecord{}; explicit FromInfo(duint from) { if(!MemIsValidReadPtr(from)) return; { SHARED_ACQUIRE(LockModules); auto module = ModInfoFromAddr(from); if(!module) return; moduleBase = module->base; moduleSize = module->size; } BASIC_INSTRUCTION_INFO instInfo; DbgDisasmFastAt(from, &instInfo); xrefRecord.addr = from - moduleBase; if(instInfo.call) xrefRecord.type = XREF_CALL; else if(instInfo.branch) xrefRecord.type = XREF_JMP; else xrefRecord.type = XREF_DATA; valid = true; } }; struct AddressInfo { bool valid = false; XREFSINFO* info = nullptr; explicit AddressInfo(duint address) { XREFSINFO preparedInfo; if(!xrefs.PrepareValue(preparedInfo, address, false)) return; auto key = Xrefs::VaKey(address); auto & mapData = xrefs.GetDataUnsafe(); auto insertResult = mapData.emplace(key, preparedInfo); info = &insertResult.first->second; valid = true; } }; EXCLUSIVE_ACQUIRE(LockCrossReferences); std::unordered_map<duint, FromInfo> fromCache; std::unordered_map<duint, AddressInfo> addressCache; duint succeeded = 0; for(duint i = 0; i < Count; i++) { duint address = Edges[i].address; duint from = Edges[i].from; auto fromCacheIt = fromCache.find(from); if(fromCacheIt == fromCache.end()) fromCacheIt = fromCache.emplace(from, FromInfo(from)).first; const auto & fromInfo = fromCacheIt->second; if(!fromInfo.valid) continue; if(address < fromInfo.moduleBase || address >= fromInfo.moduleBase + fromInfo.moduleSize) continue; auto addressCacheIt = addressCache.find(address); if(addressCacheIt == addressCache.end()) addressCacheIt = addressCache.emplace(address, AddressInfo(address)).first; const auto & addressInfo = addressCacheIt->second; if(!addressInfo.valid) continue; auto & info = *addressInfo.info; auto & xrefRecord = fromInfo.xrefRecord; info.references.emplace(xrefRecord.addr, xrefRecord); info.type = max(info.type, xrefRecord.type); succeeded++; } return succeeded; } bool XrefGet(duint Address, XREF_INFO* List) { SHARED_ACQUIRE(LockCrossReferences); auto & mapData = xrefs.GetDataUnsafe(); auto found = mapData.find(Xrefs::VaKey(Address)); if(found == mapData.end()) return false; if(List->refcount != found->second.references.size()) return false; auto moduleBase = ModBaseFromAddr(Address); auto ptr = List->references; for(const auto & itr : found->second.references) { *ptr = itr.second; ptr->addr += moduleBase; ++ptr; } return true; } duint XrefGetCount(duint Address) { SHARED_ACQUIRE(LockCrossReferences); auto & mapData = xrefs.GetDataUnsafe(); auto found = mapData.find(Xrefs::VaKey(Address)); return found == mapData.end() ? 0 : found->second.references.size(); } XREFTYPE XrefGetType(duint Address) { SHARED_ACQUIRE(LockCrossReferences); auto & mapData = xrefs.GetDataUnsafe(); auto found = mapData.find(Xrefs::VaKey(Address)); return found == mapData.end() ? XREF_NONE : found->second.type; } bool XrefDeleteAll(duint Address) { return xrefs.Delete(Xrefs::VaKey(Address)); } void XrefDelRange(duint Start, duint End) { xrefs.DeleteRange(Start, End, false); } void XrefCacheSave(JSON Root) { xrefs.CacheSave(Root); } void XrefCacheLoad(JSON Root) { xrefs.CacheLoad(Root); } void XrefClear() { xrefs.Clear(); }
C/C++
x64dbg-development/src/dbg/xrefs.h
#ifndef _XREFS_H #define _XREFS_H #include "_global.h" #include "jansson/jansson_x64dbg.h" bool XrefAdd(duint Address, duint From); duint XrefAddMulti(const XREF_EDGE* Edges, duint Count); bool XrefGet(duint Address, XREF_INFO* List); duint XrefGetCount(duint Address); XREFTYPE XrefGetType(duint Address); bool XrefDeleteAll(duint Address); void XrefDelRange(duint Start, duint End); void XrefCacheSave(JSON Root); void XrefCacheLoad(JSON Root); void XrefClear(); #endif // _FUNCTION_H
C++
x64dbg-development/src/dbg/_dbgfunctions.cpp
/** @file _dbgfunctions.cpp @brief Implements the dbgfunctions class. */ #include "_global.h" #include "_dbgfunctions.h" #include "assemble.h" #include "debugger.h" #include "jit.h" #include "patches.h" #include "memory.h" #include "disasm_fast.h" #include "stackinfo.h" #include "symbolinfo.h" #include "module.h" #include "exhandlerinfo.h" #include "breakpoint.h" #include "threading.h" #include "stringformat.h" #include "TraceRecord.h" #include "mnemonichelp.h" #include "handles.h" #include "../bridge/bridgelist.h" #include "tcpconnections.h" #include "watch.h" #include "animate.h" #include "thread.h" #include "comment.h" #include "exception.h" #include "database.h" #include "dbghelp_safe.h" static DBGFUNCTIONS _dbgfunctions; const DBGFUNCTIONS* dbgfunctionsget() { return &_dbgfunctions; } static bool _assembleatex(duint addr, const char* instruction, char* error, bool fillnop) { return assembleat(addr, instruction, nullptr, error, fillnop); } static bool _sectionfromaddr(duint addr, char* section) { std::vector<MODSECTIONINFO> sections; if(ModSectionsFromAddr(addr, &sections)) { for(const auto & cur : sections) { if(addr >= cur.addr && addr < cur.addr + (cur.size + (0x1000 - 1) & ~(0x1000 - 1))) { strncpy_s(section, MAX_SECTION_SIZE * 5, cur.name, _TRUNCATE); return true; } } } return false; } static bool _patchget(duint addr) { return PatchGet(addr, nullptr); } static bool _patchinrange(duint start, duint end) { if(start > end) std::swap(start, end); for(duint i = start; i <= end; i++) { if(_patchget(i)) return true; } return false; } static bool _mempatch(duint va, const unsigned char* src, duint size) { return MemPatch(va, src, size, nullptr); } static void _patchrestorerange(duint start, duint end) { if(start > end) std::swap(start, end); for(duint i = start; i <= end; i++) PatchDelete(i, true); GuiUpdatePatches(); } static bool _patchrestore(duint addr) { return PatchDelete(addr, true); } static void _getcallstack(DBGCALLSTACK* callstack) { if(hActiveThread) stackgetcallstack(GetContextDataEx(hActiveThread, UE_CSP), (CALLSTACK*)callstack); } static void _getcallstackbythread(HANDLE thread, DBGCALLSTACK* callstack) { if(thread) stackgetcallstackbythread(thread, (CALLSTACK*)callstack); } static void _getsehchain(DBGSEHCHAIN* sehchain) { std::vector<duint> SEHList; ExHandlerGetSEH(SEHList); sehchain->total = SEHList.size(); if(sehchain->total > 0) { sehchain->records = (DBGSEHRECORD*)BridgeAlloc(sehchain->total * sizeof(DBGSEHRECORD)); for(size_t i = 0; i < sehchain->total; i++) { sehchain->records[i].addr = SEHList[i]; MemRead(SEHList[i] + 4, &sehchain->records[i].handler, sizeof(duint)); } } else { sehchain->records = nullptr; } } static bool _getjitauto(bool* jit_auto) { return dbggetjitauto(jit_auto, notfound, NULL, NULL); } static bool _getcmdline(char* cmd_line, size_t* cbsize) { if(!cmd_line && !cbsize) return false; char* cmdline; if(!dbggetcmdline(&cmdline, NULL, fdProcessInfo->hProcess)) return false; if(!cmd_line && cbsize) *cbsize = strlen(cmdline) + sizeof(char); else if(cmd_line) memcpy(cmd_line, cmdline, strlen(cmdline) + 1); efree(cmdline, "_getcmdline:cmdline"); return true; } static bool _setcmdline(const char* cmd_line) { return dbgsetcmdline(cmd_line, nullptr); } static bool _getjit(char* jit, bool jit64) { arch dummy; char jit_tmp[JIT_ENTRY_MAX_SIZE] = ""; if(jit != NULL) { if(!dbggetjit(jit_tmp, jit64 ? x64 : x32, &dummy, NULL)) return false; strcpy_s(jit, MAX_SETTING_SIZE, jit_tmp); } else // if jit input == NULL: it returns false if there are not an OLD JIT STORED. { Memory<char*> oldjit(MAX_SETTING_SIZE + 1); if(!BridgeSettingGet("JIT", "Old", oldjit())) return false; } return true; } static bool _getprocesslist(DBGPROCESSINFO** entries, int* count) { std::vector<PROCESSENTRY32> infoList; std::vector<std::string> commandList; std::vector<std::string> winTextList; if(!dbglistprocesses(&infoList, &commandList, &winTextList)) return false; *count = (int)infoList.size(); if(!*count) { *entries = nullptr; return false; } *entries = (DBGPROCESSINFO*)BridgeAlloc(*count * sizeof(DBGPROCESSINFO)); for(int i = 0; i < *count; i++) { (*entries)[*count - i - 1].dwProcessId = infoList.at(i).th32ProcessID; strncpy_s((*entries)[*count - i - 1].szExeFile, infoList.at(i).szExeFile, _TRUNCATE); strncpy_s((*entries)[*count - i - 1].szExeMainWindowTitle, winTextList.at(i).c_str(), _TRUNCATE); strncpy_s((*entries)[*count - i - 1].szExeArgs, commandList.at(i).c_str(), _TRUNCATE); } return true; } static void _memupdatemap() { MemUpdateMap(); GuiUpdateMemoryView(); } static duint _getaddrfromline(const char* szSourceFile, int line, duint* disp) { if(disp) *disp = 0; return 0; } static duint _getaddrfromlineex(duint mod, const char* szSourceFile, int line) { duint addr = 0; if(SymGetSourceAddr(mod, szSourceFile, line, &addr)) return addr; return 0; } static bool _getsourcefromaddr(duint addr, char* szSourceFile, int* line) { char sourceFile[MAX_STRING_SIZE] = ""; if(!SymGetSourceLine(addr, sourceFile, line)) return false; if(!FileExists(sourceFile)) return false; if(szSourceFile) strcpy_s(szSourceFile, MAX_STRING_SIZE, sourceFile); return true; } static bool _valfromstring(const char* string, duint* value) { return valfromstring(string, value); } static bool _getbridgebp(BPXTYPE type, duint addr, BRIDGEBP* bp) { BP_TYPE bptype; switch(type) { case bp_normal: bptype = BPNORMAL; break; case bp_hardware: bptype = BPHARDWARE; break; case bp_memory: bptype = BPMEMORY; break; case bp_dll: bptype = BPDLL; addr = ModHashFromName(reinterpret_cast<const char*>(addr)); break; case bp_exception: bptype = BPEXCEPTION; break; default: return false; } SHARED_ACQUIRE(LockBreakpoints); auto bpInfo = BpInfoFromAddr(bptype, addr); if(!bpInfo) return false; if(bp) { BpToBridge(bpInfo, bp); bp->addr = addr; } return true; } static bool _stringformatinline(const char* format, size_t resultSize, char* result) { if(!format || !result) return false; strncpy_s(result, resultSize, stringformatinline(format).c_str(), _TRUNCATE); return true; } static void _getmnemonicbrief(const char* mnem, size_t resultSize, char* result) { if(!result) return; strncpy_s(result, resultSize, MnemonicHelp::getBriefDescription(mnem).c_str(), _TRUNCATE); } static bool _enumhandles(ListOf(HANDLEINFO) handles) { std::vector<HANDLEINFO> handleV; if(!HandlesEnum(handleV)) return false; return BridgeList<HANDLEINFO>::CopyData(handles, handleV); } static bool _gethandlename(duint handle, char* name, size_t nameSize, char* typeName, size_t typeNameSize) { String nameS; String typeNameS; if(!HandlesGetName(HANDLE(handle), nameS, typeNameS)) return false; strncpy_s(name, nameSize, nameS.c_str(), _TRUNCATE); strncpy_s(typeName, typeNameSize, typeNameS.c_str(), _TRUNCATE); return true; } static bool _enumtcpconnections(ListOf(TCPCONNECTIONINFO) connections) { std::vector<TCPCONNECTIONINFO> connectionsV; if(!TcpEnumConnections(fdProcessInfo->dwProcessId, connectionsV)) return false; return BridgeList<TCPCONNECTIONINFO>::CopyData(connections, connectionsV); } static bool _enumwindows(ListOf(WINDOW_INFO) windows) { std::vector<WINDOW_INFO> windowInfoV; if(!HandlesEnumWindows(windowInfoV)) return false; return BridgeList<WINDOW_INFO>::CopyData(windows, windowInfoV); } static bool _enumheaps(ListOf(HEAPINFO) heaps) { std::vector<HEAPINFO> heapInfoV; if(!HandlesEnumHeaps(heapInfoV)) return false; return BridgeList<HEAPINFO>::CopyData(heaps, heapInfoV); } static void _getcallstackex(DBGCALLSTACK* callstack, bool cache) { auto csp = GetContextDataEx(hActiveThread, UE_CSP); if(!cache) stackupdatecallstack(csp); stackgetcallstack(csp, (CALLSTACK*)callstack); } static void _enumconstants(ListOf(CONSTANTINFO) constants) { auto constantsV = ConstantList(); BridgeList<CONSTANTINFO>::CopyData(constants, constantsV); } static void _enumerrorcodes(ListOf(CONSTANTINFO) errorcodes) { auto errorcodesV = ErrorCodeList(); BridgeList<CONSTANTINFO>::CopyData(errorcodes, errorcodesV); } static void _enumexceptions(ListOf(CONSTANTINFO) exceptions) { auto exceptionsV = ExceptionList(); BridgeList<CONSTANTINFO>::CopyData(exceptions, exceptionsV); } static duint _membpsize(duint addr) { SHARED_ACQUIRE(LockBreakpoints); auto info = BpInfoFromAddr(BPMEMORY, addr); return info ? info->memsize : 0; } static bool _modrelocationsfromaddr(duint addr, ListOf(DBGRELOCATIONINFO) relocations) { std::vector<MODRELOCATIONINFO> infos; if(!ModRelocationsFromAddr(addr, infos)) return false; BridgeList<MODRELOCATIONINFO>::CopyData(relocations, infos); return true; } static bool _modrelocationsinrange(duint addr, duint size, ListOf(DBGRELOCATIONINFO) relocations) { std::vector<MODRELOCATIONINFO> infos; if(!ModRelocationsInRange(addr, size, infos)) return false; BridgeList<MODRELOCATIONINFO>::CopyData(relocations, infos); return true; } static int SymAutoComplete(const char* Search, char** Buffer, int MaxSymbols) { //TODO: refactor this in a function because this pattern will become common std::vector<duint> mods; ModEnum([&mods](const MODINFO & info) { mods.push_back(info.base); }); std::unordered_set<std::string> visited; static const bool caseSensitiveAutoComplete = settingboolget("Gui", "CaseSensitiveAutoComplete"); int count = 0; std::string prefix(Search); for(duint base : mods) { if(count == MaxSymbols) break; SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(base); if(!modInfo) continue; auto addName = [Buffer, MaxSymbols, &visited, &count](const std::string & name) { if(visited.count(name)) return true; visited.insert(name); Buffer[count] = (char*)BridgeAlloc(name.size() + 1); memcpy(Buffer[count], name.c_str(), name.size() + 1); return ++count < MaxSymbols; }; NameIndex::findByPrefix(modInfo->exportsByName, prefix, [modInfo, &addName](const NameIndex & index) { return addName(modInfo->exports[index.index].name); }, caseSensitiveAutoComplete); if(count == MaxSymbols) break; if(modInfo->symbols->isOpen()) { modInfo->symbols->findSymbolsByPrefix(prefix, [&addName](const SymbolInfo & symInfo) { return addName(symInfo.decoratedName); }, caseSensitiveAutoComplete); } } std::stable_sort(Buffer, Buffer + count, [](const char* a, const char* b) { return (caseSensitiveAutoComplete ? strcmp : StringUtils::hackicmp)(a, b) < 0; }); return count; } static MODULESYMBOLSTATUS _modsymbolstatus(duint base) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(base); if(!modInfo) return MODSYMUNLOADED; bool isOpen = modInfo->symbols->isOpen(); bool isLoading = modInfo->symbols->isLoading(); if(isOpen && !isLoading) return MODSYMLOADED; else if(isOpen && isLoading) return MODSYMLOADING; else if(!isOpen && symbolDownloadingBase == base) return MODSYMLOADING; else return MODSYMUNLOADED; } static void _refreshmodulelist() { SymUpdateModuleList(); } static unsigned int _getTraceRecordHitCount(duint address) { return TraceRecord.getHitCount(address); } static TRACERECORDBYTETYPE _getTraceRecordByteType(duint address) { return (TRACERECORDBYTETYPE)TraceRecord.getByteType(address); } static bool _setTraceRecordType(duint pageAddress, TRACERECORDTYPE type) { return TraceRecord.setTraceRecordType(pageAddress, (TraceRecordManager::TraceRecordType)type); } static TRACERECORDTYPE _getTraceRecordType(duint pageAddress) { return (TRACERECORDTYPE)TraceRecord.getTraceRecordType(pageAddress); } static bool _enableTraceRecording(bool enabled, const char* fileName) { return TraceRecord.enableTraceRecording(enabled, fileName); } static bool _isTraceRecordingEnabled() { return TraceRecord.isTraceRecordingEnabled(); } void dbgfunctionsinit() { _dbgfunctions.AssembleAtEx = _assembleatex; _dbgfunctions.SectionFromAddr = _sectionfromaddr; _dbgfunctions.ModNameFromAddr = ModNameFromAddr; _dbgfunctions.ModBaseFromAddr = ModBaseFromAddr; _dbgfunctions.ModBaseFromName = ModBaseFromName; _dbgfunctions.ModSizeFromAddr = ModSizeFromAddr; _dbgfunctions.ModGetParty = ModGetParty; _dbgfunctions.ModSetParty = ModSetParty; _dbgfunctions.WatchIsWatchdogTriggered = WatchIsWatchdogTriggered; _dbgfunctions.Assemble = assemble; _dbgfunctions.PatchGet = _patchget; _dbgfunctions.PatchInRange = _patchinrange; _dbgfunctions.MemPatch = _mempatch; _dbgfunctions.PatchRestoreRange = _patchrestorerange; _dbgfunctions.PatchEnum = (PATCHENUM)PatchEnum; _dbgfunctions.PatchRestore = _patchrestore; _dbgfunctions.PatchFile = (PATCHFILE)PatchFile; _dbgfunctions.ModPathFromAddr = ModPathFromAddr; _dbgfunctions.ModPathFromName = ModPathFromName; _dbgfunctions.DisasmFast = disasmfast; _dbgfunctions.MemUpdateMap = _memupdatemap; _dbgfunctions.GetCallStack = _getcallstack; _dbgfunctions.GetSEHChain = _getsehchain; _dbgfunctions.SymbolDownloadAllSymbols = SymDownloadAllSymbols; _dbgfunctions.GetJit = _getjit; _dbgfunctions.GetJitAuto = _getjitauto; _dbgfunctions.GetDefJit = dbggetdefjit; _dbgfunctions.GetProcessList = _getprocesslist; _dbgfunctions.GetPageRights = MemGetPageRights; _dbgfunctions.SetPageRights = MemSetPageRights; _dbgfunctions.PageRightsToString = MemPageRightsToString; _dbgfunctions.IsProcessElevated = BridgeIsProcessElevated; _dbgfunctions.GetCmdline = _getcmdline; _dbgfunctions.SetCmdline = _setcmdline; _dbgfunctions.FileOffsetToVa = valfileoffsettova; _dbgfunctions.VaToFileOffset = valvatofileoffset; _dbgfunctions.GetAddrFromLine = _getaddrfromline; _dbgfunctions.GetSourceFromAddr = _getsourcefromaddr; _dbgfunctions.ValFromString = _valfromstring; _dbgfunctions.PatchGetEx = (PATCHGETEX)PatchGet; _dbgfunctions.GetBridgeBp = _getbridgebp; _dbgfunctions.StringFormatInline = _stringformatinline; _dbgfunctions.GetMnemonicBrief = _getmnemonicbrief; _dbgfunctions.GetTraceRecordHitCount = _getTraceRecordHitCount; _dbgfunctions.GetTraceRecordByteType = _getTraceRecordByteType; _dbgfunctions.SetTraceRecordType = _setTraceRecordType; _dbgfunctions.GetTraceRecordType = _getTraceRecordType; _dbgfunctions.EnumHandles = _enumhandles; _dbgfunctions.GetHandleName = _gethandlename; _dbgfunctions.EnumTcpConnections = _enumtcpconnections; _dbgfunctions.GetDbgEvents = dbggetdbgevents; _dbgfunctions.MemIsCodePage = MemIsCodePage; _dbgfunctions.AnimateCommand = _dbg_animatecommand; _dbgfunctions.DbgSetDebuggeeInitScript = dbgsetdebuggeeinitscript; _dbgfunctions.DbgGetDebuggeeInitScript = dbggetdebuggeeinitscript; _dbgfunctions.EnumWindows = _enumwindows; _dbgfunctions.EnumHeaps = _enumheaps; _dbgfunctions.ThreadGetName = ThreadGetName; _dbgfunctions.IsDepEnabled = dbgisdepenabled; _dbgfunctions.GetCallStackEx = _getcallstackex; _dbgfunctions.GetUserComment = CommentGet; _dbgfunctions.EnumConstants = _enumconstants; _dbgfunctions.EnumErrorCodes = _enumerrorcodes; _dbgfunctions.EnumExceptions = _enumexceptions; _dbgfunctions.MemBpSize = _membpsize; _dbgfunctions.ModRelocationsFromAddr = _modrelocationsfromaddr; _dbgfunctions.ModRelocationAtAddr = (MODRELOCATIONATADDR)ModRelocationAtAddr; _dbgfunctions.ModRelocationsInRange = _modrelocationsinrange; _dbgfunctions.DbGetHash = DbGetHash; _dbgfunctions.SymAutoComplete = SymAutoComplete; _dbgfunctions.RefreshModuleList = _refreshmodulelist; _dbgfunctions.GetAddrFromLineEx = _getaddrfromlineex; _dbgfunctions.ModSymbolStatus = _modsymbolstatus; _dbgfunctions.GetCallStackByThread = _getcallstackbythread; }
C/C++
x64dbg-development/src/dbg/_dbgfunctions.h
#ifndef _DBGFUNCTIONS_H #define _DBGFUNCTIONS_H #ifndef __cplusplus #include <stdbool.h> #endif typedef struct { char mod[MAX_MODULE_SIZE]; duint addr; unsigned char oldbyte; unsigned char newbyte; } DBGPATCHINFO; typedef struct { duint addr; duint from; duint to; char comment[MAX_COMMENT_SIZE]; } DBGCALLSTACKENTRY; typedef struct { int total; DBGCALLSTACKENTRY* entries; } DBGCALLSTACK; typedef struct { duint addr; duint handler; } DBGSEHRECORD; typedef struct { duint total; DBGSEHRECORD* records; } DBGSEHCHAIN; typedef struct { DWORD dwProcessId; char szExeFile[MAX_PATH]; char szExeMainWindowTitle[MAX_PATH]; char szExeArgs[MAX_COMMAND_LINE_SIZE]; } DBGPROCESSINFO; typedef struct { DWORD rva; BYTE type; WORD size; } DBGRELOCATIONINFO; typedef enum { InstructionBody = 0, InstructionHeading = 1, InstructionTailing = 2, InstructionOverlapped = 3, // The byte was executed with differing instruction base addresses DataByte, // This and the following is not implemented yet. DataWord, DataDWord, DataQWord, DataFloat, DataDouble, DataLongDouble, DataXMM, DataYMM, DataMMX, DataMixed, //the byte is accessed in multiple ways InstructionDataMixed //the byte is both executed and written } TRACERECORDBYTETYPE; typedef enum { TraceRecordNone, TraceRecordBitExec, TraceRecordByteWithExecTypeAndCounter, TraceRecordWordWithExecTypeAndCounter } TRACERECORDTYPE; typedef struct { duint Handle; unsigned char TypeNumber; unsigned int GrantedAccess; } HANDLEINFO; // The longest ip address is 1234:6789:1234:6789:1234:6789:123.567.901.345 (46 bytes) #define TCP_ADDR_SIZE 50 typedef struct { char RemoteAddress[TCP_ADDR_SIZE]; unsigned short RemotePort; char LocalAddress[TCP_ADDR_SIZE]; unsigned short LocalPort; char StateText[TCP_ADDR_SIZE]; unsigned int State; } TCPCONNECTIONINFO; typedef struct { duint handle; duint parent; DWORD threadId; DWORD style; DWORD styleEx; duint wndProc; bool enabled; RECT position; char windowTitle[MAX_COMMENT_SIZE]; char windowClass[MAX_COMMENT_SIZE]; } WINDOW_INFO; typedef struct { duint addr; duint size; duint flags; } HEAPINFO; typedef struct { const char* name; duint value; } CONSTANTINFO; typedef enum { MODSYMUNLOADED = 0, MODSYMLOADING, MODSYMLOADED } MODULESYMBOLSTATUS; typedef bool (*ASSEMBLEATEX)(duint addr, const char* instruction, char* error, bool fillnop); typedef bool (*SECTIONFROMADDR)(duint addr, char* section); typedef bool (*MODNAMEFROMADDR)(duint addr, char* modname, bool extension); typedef duint(*MODBASEFROMADDR)(duint addr); typedef duint(*MODBASEFROMNAME)(const char* modname); typedef duint(*MODSIZEFROMADDR)(duint addr); typedef bool (*ASSEMBLE)(duint addr, unsigned char* dest, int* size, const char* instruction, char* error); typedef bool (*PATCHGET)(duint addr); typedef bool (*PATCHINRANGE)(duint start, duint end); typedef bool (*MEMPATCH)(duint va, const unsigned char* src, duint size); typedef void (*PATCHRESTORERANGE)(duint start, duint end); typedef bool (*PATCHENUM)(DBGPATCHINFO* patchlist, size_t* cbsize); typedef bool (*PATCHRESTORE)(duint addr); typedef int (*PATCHFILE)(DBGPATCHINFO* patchlist, int count, const char* szFileName, char* error); typedef int (*MODPATHFROMADDR)(duint addr, char* path, int size); typedef int (*MODPATHFROMNAME)(const char* modname, char* path, int size); typedef bool (*DISASMFAST)(const unsigned char* data, duint addr, BASIC_INSTRUCTION_INFO* basicinfo); typedef void (*MEMUPDATEMAP)(); typedef void (*GETCALLSTACK)(DBGCALLSTACK* callstack); typedef void (*GETSEHCHAIN)(DBGSEHCHAIN* sehchain); typedef void (*SYMBOLDOWNLOADALLSYMBOLS)(const char* szSymbolStore); typedef bool (*GETJIT)(char* jit, bool x64); typedef bool (*GETJITAUTO)(bool* jitauto); typedef bool (*GETDEFJIT)(char* defjit); typedef bool (*GETPROCESSLIST)(DBGPROCESSINFO** entries, int* count); typedef bool (*GETPAGERIGHTS)(duint addr, char* rights); typedef bool (*SETPAGERIGHTS)(duint addr, const char* rights); typedef bool (*PAGERIGHTSTOSTRING)(DWORD protect, char* rights); typedef bool (*ISPROCESSELEVATED)(); typedef bool (*GETCMDLINE)(char* cmdline, size_t* cbsize); typedef bool (*SETCMDLINE)(const char* cmdline); typedef duint(*FILEOFFSETTOVA)(const char* modname, duint offset); typedef duint(*VATOFILEOFFSET)(duint va); typedef duint(*GETADDRFROMLINE)(const char* szSourceFile, int line, duint* displacement); typedef bool (*GETSOURCEFROMADDR)(duint addr, char* szSourceFile, int* line); typedef bool (*VALFROMSTRING)(const char* string, duint* value); typedef bool (*PATCHGETEX)(duint addr, DBGPATCHINFO* info); typedef bool (*GETBRIDGEBP)(BPXTYPE type, duint addr, BRIDGEBP* bp); typedef bool (*STRINGFORMATINLINE)(const char* format, size_t resultSize, char* result); typedef void (*GETMNEMONICBRIEF)(const char* mnem, size_t resultSize, char* result); typedef unsigned int (*GETTRACERECORDHITCOUNT)(duint address); typedef TRACERECORDBYTETYPE(*GETTRACERECORDBYTETYPE)(duint address); typedef bool (*SETTRACERECORDTYPE)(duint pageAddress, TRACERECORDTYPE type); typedef TRACERECORDTYPE(*GETTRACERECORDTYPE)(duint pageAddress); typedef bool (*ENUMHANDLES)(ListOf(HANDLEINFO) handles); typedef bool (*GETHANDLENAME)(duint handle, char* name, size_t nameSize, char* typeName, size_t typeNameSize); typedef bool (*ENUMTCPCONNECTIONS)(ListOf(TCPCONNECTIONINFO) connections); typedef duint(*GETDBGEVENTS)(); typedef MODULEPARTY(*MODGETPARTY)(duint base); typedef void (*MODSETPARTY)(duint base, MODULEPARTY party); typedef bool(*WATCHISWATCHDOGTRIGGERED)(unsigned int id); typedef bool(*MEMISCODEPAGE)(duint addr, bool refresh); typedef bool(*ANIMATECOMMAND)(const char* command); typedef void(*DBGSETDEBUGGEEINITSCRIPT)(const char* fileName); typedef const char* (*DBGGETDEBUGGEEINITSCRIPT)(); typedef bool(*HANDLESENUMWINDOWS)(ListOf(WINDOW_INFO) windows); typedef bool(*HANDLESENUMHEAPS)(ListOf(HEAPINFO) heaps); typedef bool(*THREADGETNAME)(DWORD tid, char* name); typedef bool(*ISDEPENABLED)(); typedef void(*GETCALLSTACKEX)(DBGCALLSTACK* callstack, bool cache); typedef bool(*GETUSERCOMMENT)(duint addr, char* comment); typedef void(*ENUMCONSTANTS)(ListOf(CONSTANTINFO) constants); typedef duint(*MEMBPSIZE)(duint addr); typedef bool(*MODRELOCATIONSFROMADDR)(duint addr, ListOf(DBGRELOCATIONINFO) relocations); typedef bool(*MODRELOCATIONATADDR)(duint addr, DBGRELOCATIONINFO* relocation); typedef bool(*MODRELOCATIONSINRANGE)(duint addr, duint size, ListOf(DBGRELOCATIONINFO) relocations); typedef duint(*DBGETHASH)(); typedef int(*SYMAUTOCOMPLETE)(const char* Search, char** Buffer, int MaxSymbols); typedef void(*REFRESHMODULELIST)(); typedef duint(*GETADDRFROMLINEEX)(duint mod, const char* szSourceFile, int line); typedef MODULESYMBOLSTATUS(*MODSYMBOLSTATUS)(duint mod); typedef void(*GETCALLSTACKBYTHREAD)(HANDLE thread, DBGCALLSTACK* callstack); //The list of all the DbgFunctions() return value. //WARNING: This list is append only. Do not insert things in the middle or plugins would break. typedef struct DBGFUNCTIONS_ { ASSEMBLEATEX AssembleAtEx; SECTIONFROMADDR SectionFromAddr; MODNAMEFROMADDR ModNameFromAddr; MODBASEFROMADDR ModBaseFromAddr; MODBASEFROMNAME ModBaseFromName; MODSIZEFROMADDR ModSizeFromAddr; ASSEMBLE Assemble; PATCHGET PatchGet; PATCHINRANGE PatchInRange; MEMPATCH MemPatch; PATCHRESTORERANGE PatchRestoreRange; PATCHENUM PatchEnum; PATCHRESTORE PatchRestore; PATCHFILE PatchFile; MODPATHFROMADDR ModPathFromAddr; MODPATHFROMNAME ModPathFromName; DISASMFAST DisasmFast; MEMUPDATEMAP MemUpdateMap; GETCALLSTACK GetCallStack; GETSEHCHAIN GetSEHChain; SYMBOLDOWNLOADALLSYMBOLS SymbolDownloadAllSymbols; GETJITAUTO GetJitAuto; GETJIT GetJit; GETDEFJIT GetDefJit; GETPROCESSLIST GetProcessList; GETPAGERIGHTS GetPageRights; SETPAGERIGHTS SetPageRights; PAGERIGHTSTOSTRING PageRightsToString; ISPROCESSELEVATED IsProcessElevated; GETCMDLINE GetCmdline; SETCMDLINE SetCmdline; FILEOFFSETTOVA FileOffsetToVa; VATOFILEOFFSET VaToFileOffset; GETADDRFROMLINE GetAddrFromLine; GETSOURCEFROMADDR GetSourceFromAddr; VALFROMSTRING ValFromString; PATCHGETEX PatchGetEx; GETBRIDGEBP GetBridgeBp; STRINGFORMATINLINE StringFormatInline; GETMNEMONICBRIEF GetMnemonicBrief; GETTRACERECORDHITCOUNT GetTraceRecordHitCount; GETTRACERECORDBYTETYPE GetTraceRecordByteType; SETTRACERECORDTYPE SetTraceRecordType; GETTRACERECORDTYPE GetTraceRecordType; ENUMHANDLES EnumHandles; GETHANDLENAME GetHandleName; ENUMTCPCONNECTIONS EnumTcpConnections; GETDBGEVENTS GetDbgEvents; MODGETPARTY ModGetParty; MODSETPARTY ModSetParty; WATCHISWATCHDOGTRIGGERED WatchIsWatchdogTriggered; MEMISCODEPAGE MemIsCodePage; ANIMATECOMMAND AnimateCommand; DBGSETDEBUGGEEINITSCRIPT DbgSetDebuggeeInitScript; DBGGETDEBUGGEEINITSCRIPT DbgGetDebuggeeInitScript; HANDLESENUMWINDOWS EnumWindows; HANDLESENUMHEAPS EnumHeaps; THREADGETNAME ThreadGetName; ISDEPENABLED IsDepEnabled; GETCALLSTACKEX GetCallStackEx; GETUSERCOMMENT GetUserComment; ENUMCONSTANTS EnumConstants; ENUMCONSTANTS EnumErrorCodes; ENUMCONSTANTS EnumExceptions; MEMBPSIZE MemBpSize; MODRELOCATIONSFROMADDR ModRelocationsFromAddr; MODRELOCATIONATADDR ModRelocationAtAddr; MODRELOCATIONSINRANGE ModRelocationsInRange; DBGETHASH DbGetHash; SYMAUTOCOMPLETE SymAutoComplete; REFRESHMODULELIST RefreshModuleList; GETADDRFROMLINEEX GetAddrFromLineEx; MODSYMBOLSTATUS ModSymbolStatus; GETCALLSTACKBYTHREAD GetCallStackByThread; } DBGFUNCTIONS; #ifdef BUILD_DBG const DBGFUNCTIONS* dbgfunctionsget(); void dbgfunctionsinit(); #endif //BUILD_DBG #endif //_DBGFUNCTIONS_H
C++
x64dbg-development/src/dbg/_exports.cpp
/** @file _exports.cpp @brief Implements the exports class. */ #include "_exports.h" #include "memory.h" #include "debugger.h" #include "value.h" #include "threading.h" #include "breakpoint.h" #include "disasm_helper.h" #include "simplescript.h" #include "symbolinfo.h" #include "assemble.h" #include "stackinfo.h" #include "thread.h" #include "disasm_fast.h" #include "plugin_loader.h" #include "_dbgfunctions.h" #include "module.h" #include "comment.h" #include "label.h" #include "bookmark.h" #include "function.h" #include "loop.h" #include "exception.h" #include "x64dbg.h" #include "xrefs.h" #include "encodemap.h" #include "argument.h" #include "watch.h" #include "animate.h" #include "TraceRecord.h" #include "recursiveanalysis.h" #include "dbghelp_safe.h" #include "symbolinfo.h" static bool bOnlyCipAutoComments = false; static bool bNoSourceLineAutoComments = false; static TITAN_ENGINE_CONTEXT_t lastContext; extern "C" DLL_EXPORT duint _dbg_memfindbaseaddr(duint addr, duint* size) { return MemFindBaseAddr(addr, size); } extern "C" DLL_EXPORT bool _dbg_memread(duint addr, unsigned char* dest, duint size, duint* read) { return MemRead(addr, dest, size, read); } extern "C" DLL_EXPORT bool _dbg_memwrite(duint addr, const unsigned char* src, duint size, duint* written) { return MemWrite(addr, src, size, written); } extern "C" DLL_EXPORT bool _dbg_memmap(MEMMAP* memmap) { SHARED_ACQUIRE(LockMemoryPages); int pagecount = (int)memoryPages.size(); memmap->count = pagecount; memmap->page = nullptr; if(!pagecount) return true; // Allocate memory that is already zeroed memmap->page = (MEMPAGE*)BridgeAlloc(sizeof(MEMPAGE) * pagecount); // Copy all elements over int i = 0; for(auto & itr : memoryPages) memcpy(&memmap->page[i++], &itr.second, sizeof(MEMPAGE)); // Done return true; } extern "C" DLL_EXPORT bool _dbg_memisvalidreadptr(duint addr) { return MemIsValidReadPtr(addr, true); } extern "C" DLL_EXPORT bool _dbg_valfromstring(const char* string, duint* value) { return valfromstring(string, value); } extern "C" DLL_EXPORT bool _dbg_isdebugging() { return hDebugLoopThread && IsFileBeingDebugged(); } extern "C" DLL_EXPORT bool _dbg_isjumpgoingtoexecute(duint addr) { if(!hActiveThread) return false; unsigned char data[16]; if(MemRead(addr, data, sizeof(data), nullptr, true)) { Zydis cp; if(cp.Disassemble(addr, data)) { CONTEXT ctx; memset(&ctx, 0, sizeof(ctx)); ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; GetThreadContext(hActiveThread, &ctx); #ifdef _WIN64 auto cflags = ctx.EFlags; auto ccx = ctx.Rcx; #else auto cflags = ctx.EFlags; auto ccx = ctx.Ecx; #endif //_WIN64 return cp.IsBranchGoingToExecute(cflags, ccx); } } return false; } static bool shouldFilterSymbol(const char* name) { if(!name) return true; if(strstr(name, "`string'")) return true; if(strstr(name, "__imp_") == name || strstr(name, "_imp_") == name) return true; PLUG_CB_FILTERSYMBOL filterInfo = { name, false }; plugincbcall(CB_FILTERSYMBOL, &filterInfo); return filterInfo.retval; } // https://github.com/llvm-mirror/llvm/blob/2ae7de27f7d9276e7bada445ea7576bbc4c83ae6/lib/DebugInfo/Symbolize/Symbolize.cpp#L427 // https://github.com/x64dbg/x64dbg/pull/1478 // Undo these various manglings for Win32 extern "C" functions: // cdecl - _foo // stdcall - _foo@12 // fastcall - @foo@12 // vectorcall - foo@@12 // These are all different linkage names for 'foo'. static char* demanglePE32ExternCFunc(char* SymbolName) { // Only do this for Win32 #ifdef _WIN64 return SymbolName; #endif //_WIN64 // Don't try to demangle C++ names char Front = SymbolName[0]; if(Front == '?') return SymbolName; // Remove any '_' or '@' prefix. if(Front == '_' || Front == '@') SymbolName++; // Remove any '@[0-9]+' suffix. auto AtPos = strrchr(SymbolName, '@'); if(AtPos) { auto p = AtPos + 1; while(*p && isdigit(*p)) p++; // All characters after '@' were digits if(!*p) *AtPos = '\0'; } // Remove any ending '@' for vectorcall. auto len = strlen(SymbolName); if(len && SymbolName[len - 1] == '@') SymbolName[len - 1] = '\0'; return SymbolName; } static bool getLabel(duint addr, char* label, bool noFuncOffset) { bool retval = false; label[0] = 0; if(LabelGet(addr, label)) return true; else //no user labels { DWORD64 displacement = 0; { SYMBOLINFOCPP symInfo; bool res; if(noFuncOffset) res = SymbolFromAddressExact(addr, &symInfo); else res = SymbolFromAddressExactOrLower(addr, &symInfo); if(res) { displacement = (int32_t)(addr - symInfo.addr); //auto name = demanglePE32ExternCFunc(symInfo.decoratedName.c_str()); if(bUndecorateSymbolNames && *symInfo.undecoratedSymbol != '\0') strncpy_s(label, MAX_LABEL_SIZE, symInfo.undecoratedSymbol, _TRUNCATE); else strncpy_s(label, MAX_LABEL_SIZE, symInfo.decoratedSymbol, _TRUNCATE); retval = !shouldFilterSymbol(label); if(retval && displacement != 0) { char temp[32]; sprintf_s(temp, "+%llX", displacement); strncat_s(label, MAX_LABEL_SIZE, temp, _TRUNCATE); } } } if(!retval) //search for CALL <jmp.&user32.MessageBoxA> { BASIC_INSTRUCTION_INFO basicinfo; memset(&basicinfo, 0, sizeof(BASIC_INSTRUCTION_INFO)); if(disasmfast(addr, &basicinfo, true) && basicinfo.branch && !basicinfo.call && basicinfo.memory.value) //thing is a JMP { duint val = 0; if(MemRead(basicinfo.memory.value, &val, sizeof(val), nullptr, true)) { SYMBOLINFOCPP symInfo; bool res; if(noFuncOffset) res = SymbolFromAddressExact(val, &symInfo); else res = SymbolFromAddressExactOrLower(val, &symInfo); if(res) { //pSymbol->Name[pSymbol->MaxNameLen - 1] = '\0'; //auto name = demanglePE32ExternCFunc(pSymbol->Name); if(bUndecorateSymbolNames && *symInfo.undecoratedSymbol != '\0') _snprintf_s(label, MAX_LABEL_SIZE, _TRUNCATE, "JMP.&%s", symInfo.undecoratedSymbol); else _snprintf_s(label, MAX_LABEL_SIZE, _TRUNCATE, "JMP.&%s", symInfo.decoratedSymbol); retval = !shouldFilterSymbol(label); if(retval && displacement) { char temp[32]; sprintf_s(temp, "+%llX", displacement); strncat_s(label, MAX_LABEL_SIZE, temp, _TRUNCATE); } } } } } if(!retval) //search for module entry { if(addr != 0 && ModEntryFromAddr(addr) == addr) { strcpy_s(label, MAX_LABEL_SIZE, "EntryPoint"); return true; } duint start; if(FunctionGet(addr, &start, nullptr)) { duint rva = addr - start; if(rva == 0) { #ifdef _WIN64 sprintf_s(label, MAX_LABEL_SIZE, "sub_%llX", start); #else //x86 sprintf_s(label, MAX_LABEL_SIZE, "sub_%X", start); #endif //_WIN64 return true; } if(noFuncOffset) return false; getLabel(start, label, false); char temp[32]; #ifdef _WIN64 sprintf_s(temp, "+%llX", rva); #else //x86 sprintf_s(temp, "+%X", rva); #endif //_WIN64 strncat_s(label, MAX_LABEL_SIZE, temp, _TRUNCATE); return true; } } } return retval; } static bool getAutoComment(duint addr, String & comment) { bool retval = false; duint disp; char fileName[MAX_STRING_SIZE] = {}; int lineNumber = 0; if(!bNoSourceLineAutoComments && SymGetSourceLine(addr, fileName, &lineNumber, &disp) && !disp) { char* actualName = fileName; char* l = strrchr(fileName, '\\'); if(l) actualName = l + 1; comment = StringUtils::sprintf("%s:%u", actualName, lineNumber); retval = true; } else { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(addr); if(modInfo != nullptr) { auto exportInfo = modInfo->findExport(addr - modInfo->base); if(exportInfo != nullptr && exportInfo->forwarded) { comment = StringUtils::sprintf("-> %s", exportInfo->forwardName.c_str()); retval = true; dputs(comment.c_str()); } } } DISASM_INSTR instr; String temp_string; BRIDGE_ADDRINFO newinfo; char string_text[MAX_STRING_SIZE] = ""; Zydis cp; auto getregs = !bOnlyCipAutoComments || addr == lastContext.cip; disasmget(cp, addr, &instr, getregs); // Some nop variants have 'operands' that should be ignored if(cp.Success() && !cp.IsNop()) { //Ignore register values when not on CIP and OnlyCipAutoComments is enabled: https://github.com/x64dbg/x64dbg/issues/1383 if(!getregs) { for(int i = 0; i < instr.argcount; i++) instr.arg[i].value = instr.arg[i].constant; } if(addr == lastContext.cip && (cp.GetId() == ZYDIS_MNEMONIC_SYSCALL || (cp.GetId() == ZYDIS_MNEMONIC_INT && cp[0].imm.value.u == 0x2e))) { auto syscallName = SyscallToName((unsigned int)lastContext.cax); if(!syscallName.empty()) { if(!comment.empty()) { comment.push_back(','); comment.push_back(' '); } comment.append(syscallName); retval = true; } } for(int i = 0; i < instr.argcount; i++) { memset(&newinfo, 0, sizeof(BRIDGE_ADDRINFO)); newinfo.flags = flaglabel; STRING_TYPE strtype = str_none; if(instr.arg[i].constant == instr.arg[i].value) //avoid: call <module.label> ; addr:label { auto constant = instr.arg[i].constant; if(instr.arg[i].type == arg_normal && instr.arg[i].value == addr + instr.instr_size && cp.IsCall()) temp_string.assign("call $0"); else if(instr.arg[i].type == arg_normal && instr.arg[i].value == addr + instr.instr_size && cp.IsJump()) temp_string.assign("jmp $0"); else if(instr.type == instr_branch) continue; else if(instr.arg[i].type == arg_normal && constant < 256 && (isprint(int(constant)) || isspace(int(constant))) && (strstr(instr.instruction, "cmp") || strstr(instr.instruction, "mov"))) { temp_string.assign(instr.arg[i].mnemonic); temp_string.push_back(':'); temp_string.push_back('\''); temp_string.append(StringUtils::Escape((unsigned char)constant)); temp_string.push_back('\''); } else if(DbgGetStringAt(instr.arg[i].constant, string_text)) { temp_string.assign(instr.arg[i].mnemonic); temp_string.push_back(':'); temp_string.append(string_text); } } else if(instr.arg[i].memvalue && (DbgGetStringAt(instr.arg[i].memvalue, string_text) || _dbg_addrinfoget(instr.arg[i].memvalue, instr.arg[i].segment, &newinfo))) { if(*string_text) { temp_string.assign("["); temp_string.append(instr.arg[i].mnemonic); temp_string.push_back(']'); temp_string.push_back(':'); temp_string.append(string_text); } else if(*newinfo.label) { temp_string.assign("["); temp_string.append(instr.arg[i].mnemonic); temp_string.push_back(']'); temp_string.push_back(':'); temp_string.append(newinfo.label); } } else if(instr.arg[i].value && (DbgGetStringAt(instr.arg[i].value, string_text) || _dbg_addrinfoget(instr.arg[i].value, instr.arg[i].segment, &newinfo))) { if(instr.type != instr_normal) //stack/jumps (eg add esp, 4 or jmp 401110) cannot directly point to strings { if(*newinfo.label) { temp_string = instr.arg[i].mnemonic; temp_string.push_back(':'); temp_string.append(newinfo.label); } } else if(*string_text) { temp_string = instr.arg[i].mnemonic; temp_string.push_back(':'); temp_string.append(string_text); } else if(*newinfo.label) { temp_string = instr.arg[i].mnemonic; temp_string.push_back(':'); temp_string.append(newinfo.label); } } else continue; if(!strstr(comment.c_str(), temp_string.c_str())) //avoid duplicate comments { if(!comment.empty()) { comment.push_back(','); comment.push_back(' '); } comment.append(temp_string); retval = true; } } } BREAKPOINT bp; // Add autocomment for breakpoints with BreakpointsView format because there's usually something useful if(BpGet(addr, BPNORMAL, nullptr, &bp) || BpGet(addr, BPHARDWARE, nullptr, &bp)) { temp_string.clear(); auto next = [&temp_string]() { if(!temp_string.empty()) temp_string += ", "; }; if(*bp.breakCondition) { next(); temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "breakif")); temp_string += "("; temp_string += bp.breakCondition; temp_string += ")"; } if(bp.fastResume) { next(); temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "fastresume()")); } else //fast resume skips all other steps { if(*bp.logText) { next(); if(*bp.logCondition) { temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "logif")); temp_string += "("; temp_string += bp.logCondition; temp_string += ", "; } else { temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "log")); temp_string += "("; } temp_string += bp.logText; temp_string += ")"; } if(*bp.commandText) { next(); if(*bp.commandCondition) { temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "cmdif")); temp_string += "("; temp_string += bp.commandCondition; temp_string += ", "; } else { temp_string += GuiTranslateText(QT_TRANSLATE_NOOP("DBG", "cmd")); temp_string += "("; } temp_string += bp.commandText; temp_string += ")"; } } if(!temp_string.empty()) { if(!comment.empty()) { comment.push_back(','); comment.push_back(' '); } comment.append(temp_string); retval = true; } } StringUtils::ReplaceAll(comment, "{", "{{"); StringUtils::ReplaceAll(comment, "}", "}}"); return retval; } extern "C" DLL_EXPORT bool _dbg_addrinfoget(duint addr, SEGMENTREG segment, BRIDGE_ADDRINFO* addrinfo) { if(!DbgIsDebugging()) return false; bool retval = false; if(addrinfo->flags & flagmodule) //get module { if(ModNameFromAddr(addr, addrinfo->module, false)) //get module name retval = true; } if(addrinfo->flags & flaglabel) { retval = getLabel(addr, addrinfo->label, (addrinfo->flags & flagNoFuncOffset) != 0); } if(addrinfo->flags & flagbookmark) { addrinfo->isbookmark = BookmarkGet(addr); retval = true; } if(addrinfo->flags & flagfunction) { if(FunctionGet(addr, &addrinfo->function.start, &addrinfo->function.end, &addrinfo->function.instrcount)) retval = true; } if(addrinfo->flags & flagloop) { if(LoopGet(addrinfo->loop.depth, addr, &addrinfo->loop.start, &addrinfo->loop.end, &addrinfo->loop.instrcount)) retval = true; } if(addrinfo->flags & flagargs) { if(ArgumentGet(addr, &addrinfo->args.start, &addrinfo->args.end, &addrinfo->function.instrcount)) retval = true; } if(addrinfo->flags & flagcomment) { *addrinfo->comment = 0; if(CommentGet(addr, addrinfo->comment)) { retval = true; } else { String comment; retval = getAutoComment(addr, comment); strcpy_s(addrinfo->comment, "\1"); strncat_s(addrinfo->comment, comment.c_str(), _TRUNCATE); } } PLUG_CB_ADDRINFO info; info.addr = addr; info.addrinfo = addrinfo; info.retval = retval; plugincbcall(CB_ADDRINFO, &info); return info.retval; } extern "C" DLL_EXPORT bool _dbg_addrinfoset(duint addr, BRIDGE_ADDRINFO* addrinfo) { bool retval = false; if(addrinfo->flags & flaglabel) //set label { if(LabelSet(addr, addrinfo->label, true)) retval = true; } if(addrinfo->flags & flagcomment) //set comment { if(CommentSet(addr, addrinfo->comment, true)) retval = true; } if(addrinfo->flags & flagbookmark) //set bookmark { if(addrinfo->isbookmark) retval = BookmarkSet(addr, true); else retval = BookmarkDelete(addr); } return retval; } extern "C" DLL_EXPORT bool _dbg_encodetypeset(duint addr, duint size, ENCODETYPE type) { return EncodeMapSetType(addr, size, type); } extern "C" DLL_EXPORT PROCESS_INFORMATION* _dbg_getProcessInformation() { return fdProcessInfo; } extern "C" DLL_EXPORT int _dbg_bpgettypeat(duint addr) { static duint cacheAddr; static int cacheBpCount; static int cacheResult; int bpcount = BpGetList(nullptr); if(cacheAddr != addr || cacheBpCount != bpcount) { BREAKPOINT bp; cacheAddr = addr; cacheResult = 0; cacheBpCount = bpcount; if(BpGet(addr, BPNORMAL, 0, &bp)) if(bp.enabled) cacheResult |= bp_normal; if(BpGet(addr, BPHARDWARE, 0, &bp)) if(bp.enabled) cacheResult |= bp_hardware; if(BpGet(addr, BPMEMORY, 0, &bp)) if(bp.enabled) cacheResult |= bp_memory; } return cacheResult; } static void GetMxCsrFields(MXCSRFIELDS* MxCsrFields, DWORD MxCsr) { MxCsrFields->DAZ = valmxcsrflagfromstring(MxCsr, "DAZ"); MxCsrFields->DE = valmxcsrflagfromstring(MxCsr, "DE"); MxCsrFields->FZ = valmxcsrflagfromstring(MxCsr, "FZ"); MxCsrFields->IE = valmxcsrflagfromstring(MxCsr, "IE"); MxCsrFields->IM = valmxcsrflagfromstring(MxCsr, "IM"); MxCsrFields->DM = valmxcsrflagfromstring(MxCsr, "DM"); MxCsrFields->OE = valmxcsrflagfromstring(MxCsr, "OE"); MxCsrFields->OM = valmxcsrflagfromstring(MxCsr, "OM"); MxCsrFields->PE = valmxcsrflagfromstring(MxCsr, "PE"); MxCsrFields->PM = valmxcsrflagfromstring(MxCsr, "PM"); MxCsrFields->UE = valmxcsrflagfromstring(MxCsr, "UE"); MxCsrFields->UM = valmxcsrflagfromstring(MxCsr, "UM"); MxCsrFields->ZE = valmxcsrflagfromstring(MxCsr, "ZE"); MxCsrFields->ZM = valmxcsrflagfromstring(MxCsr, "ZM"); MxCsrFields->RC = valmxcsrfieldfromstring(MxCsr, "RC"); } static void Getx87ControlWordFields(X87CONTROLWORDFIELDS* x87ControlWordFields, WORD ControlWord) { x87ControlWordFields->DM = valx87controlwordflagfromstring(ControlWord, "DM"); x87ControlWordFields->IC = valx87controlwordflagfromstring(ControlWord, "IC"); x87ControlWordFields->IEM = valx87controlwordflagfromstring(ControlWord, "IEM"); x87ControlWordFields->IM = valx87controlwordflagfromstring(ControlWord, "IM"); x87ControlWordFields->OM = valx87controlwordflagfromstring(ControlWord, "OM"); x87ControlWordFields->PM = valx87controlwordflagfromstring(ControlWord, "PM"); x87ControlWordFields->UM = valx87controlwordflagfromstring(ControlWord, "UM"); x87ControlWordFields->ZM = valx87controlwordflagfromstring(ControlWord, "ZM"); x87ControlWordFields->RC = valx87controlwordfieldfromstring(ControlWord, "RC"); x87ControlWordFields->PC = valx87controlwordfieldfromstring(ControlWord, "PC"); } static void Getx87StatusWordFields(X87STATUSWORDFIELDS* x87StatusWordFields, WORD StatusWord) { x87StatusWordFields->B = valx87statuswordflagfromstring(StatusWord, "B"); x87StatusWordFields->C0 = valx87statuswordflagfromstring(StatusWord, "C0"); x87StatusWordFields->C1 = valx87statuswordflagfromstring(StatusWord, "C1"); x87StatusWordFields->C2 = valx87statuswordflagfromstring(StatusWord, "C2"); x87StatusWordFields->C3 = valx87statuswordflagfromstring(StatusWord, "C3"); x87StatusWordFields->D = valx87statuswordflagfromstring(StatusWord, "D"); x87StatusWordFields->I = valx87statuswordflagfromstring(StatusWord, "I"); x87StatusWordFields->ES = valx87statuswordflagfromstring(StatusWord, "ES"); x87StatusWordFields->O = valx87statuswordflagfromstring(StatusWord, "O"); x87StatusWordFields->P = valx87statuswordflagfromstring(StatusWord, "P"); x87StatusWordFields->SF = valx87statuswordflagfromstring(StatusWord, "SF"); x87StatusWordFields->U = valx87statuswordflagfromstring(StatusWord, "U"); x87StatusWordFields->Z = valx87statuswordflagfromstring(StatusWord, "Z"); x87StatusWordFields->TOP = valx87statuswordfieldfromstring(StatusWord, "TOP"); } static void TranslateTitanFpu(const x87FPU_t* titanfpu, X87FPU* fpu) { fpu->ControlWord = titanfpu->ControlWord; fpu->StatusWord = titanfpu->StatusWord; fpu->TagWord = titanfpu->TagWord; fpu->ErrorOffset = titanfpu->ErrorOffset; fpu->ErrorSelector = titanfpu->ErrorSelector; fpu->DataOffset = titanfpu->DataOffset; fpu->DataSelector = titanfpu->DataSelector; fpu->Cr0NpxState = titanfpu->Cr0NpxState; } static void TranslateTitanContextToRegContext(const TITAN_ENGINE_CONTEXT_t* titcontext, REGISTERCONTEXT* regcontext) { regcontext->cax = titcontext->cax; regcontext->ccx = titcontext->ccx; regcontext->cdx = titcontext->cdx; regcontext->cbx = titcontext->cbx; regcontext->csp = titcontext->csp; regcontext->cbp = titcontext->cbp; regcontext->csi = titcontext->csi; regcontext->cdi = titcontext->cdi; #ifdef _WIN64 regcontext->r8 = titcontext->r8; regcontext->r9 = titcontext->r9; regcontext->r10 = titcontext->r10; regcontext->r11 = titcontext->r11; regcontext->r12 = titcontext->r12; regcontext->r13 = titcontext->r13; regcontext->r14 = titcontext->r14; regcontext->r15 = titcontext->r15; #endif //_WIN64 regcontext->cip = titcontext->cip; regcontext->eflags = titcontext->eflags; regcontext->gs = titcontext->gs; regcontext->fs = titcontext->fs; regcontext->es = titcontext->es; regcontext->ds = titcontext->ds; regcontext->cs = titcontext->cs; regcontext->ss = titcontext->ss; regcontext->dr0 = titcontext->dr0; regcontext->dr1 = titcontext->dr1; regcontext->dr2 = titcontext->dr2; regcontext->dr3 = titcontext->dr3; regcontext->dr6 = titcontext->dr6; regcontext->dr7 = titcontext->dr7; memcpy(regcontext->RegisterArea, titcontext->RegisterArea, sizeof(regcontext->RegisterArea)); TranslateTitanFpu(&titcontext->x87fpu, &regcontext->x87fpu); regcontext->MxCsr = titcontext->MxCsr; memcpy(regcontext->XmmRegisters, titcontext->XmmRegisters, sizeof(regcontext->XmmRegisters)); memcpy(regcontext->YmmRegisters, titcontext->YmmRegisters, sizeof(regcontext->YmmRegisters)); } static void TranslateTitanFpuRegister(const x87FPURegister_t* titanReg, X87FPUREGISTER* reg) { memcpy(reg->data, titanReg->data, sizeof(reg->data)); reg->st_value = titanReg->st_value; reg->tag = titanReg->tag; } static void TranslateTitanFpuRegisters(const x87FPURegister_t titanFpu[8], X87FPUREGISTER fpu[8]) { for(int i = 0; i < 8; i++) TranslateTitanFpuRegister(&titanFpu[i], &fpu[i]); } extern "C" DLL_EXPORT bool _dbg_getregdump(REGDUMP* regdump) { if(!DbgIsDebugging()) { memset(regdump, 0, sizeof(REGDUMP)); return true; } TITAN_ENGINE_CONTEXT_t titcontext; if(!GetFullContextDataEx(hActiveThread, &titcontext)) return false; // NOTE: this is not thread-safe, but that's fine because lastContext is only used for GUI-related operations memcpy(&lastContext, &titcontext, sizeof(titcontext)); TranslateTitanContextToRegContext(&titcontext, &regdump->regcontext); duint cflags = regdump->regcontext.eflags; regdump->flags.c = (cflags & (1 << 0)) != 0; regdump->flags.p = (cflags & (1 << 2)) != 0; regdump->flags.a = (cflags & (1 << 4)) != 0; regdump->flags.z = (cflags & (1 << 6)) != 0; regdump->flags.s = (cflags & (1 << 7)) != 0; regdump->flags.t = (cflags & (1 << 8)) != 0; regdump->flags.i = (cflags & (1 << 9)) != 0; regdump->flags.d = (cflags & (1 << 10)) != 0; regdump->flags.o = (cflags & (1 << 11)) != 0; x87FPURegister_t x87FPURegisters[8]; Getx87FPURegisters(x87FPURegisters, &titcontext); TranslateTitanFpuRegisters(x87FPURegisters, regdump->x87FPURegisters); GetMMXRegisters(regdump->mmx, &titcontext); GetMxCsrFields(& (regdump->MxCsrFields), regdump->regcontext.MxCsr); Getx87ControlWordFields(& (regdump->x87ControlWordFields), regdump->regcontext.x87fpu.ControlWord); Getx87StatusWordFields(& (regdump->x87StatusWordFields), regdump->regcontext.x87fpu.StatusWord); LASTERROR lastError; memset(&lastError.name, 0, sizeof(lastError.name)); lastError.code = ThreadGetLastError(ThreadGetId(hActiveThread)); strncpy_s(lastError.name, ErrorCodeToName(lastError.code).c_str(), _TRUNCATE); regdump->lastError = lastError; LASTSTATUS lastStatus; memset(&lastStatus.name, 0, sizeof(lastStatus.name)); lastStatus.code = ThreadGetLastStatus(ThreadGetId(hActiveThread)); strncpy_s(lastStatus.name, NtStatusCodeToName(lastStatus.code).c_str(), _TRUNCATE); regdump->lastStatus = lastStatus; return true; } extern "C" DLL_EXPORT bool _dbg_valtostring(const char* string, duint value) { return valtostring(string, value, true); } extern "C" DLL_EXPORT int _dbg_getbplist(BPXTYPE type, BPMAP* bpmap) { if(!bpmap) return 0; bpmap->count = 0; bpmap->bp = nullptr; std::vector<BREAKPOINT> list; int bpcount = BpGetList(&list); if(bpcount == 0) return 0; int retcount = 0; std::vector<BRIDGEBP> bridgeList; BRIDGEBP curBp; BP_TYPE currentBpType; switch(type) { case bp_none: currentBpType = BP_TYPE(-1); break; case bp_normal: currentBpType = BPNORMAL; break; case bp_hardware: currentBpType = BPHARDWARE; break; case bp_memory: currentBpType = BPMEMORY; break; case bp_dll: currentBpType = BPDLL; break; case bp_exception: currentBpType = BPEXCEPTION; break; default: return 0; } unsigned short slot = 0; for(int i = 0; i < bpcount; i++) { if(currentBpType != -1 && list[i].type != currentBpType) continue; BpToBridge(&list[i], &curBp); bridgeList.push_back(curBp); retcount++; } if(!retcount) return 0; bpmap->count = retcount; bpmap->bp = (BRIDGEBP*)BridgeAlloc(sizeof(BRIDGEBP) * retcount); for(int i = 0; i < retcount; i++) memcpy(&bpmap->bp[i], &bridgeList.at(i), sizeof(BRIDGEBP)); return retcount; } extern "C" DLL_EXPORT duint _dbg_getbranchdestination(duint addr) { unsigned char data[MAX_DISASM_BUFFER]; if(!MemIsValidReadPtr(addr, true) || !MemRead(addr, data, sizeof(data))) return 0; Zydis cp; if(!cp.Disassemble(addr, data)) return 0; if(cp.IsBranchType(Zydis::BTJmp | Zydis::BTCall | Zydis::BTLoop | Zydis::BTXbegin)) { auto opValue = cp.ResolveOpValue(0, [](ZydisRegister reg) -> size_t { switch(reg) { #ifndef _WIN64 //x32 case ZYDIS_REGISTER_EAX: return lastContext.cax; case ZYDIS_REGISTER_EBX: return lastContext.cbx; case ZYDIS_REGISTER_ECX: return lastContext.ccx; case ZYDIS_REGISTER_EDX: return lastContext.cdx; case ZYDIS_REGISTER_EBP: return lastContext.cbp; case ZYDIS_REGISTER_ESP: return lastContext.csp; case ZYDIS_REGISTER_ESI: return lastContext.csi; case ZYDIS_REGISTER_EDI: return lastContext.cdi; case ZYDIS_REGISTER_EIP: return lastContext.cip; #else //x64 case ZYDIS_REGISTER_RAX: return lastContext.cax; case ZYDIS_REGISTER_RBX: return lastContext.cbx; case ZYDIS_REGISTER_RCX: return lastContext.ccx; case ZYDIS_REGISTER_RDX: return lastContext.cdx; case ZYDIS_REGISTER_RBP: return lastContext.cbp; case ZYDIS_REGISTER_RSP: return lastContext.csp; case ZYDIS_REGISTER_RSI: return lastContext.csi; case ZYDIS_REGISTER_RDI: return lastContext.cdi; case ZYDIS_REGISTER_RIP: return lastContext.cip; case ZYDIS_REGISTER_R8: return lastContext.r8; case ZYDIS_REGISTER_R9: return lastContext.r9; case ZYDIS_REGISTER_R10: return lastContext.r10; case ZYDIS_REGISTER_R11: return lastContext.r11; case ZYDIS_REGISTER_R12: return lastContext.r12; case ZYDIS_REGISTER_R13: return lastContext.r13; case ZYDIS_REGISTER_R14: return lastContext.r14; case ZYDIS_REGISTER_R15: return lastContext.r15; #endif //_WIN64 default: return 0; } }); if(cp.OpCount() && cp[0].type == ZYDIS_OPERAND_TYPE_MEMORY) { auto const tebseg = ArchValue(ZYDIS_REGISTER_FS, ZYDIS_REGISTER_GS); if(cp[0].mem.segment == tebseg) opValue += duint(GetTEBLocation(hActiveThread)); if(MemRead(opValue, &opValue, sizeof(opValue))) return opValue; } else return opValue; } if(cp.IsRet()) { auto csp = lastContext.csp; duint dest = 0; if(MemRead(csp, &dest, sizeof(dest))) return dest; } return 0; } extern "C" DLL_EXPORT bool _dbg_functionoverlaps(duint start, duint end) { return FunctionOverlaps(start, end); } extern "C" DLL_EXPORT duint _dbg_sendmessage(DBGMSG type, void* param1, void* param2) { if(dbgisstopped()) { switch(type) //ignore win events { //these functions are safe to call when we did not initialize yet case DBG_DEINITIALIZE_LOCKS: case DBG_INITIALIZE_LOCKS: case DBG_GET_FUNCTIONS: case DBG_SETTINGS_UPDATED: case DBG_GET_THREAD_LIST: case DBG_WIN_EVENT: case DBG_WIN_EVENT_GLOBAL: case DBG_RELEASE_ENCODE_TYPE_BUFFER: case DBG_GET_TIME_WASTED_COUNTER: case DBG_GET_DEBUG_ENGINE: break; //the rest is unsafe -> throw an exception when people try to call them default: __debugbreak(); //we cannot process messages when the debugger is stopped, this must be a bug } } switch(type) { case DBG_SCRIPT_LOAD: { scriptload((const char*)param1); } break; case DBG_SCRIPT_UNLOAD: { scriptunload(); } break; case DBG_SCRIPT_RUN: { scriptrun((int)(duint)param1); } break; case DBG_SCRIPT_STEP: { scriptstep(); } break; case DBG_SCRIPT_BPTOGGLE: { return scriptbptoggle((int)(duint)param1); } break; case DBG_SCRIPT_BPGET: { return scriptbpget((int)(duint)param1); } break; case DBG_SCRIPT_CMDEXEC: { return scriptcmdexec((const char*)param1); } break; case DBG_SCRIPT_ABORT: { scriptabort(); } break; case DBG_SCRIPT_GETLINETYPE: { return (duint)scriptgetlinetype((int)(duint)param1); } break; case DBG_SCRIPT_SETIP: { scriptsetip((int)(duint)param1); } break; case DBG_SCRIPT_GETBRANCHINFO: { return (duint)scriptgetbranchinfo((int)(duint)param1, (SCRIPTBRANCH*)param2); } break; case DBG_SYMBOL_ENUM: case DBG_SYMBOL_ENUM_FROMCACHE: { SYMBOLCBINFO* cbInfo = (SYMBOLCBINFO*)param1; if(cbInfo->base == -1) { SHARED_ACQUIRE(LockModules); auto info = ModInfoFromAddr(cbInfo->start); if(info != nullptr && cbInfo->end >= info->base && cbInfo->end < info->base + info->size) { auto beginRva = cbInfo->start - info->base; auto endRva = cbInfo->end - info->base; if(beginRva > endRva) { return false; } return SymEnum(info->base, cbInfo->cbSymbolEnum, cbInfo->user, beginRva, endRva, cbInfo->symbolMask); } else { return false; } } else { return SymEnum(cbInfo->base, cbInfo->cbSymbolEnum, cbInfo->user, 0, -1, SYMBOL_MASK_ALL); } } break; case DBG_ASSEMBLE_AT: { return assembleat((duint)param1, (const char*)param2, 0, 0, false); } break; case DBG_MODBASE_FROM_NAME: { return ModBaseFromName((const char*)param1); } break; case DBG_DISASM_AT: { disasmget((duint)param1, (DISASM_INSTR*)param2); } break; case DBG_STACK_COMMENT_GET: { return stackcommentget((duint)param1, (STACK_COMMENT*)param2); } break; case DBG_GET_THREAD_LIST: { ThreadGetList((THREADLIST*)param1); } break; case DBG_SETTINGS_UPDATED: { valuesetsignedcalc(!settingboolget("Engine", "CalculationType")); //0:signed, 1:unsigned SetEngineVariable(UE_ENGINE_SET_DEBUG_PRIVILEGE, settingboolget("Engine", "EnableDebugPrivilege")); SetEngineVariable(UE_ENGINE_SAFE_ATTACH, settingboolget("Engine", "SafeAttach")); SetEngineVariable(UE_ENGINE_MEMBP_ALT, settingboolget("Engine", "MembpAlt")); SetEngineVariable(UE_ENGINE_DISABLE_ASLR, settingboolget("Engine", "DisableAslr")); bOnlyCipAutoComments = settingboolget("Disassembler", "OnlyCipAutoComments"); bNoSourceLineAutoComments = settingboolget("Disassembler", "NoSourceLineAutoComments"); bListAllPages = settingboolget("Engine", "ListAllPages"); bUndecorateSymbolNames = settingboolget("Engine", "UndecorateSymbolNames"); bEnableSourceDebugging = settingboolget("Engine", "EnableSourceDebugging"); bSkipInt3Stepping = settingboolget("Engine", "SkipInt3Stepping"); bIgnoreInconsistentBreakpoints = settingboolget("Engine", "IgnoreInconsistentBreakpoints"); bNoForegroundWindow = settingboolget("Gui", "NoForegroundWindow"); bVerboseExceptionLogging = settingboolget("Engine", "VerboseExceptionLogging"); bNoWow64SingleStepWorkaround = settingboolget("Engine", "NoWow64SingleStepWorkaround"); bQueryWorkingSet = settingboolget("Misc", "QueryWorkingSet"); bForceLoadSymbols = settingboolget("Misc", "ForceLoadSymbols"); bPidTidInHex = settingboolget("Gui", "PidTidInHex"); stackupdatesettings(); duint setting; if(BridgeSettingGetUint("Engine", "BreakpointType", &setting)) { switch(setting) { case 0: //break_int3short SetBPXOptions(UE_BREAKPOINT_INT3); break; case 1: //break_int3long SetBPXOptions(UE_BREAKPOINT_LONG_INT3); break; case 2: //break_ud2 SetBPXOptions(UE_BREAKPOINT_UD2); break; } } if(BridgeSettingGetUint("Engine", "Assembler", &setting)) assemblerEngine = AssemblerEngine(setting); else { assemblerEngine = AssemblerEngine::asmjit; BridgeSettingSetUint("Engine", "Assembler", duint(assemblerEngine)); } std::vector<char> settingText(MAX_SETTING_SIZE + 1, '\0'); bool unknownExceptionsFilterAdded = false; dbgclearexceptionfilters(); if(BridgeSettingGet("Exceptions", "IgnoreRange", settingText.data())) { char* context = nullptr; auto entry = strtok_s(settingText.data(), ",", &context); while(entry) { unsigned long start; unsigned long end; if(strstr(entry, "debug") == nullptr && // check for old ignore format sscanf_s(entry, "%08X-%08X", &start, &end) == 2 && start <= end) { ExceptionFilter filter; filter.range.start = start; filter.range.end = end; // Default settings for an ignore entry filter.breakOn = ExceptionBreakOn::SecondChance; filter.logException = true; filter.handledBy = ExceptionHandledBy::Debuggee; dbgaddexceptionfilter(filter); } else if(strstr(entry, "debug") != nullptr && // new filter format sscanf_s(entry, "%08X-%08X", &start, &end) == 2 && start <= end) { ExceptionFilter filter; filter.range.start = start; filter.range.end = end; filter.breakOn = strstr(entry, "first") != nullptr ? ExceptionBreakOn::FirstChance : strstr(entry, "second") != nullptr ? ExceptionBreakOn::SecondChance : ExceptionBreakOn::DoNotBreak; filter.logException = strstr(entry, "nolog") == nullptr; filter.handledBy = strstr(entry, "debugger") != nullptr ? ExceptionHandledBy::Debugger : ExceptionHandledBy::Debuggee; dbgaddexceptionfilter(filter); if(filter.range.start == 0 && filter.range.start == filter.range.end) unknownExceptionsFilterAdded = true; } entry = strtok_s(nullptr, ",", &context); } } if(!unknownExceptionsFilterAdded) // add a default filter for unknown exceptions if it was not yet present in settings { ExceptionFilter unknownExceptionsFilter; unknownExceptionsFilter.range.start = unknownExceptionsFilter.range.end = 0; unknownExceptionsFilter.breakOn = ExceptionBreakOn::FirstChance; unknownExceptionsFilter.logException = true; unknownExceptionsFilter.handledBy = ExceptionHandledBy::Debuggee; dbgaddexceptionfilter(unknownExceptionsFilter); } // check if we need to change the main window title bool bNewWindowLongPath = settingboolget("Gui", "WindowLongPath"); if(bWindowLongPath != bNewWindowLongPath) { bWindowLongPath = bNewWindowLongPath; if(DbgIsDebugging()) { duint addr = 0; SELECTIONDATA selection; if(GuiSelectionGet(GUI_DISASSEMBLY, &selection)) addr = selection.start; else addr = GetContextDataEx(hActiveThread, UE_CIP); DebugUpdateTitleAsync(addr, false); } } if(BridgeSettingGet("Symbols", "CachePath", settingText.data())) { // Trim the buffer to fit inside MAX_PATH strncpy_s(szSymbolCachePath, settingText.data(), _TRUNCATE); } duint animateInterval; if(BridgeSettingGetUint("Engine", "AnimateInterval", &animateInterval)) _dbg_setanimateinterval((unsigned int)animateInterval); else _dbg_setanimateinterval(50); // 20 commands per second if(BridgeSettingGetUint("Engine", "MaxSkipExceptionCount", &setting)) maxSkipExceptionCount = setting; else BridgeSettingSetUint("Engine", "MaxSkipExceptionCount", maxSkipExceptionCount); duint newStringAlgorithm = 0; if(!BridgeSettingGetUint("Engine", "NewStringAlgorithm", &newStringAlgorithm)) { auto acp = GetACP(); newStringAlgorithm = acp == 932 || acp == 936 || acp == 949 || acp == 950 || acp == 951 || acp == 1251; } bNewStringAlgorithm = !!newStringAlgorithm; } break; case DBG_DISASM_FAST_AT: { if(!param1 || !param2) return 0; BASIC_INSTRUCTION_INFO* basicinfo = (BASIC_INSTRUCTION_INFO*)param2; if(!disasmfast((duint)param1, basicinfo)) basicinfo->size = 1; return 0; } break; case DBG_MENU_ENTRY_CLICKED: { int hEntry = (int)(duint)param1; pluginmenucall(hEntry); } break; case DBG_FUNCTION_GET: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)FunctionGet(info->addr, &info->start, &info->end); } break; case DBG_FUNCTION_OVERLAPS: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)FunctionOverlaps(info->start, info->end); } break; case DBG_FUNCTION_ADD: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)FunctionAdd(info->start, info->end, info->manual); } break; case DBG_FUNCTION_DEL: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)FunctionDelete(info->addr); } break; case DBG_ARGUMENT_GET: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)ArgumentGet(info->addr, &info->start, &info->end); } break; case DBG_ARGUMENT_OVERLAPS: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)ArgumentOverlaps(info->start, info->end); } break; case DBG_ARGUMENT_ADD: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)ArgumentAdd(info->start, info->end, info->manual); } break; case DBG_ARGUMENT_DEL: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)ArgumentDelete(info->addr); } break; case DBG_LOOP_GET: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)LoopGet(info->depth, info->addr, &info->start, &info->end); } break; case DBG_LOOP_OVERLAPS: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)LoopOverlaps(info->depth, info->start, info->end, 0); } break; case DBG_LOOP_ADD: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)LoopAdd(info->start, info->end, info->manual); } break; case DBG_LOOP_DEL: { FUNCTION_LOOP_INFO* info = (FUNCTION_LOOP_INFO*)param1; return (duint)LoopDelete(info->depth, info->addr); } break; case DBG_IS_RUN_LOCKED: { return (duint)waitislocked(WAITID_RUN); } break; case DBG_IS_BP_DISABLED: { BREAKPOINT bp; if(BpGet((duint)param1, BPNORMAL, 0, &bp)) return !(duint)bp.enabled; return (duint)false; } break; case DBG_SET_AUTO_COMMENT_AT: { return (duint)CommentSet((duint)param1, (const char*)param2, false); } break; case DBG_DELETE_AUTO_COMMENT_RANGE: { CommentDelRange((duint)param1, (duint)param2, false); } break; case DBG_SET_AUTO_LABEL_AT: { return (duint)LabelSet((duint)param1, (const char*)param2, false); } break; case DBG_DELETE_AUTO_LABEL_RANGE: { LabelDelRange((duint)param1, (duint)param2, false); } break; case DBG_SET_AUTO_BOOKMARK_AT: { return (duint)BookmarkSet((duint)param1, false); } break; case DBG_DELETE_AUTO_BOOKMARK_RANGE: { BookmarkDelRange((duint)param1, (duint)param2, false); } break; case DBG_SET_AUTO_FUNCTION_AT: { return (duint)FunctionAdd((duint)param1, (duint)param2, false); } break; case DBG_DELETE_AUTO_FUNCTION_RANGE: { FunctionDelRange((duint)param1, (duint)param2, false); } break; case DBG_GET_XREF_COUNT_AT: { return XrefGetCount((duint)param1); } break; case DBG_XREF_GET: { if(!param2) return false; XREF_INFO* info = (XREF_INFO*)param2; duint address = (duint)param1; info->refcount = XrefGetCount(address); if(info->refcount == 0) { info->references = nullptr; return false; } else { info->references = (XREF_RECORD*)BridgeAlloc(sizeof(XREF_RECORD) * info->refcount); return XrefGet(address, info); } } break; case DBG_XREF_ADD: { return XrefAdd((duint)param1, (duint)param2); } break; case DBG_XREF_DEL_ALL: { return XrefDeleteAll((duint)param1); } break; case DBG_GET_XREF_TYPE_AT: { return XrefGetType((duint)param1); } break; case DBG_GET_ENCODE_TYPE_BUFFER: { return (duint)EncodeMapGetBuffer((duint)param1, (duint*)param2); } break; case DBG_ENCODE_TYPE_GET: { return EncodeMapGetType((duint)param1, (duint)param2); } break; case DBG_ENCODE_SIZE_GET: { return EncodeMapGetSize((duint)param1, (duint)param2); } break; case DBG_DELETE_ENCODE_TYPE_RANGE: { EncodeMapDelRange((duint)param1, (duint)param2); } break; case DBG_DELETE_ENCODE_TYPE_SEG: { EncodeMapDelSegment((duint)param1); } break; case DBG_RELEASE_ENCODE_TYPE_BUFFER: { EncodeMapReleaseBuffer(param1); } break; case DBG_GET_STRING_AT: { return disasmgetstringatwrapper(duint(param1), (char*)param2); } break; case DBG_GET_FUNCTIONS: { return (duint)dbgfunctionsget(); } break; case DBG_WIN_EVENT: { return (duint)pluginwinevent((MSG*)param1, (long*)param2); } break; case DBG_WIN_EVENT_GLOBAL: { return (duint)pluginwineventglobal((MSG*)param1); } break; case DBG_INITIALIZE_LOCKS: { SectionLockerGlobal::Initialize(); } break; case DBG_DEINITIALIZE_LOCKS: { SectionLockerGlobal::Deinitialize(); } break; case DBG_GET_TIME_WASTED_COUNTER: return dbggettimewastedcounter(); case DBG_DELETE_COMMENT_RANGE: { CommentDelRange((duint)param1, (duint)param2, true); } break; case DBG_DELETE_LABEL_RANGE: { LabelDelRange((duint)param1, (duint)param2, true); } break; case DBG_DELETE_BOOKMARK_RANGE: { BookmarkDelRange((duint)param1, (duint)param2, true); } break; case DBG_GET_WATCH_LIST: { BridgeList<WATCHINFO>::CopyData((ListInfo*)param1, WatchGetList()); } break; case DBG_SELCHANGED: { PLUG_CB_SELCHANGED plugSelChanged; plugSelChanged.hWindow = (int)param1; plugSelChanged.VA = (duint)param2; plugincbcall(CB_SELCHANGED, &plugSelChanged); } break; case DBG_GET_PROCESS_HANDLE: { return duint(fdProcessInfo->hProcess); } break; case DBG_GET_THREAD_HANDLE: { return duint(hActiveThread); } break; case DBG_GET_PROCESS_ID: { return duint(fdProcessInfo->dwProcessId); } break; case DBG_GET_THREAD_ID: { return duint(ThreadGetId(hActiveThread)); } break; case DBG_GET_PEB_ADDRESS: { auto ProcessId = DWORD(param1); if(ProcessId == fdProcessInfo->dwProcessId) return (duint)GetPEBLocation(fdProcessInfo->hProcess); auto hProcess = TitanOpenProcess(PROCESS_QUERY_INFORMATION, false, ProcessId); duint pebAddress = 0; if(hProcess) { pebAddress = (duint)GetPEBLocation(hProcess); CloseHandle(hProcess); } return pebAddress; } break; case DBG_GET_TEB_ADDRESS: { auto ThreadId = DWORD(param1); auto tebAddress = ThreadGetLocalBase(ThreadId); if(tebAddress) return tebAddress; HANDLE hThread = TitanOpenThread(THREAD_QUERY_INFORMATION, FALSE, ThreadId); if(hThread) { tebAddress = (duint)GetTEBLocation(hThread); CloseHandle(hThread); } return tebAddress; } break; case DBG_ANALYZE_FUNCTION: { auto entry = duint(param1); duint size; auto base = MemFindBaseAddr(entry, &size); if(!base || !MemIsValidReadPtr(entry)) return false; auto modbase = ModBaseFromAddr(base); if(modbase) base = modbase, size = ModSizeFromAddr(modbase); RecursiveAnalysis analysis(base, size, entry, true); analysis.Analyse(); auto graph = analysis.GetFunctionGraph(entry); if(!graph) return false; *(BridgeCFGraphList*)param2 = graph->ToGraphList(); return true; } break; case DBG_MENU_PREPARE: { PLUG_CB_MENUPREPARE info; info.hMenu = GUIMENUTYPE(duint(param1)); plugincbcall(CB_MENUPREPARE, &info); } break; case DBG_GET_SYMBOL_INFO: { auto symbolptr = (const SYMBOLPTR*)param1; ((const SymbolInfoGui*)symbolptr->symbol)->convertToGuiSymbol(symbolptr->modbase, (SYMBOLINFO*)param2); } break; case DBG_GET_DEBUG_ENGINE: { static auto debugEngine = [] { duint setting = DebugEngineTitanEngine; if(!BridgeSettingGetUint("Engine", "DebugEngine", &setting)) { BridgeSettingSetUint("Engine", "DebugEngine", setting); } return (DEBUG_ENGINE)setting; }(); return debugEngine; } break; case DBG_GET_SYMBOL_INFO_AT: { return SymbolFromAddressExact((duint)param1, (SYMBOLINFO*)param2); } break; case DBG_XREF_ADD_MULTI: { return XrefAddMulti((const XREF_EDGE*)param1, (duint)param2); } break; } return 0; }
C/C++
x64dbg-development/src/dbg/_exports.h
#ifndef _EXPORTS_H #define _EXPORTS_H #include "_global.h" #ifdef __cplusplus extern "C" { #endif DLL_EXPORT duint _dbg_memfindbaseaddr(duint addr, duint* size); DLL_EXPORT bool _dbg_memread(duint addr, unsigned char* dest, duint size, duint* read); DLL_EXPORT bool _dbg_memwrite(duint addr, const unsigned char* src, duint size, duint* written); DLL_EXPORT bool _dbg_memmap(MEMMAP* memmap); DLL_EXPORT bool _dbg_memisvalidreadptr(duint addr); DLL_EXPORT bool _dbg_valfromstring(const char* string, duint* value); DLL_EXPORT bool _dbg_isdebugging(); DLL_EXPORT bool _dbg_isjumpgoingtoexecute(duint addr); DLL_EXPORT bool _dbg_addrinfoget(duint addr, SEGMENTREG segment, BRIDGE_ADDRINFO* addrinfo); DLL_EXPORT bool _dbg_addrinfoset(duint addr, BRIDGE_ADDRINFO* addrinfo); DLL_EXPORT bool _dbg_encodetypeset(duint addr, duint size, ENCODETYPE type); DLL_EXPORT int _dbg_bpgettypeat(duint addr); DLL_EXPORT bool _dbg_getregdump(REGDUMP* regdump); DLL_EXPORT bool _dbg_valtostring(const char* string, duint value); DLL_EXPORT int _dbg_getbplist(BPXTYPE type, BPMAP* list); DLL_EXPORT duint _dbg_getbranchdestination(duint addr); DLL_EXPORT bool _dbg_functionoverlaps(duint start, duint end); DLL_EXPORT duint _dbg_sendmessage(DBGMSG type, void* param1, void* param2); #ifdef __cplusplus } #endif #endif // _EXPORTS_H
C++
x64dbg-development/src/dbg/_global.cpp
/** \file _global.cpp \brief Implements the global class. */ #include "_global.h" #include <objbase.h> #include <shlobj.h> #include <psapi.h> #include "DeviceNameResolver/DeviceNameResolver.h" /** \brief x64dbg library instance. */ HINSTANCE hInst; /** \brief Number of allocated buffers by emalloc(). This should be 0 when x64dbg ends. */ static int emalloc_count = 0; #ifdef ENABLE_MEM_TRACE /** \brief Path for debugging, used to create an allocation trace file on emalloc() or efree(). Not used. */ static char alloctrace[MAX_PATH] = ""; static std::unordered_map<void*, int> alloctracemap; static CRITICAL_SECTION criticalSection; #endif /** \brief Allocates a new buffer. \param size The size of the buffer to allocate (in bytes). \param reason The reason for allocation (can be used for memory allocation tracking). \return Always returns a valid pointer to the buffer you requested. Will quit the application on errors. */ void* emalloc(size_t size, const char* reason) { ASSERT_NONZERO(size); #ifdef ENABLE_MEM_TRACE unsigned char* a = (unsigned char*)GlobalAlloc(GMEM_FIXED, size + sizeof(void*)); #else unsigned char* a = (unsigned char*)GlobalAlloc(GMEM_FIXED, size); #endif //ENABLE_MEM_TRACE if(!a) { wchar_t sizeString[25]; swprintf_s(sizeString, L"%p bytes", size); MessageBoxW(0, L"Could not allocate memory (minidump will be created)", sizeString, MB_ICONERROR); __debugbreak(); ExitProcess(1); } emalloc_count++; #ifdef ENABLE_MEM_TRACE EnterCriticalSection(&criticalSection); memset(a, 0, size + sizeof(void*)); FILE* file = fopen(alloctrace, "a+"); fprintf(file, "DBG%.5d: alloc:%p:%p:%s:%p\n", emalloc_count, a, _ReturnAddress(), reason, size); fclose(file); alloctracemap[_ReturnAddress()]++; *(void**)a = _ReturnAddress(); LeaveCriticalSection(&criticalSection); return a + sizeof(void*); #else memset(a, 0, size); return a; #endif //ENABLE_MEM_TRACE } /** \brief Reallocates a buffer allocated with emalloc(). \param [in] Pointer to memory previously allocated with emalloc(). When NULL a new buffer will be allocated by emalloc(). \param size The new memory size. \param reason The reason for allocation (can be used for memory allocation tracking). \return Always returns a valid pointer to the buffer you requested. Will quit the application on errors. */ void* erealloc(void* ptr, size_t size, const char* reason) { ASSERT_NONZERO(size); // Free the memory if the pointer was set (as per documentation). if(ptr) efree(ptr, reason); return emalloc(size, reason); } /** \brief Free memory previously allocated with emalloc(). \param [in] Pointer to the memory to free. \param reason The reason for freeing, should be the same as the reason for allocating. */ void efree(void* ptr, const char* reason) { emalloc_count--; #ifdef ENABLE_MEM_TRACE EnterCriticalSection(&criticalSection); char* ptr2 = (char*)ptr - sizeof(void*); FILE* file = fopen(alloctrace, "a+"); fprintf(file, "DBG%.5d: free:%p:%p:%s\n", emalloc_count, ptr, *(void**)ptr2, reason); fclose(file); if(alloctracemap.find(*(void**)ptr2) != alloctracemap.end()) { if(--alloctracemap.at(*(void**)ptr2) < 0) { String str = StringUtils::sprintf("address %p, reason %s", *(void**)ptr2, reason); MessageBoxA(0, str.c_str(), "Freed memory more than once", MB_OK); __debugbreak(); } } else { String str = StringUtils::sprintf("address %p, reason %s", *(void**)ptr2, reason); MessageBoxA(0, str.c_str(), "Trying to free const memory", MB_OK); __debugbreak(); } LeaveCriticalSection(&criticalSection); GlobalFree(ptr2); #else GlobalFree(ptr); #endif //ENABLE_MEM_TRACE } void* json_malloc(size_t size) { #ifdef ENABLE_MEM_TRACE return emalloc(size, "json:ptr"); #else return emalloc(size); #endif } void json_free(void* ptr) { #ifdef ENABLE_MEM_TRACE return efree(ptr, "json:ptr"); #else return efree(ptr); #endif } /** \brief Gets the number of memory leaks. This number is only valid in _dbg_dbgexitsignal(). \return The number of memory leaks. */ int memleaks() { #ifdef ENABLE_MEM_TRACE EnterCriticalSection(&criticalSection); auto leaked = false; for(auto & i : alloctracemap) { if(i.second != 0) { String str = StringUtils::sprintf("memory leak at %p : count %d", i.first, i.second); MessageBoxA(0, str.c_str(), "memory leak", MB_OK); leaked = true; } } if(leaked) __debugbreak(); LeaveCriticalSection(&criticalSection); #endif return emalloc_count; } #ifdef ENABLE_MEM_TRACE /** \brief Sets the path for the allocation trace file. \param file UTF-8 filepath. */ void setalloctrace(const char* file) { InitializeCriticalSection(&criticalSection); strcpy_s(alloctrace, file); } #endif //ENABLE_MEM_TRACE /** \brief Compares two strings without case-sensitivity. \param a The first string. \param b The second string. \return true if the strings are equal (case-insensitive). */ bool scmp(const char* a, const char* b) { if(!a || !b) return false; return !_stricmp(a, b); } /** \brief Queries if a given file exists. \param file Path to the file to check (UTF-8). \return true if the file exists on the hard drive. */ bool FileExists(const char* file) { DWORD attrib = GetFileAttributesW(StringUtils::Utf8ToUtf16(file).c_str()); return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY)); } /** \brief Queries if a given directory exists. \param dir Path to the directory to check (UTF-8). \return true if the directory exists. */ bool DirExists(const char* dir) { DWORD attrib = GetFileAttributesW(StringUtils::Utf8ToUtf16(dir).c_str()); return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0); } /** \brief Gets file path from a file handle. \param hFile File handle to get the path from. \param [in,out] szFileName Buffer of size MAX_PATH. \return true if it succeeds, false if it fails. */ bool GetFileNameFromHandle(HANDLE hFile, char* szFileName, size_t nCount) { if(!hFile) return false; wchar_t wszFileName[MAX_PATH] = L""; if(!PathFromFileHandleW(hFile, wszFileName, _countof(wszFileName))) return false; auto utf8 = StringUtils::Utf16ToUtf8(wszFileName); if(utf8.rfind(R"(\Device\vmsmb\VSMB-)", 0) == 0) { // Hack for Windows Sandbox auto windowsIdx = utf8.find(R"(\os\Windows\)"); if(windowsIdx != std::string::npos) { utf8 = R"(C:\)" + utf8.substr(windowsIdx + 4); } } if(utf8.rfind(R"(\Device\)", 0) == 0) { // CreateFileW does not work on \Device\ paths directly, you need to prepend this utf8.insert(0, R"(\\?\GLOBALROOT)"); } strncpy_s(szFileName, nCount, utf8.c_str(), _TRUNCATE); return true; } bool GetFileNameFromProcessHandle(HANDLE hProcess, char* szFileName, size_t nCount) { wchar_t wszDosFileName[MAX_PATH] = L""; wchar_t wszFileName[MAX_PATH] = L""; auto result = false; if(GetProcessImageFileNameW(hProcess, wszDosFileName, _countof(wszDosFileName))) { if(!DevicePathToPathW(wszDosFileName, wszFileName, _countof(wszFileName))) result = !!GetModuleFileNameExW(hProcess, 0, wszFileName, _countof(wszFileName)); else result = true; } else result = !!GetModuleFileNameExW(hProcess, 0, wszFileName, _countof(wszFileName)); if(result) strncpy_s(szFileName, nCount, StringUtils::Utf16ToUtf8(wszFileName).c_str(), _TRUNCATE); return result; } bool GetFileNameFromModuleHandle(HANDLE hProcess, HMODULE hModule, char* szFileName, size_t nCount) { wchar_t wszDosFileName[MAX_PATH] = L""; wchar_t wszFileName[MAX_PATH] = L""; auto result = false; if(GetMappedFileNameW(hProcess, hModule, wszDosFileName, _countof(wszDosFileName))) { if(!DevicePathToPathW(wszDosFileName, wszFileName, _countof(wszFileName))) result = !!GetModuleFileNameExW(hProcess, hModule, wszFileName, _countof(wszFileName)); else result = true; } else result = !!GetModuleFileNameExW(hProcess, hModule, wszFileName, _countof(wszFileName)); if(result) strncpy_s(szFileName, nCount, StringUtils::Utf16ToUtf8(wszFileName).c_str(), _TRUNCATE); return result; } /** \brief Get a boolean setting from the configuration file. \param section The section of the setting (UTF-8). \param name The name of the setting (UTF-8). \return true if the setting was set and equals to true, otherwise returns false. */ bool settingboolget(const char* section, const char* name) { duint setting; if(!BridgeSettingGetUint(section, name, &setting)) return false; if(setting) return true; return false; } /** \brief Query if x64dbg is running in Wow64 mode. \return true if running in Wow64, false otherwise. */ bool IsWow64() { BOOL bIsWow64Process = FALSE; //x64dbg supports WinXP SP3 and later only, so ignore the GetProcAddress crap :D IsWow64Process(GetCurrentProcess(), &bIsWow64Process); return !!bIsWow64Process; } //Taken from: http://www.cplusplus.com/forum/windows/64088/ //And: https://codereview.stackexchange.com/a/2917 bool ResolveShortcut(HWND hwnd, const wchar_t* szShortcutPath, std::wstring & executable, std::wstring & arguments, std::wstring & workingDir) { //Initialize COM stuff if(!SUCCEEDED(CoInitialize(NULL))) return false; //Get a pointer to the IShellLink interface. IShellLinkW* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (LPVOID*)&psl); if(SUCCEEDED(hres)) { //Get a pointer to the IPersistFile interface. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf); if(SUCCEEDED(hres)) { //Load the shortcut. hres = ppf->Load(szShortcutPath, STGM_READ); if(SUCCEEDED(hres)) { //Resolve the link. hres = psl->Resolve(hwnd, 0); if(SUCCEEDED(hres)) { //Get the path to the link target. wchar_t linkTarget[MAX_PATH]; hres = psl->GetPath(linkTarget, _countof(linkTarget), NULL, SLGP_RAWPATH); //Expand the environment variables. wchar_t expandedTarget[MAX_PATH]; auto expandSuccess = !!ExpandEnvironmentStringsW(linkTarget, expandedTarget, _countof(expandedTarget)); if(SUCCEEDED(hres) && expandSuccess) { executable = expandedTarget; // Extract the arguments wchar_t linkArgs[MAX_PATH]; if(SUCCEEDED(psl->GetArguments(linkArgs, _countof(linkArgs)))) { arguments = linkArgs; } // Extract the working directory wchar_t linkDir[MAX_PATH]; if(SUCCEEDED(psl->GetWorkingDirectory(linkDir, _countof(linkDir)))) { workingDir = linkDir; } } } } //Release the pointer to the IPersistFile interface. ppf->Release(); } //Release the pointer to the IShellLink interface. psl->Release(); } //Uninitialize COM stuff CoUninitialize(); return SUCCEEDED(hres); } void WaitForThreadTermination(HANDLE hThread, DWORD timeout) { WaitForSingleObject(hThread, timeout); CloseHandle(hThread); } void WaitForMultipleThreadsTermination(const HANDLE* hThread, int count, DWORD timeout) { WaitForMultipleObjects(count, hThread, TRUE, timeout); for(int i = 0; i < count; i++) CloseHandle(hThread[i]); }
C/C++
x64dbg-development/src/dbg/_global.h
#pragma once #ifdef _WIN64 #define _WIN32_WINNT 0x0502 // XP x64 is version 5.2 #else #define _WIN32_WINNT 0x0501 #endif #ifdef WINVER // Overwrite WINVER if given on command line #undef WINVER #endif #define WINVER _WIN32_WINNT #define _WIN32_IE 0x0500 // Allow including Windows.h without bringing in a redefined and outdated subset of NTSTATUSes. // To get NTSTATUS defines, #undef WIN32_NO_STATUS after Windows.h and then #include <ntstatus.h> #define WIN32_NO_STATUS #include "../dbg_types.h" #include "../dbg_assert.h" #include "../bridge/bridgemain.h" #include "stringutils.h" #ifndef DLL_EXPORT #define DLL_EXPORT __declspec(dllexport) #endif //DLL_IMPORT #ifndef DLL_IMPORT #define DLL_IMPORT __declspec(dllimport) #endif //DLL_IMPORT #ifndef QT_TRANSLATE_NOOP #define QT_TRANSLATE_NOOP(context, source) source #endif //QT_TRANSLATE_NOOP // Uncomment the following line to allow memory leak tracing //#define ENABLE_MEM_TRACE //defines #define deflen 1024 //superglobal variables extern HINSTANCE hInst; //functions #ifdef ENABLE_MEM_TRACE void* emalloc(size_t size, const char* reason = "emalloc:???"); void* erealloc(void* ptr, size_t size, const char* reason = "erealloc:???"); void efree(void* ptr, const char* reason = "efree:???"); #else void* emalloc(size_t size, const char* reason = nullptr); void* erealloc(void* ptr, size_t size, const char* reason = nullptr); void efree(void* ptr, const char* reason = nullptr); #endif //ENABLE_MEM_TRACE void* json_malloc(size_t size); void json_free(void* ptr); int memleaks(); void setalloctrace(const char* file); bool scmp(const char* a, const char* b); bool FileExists(const char* file); bool DirExists(const char* dir); bool GetFileNameFromHandle(HANDLE hFile, char* szFileName, size_t nCount); bool GetFileNameFromProcessHandle(HANDLE hProcess, char* szFileName, size_t nCount); bool GetFileNameFromModuleHandle(HANDLE hProcess, HMODULE hModule, char* szFileName, size_t nCount); bool settingboolget(const char* section, const char* name); bool IsWow64(); bool ResolveShortcut(HWND hwnd, const wchar_t* szShortcutPath, std::wstring & executable, std::wstring & arguments, std::wstring & workingDir); void WaitForThreadTermination(HANDLE hThread, DWORD timeout = INFINITE); void WaitForMultipleThreadsTermination(const HANDLE* hThread, int count, DWORD timeout = INFINITE); #ifdef _WIN64 #define ArchValue(x32value, x64value) x64value #else #define ArchValue(x32value, x64value) x32value #endif //_WIN64 #include "dynamicmem.h"
C++
x64dbg-development/src/dbg/_plugins.cpp
/** @file _plugins.cpp @brief Implements the plugins class. */ #include "_plugins.h" #include "plugin_loader.h" #include "console.h" #include "debugger.h" #include "threading.h" #include "murmurhash.h" ///debugger plugin exports (wrappers) PLUG_IMPEXP void _plugin_registercallback(int pluginHandle, CBTYPE cbType, CBPLUGIN cbPlugin) { pluginregistercallback(pluginHandle, cbType, cbPlugin); } PLUG_IMPEXP bool _plugin_unregistercallback(int pluginHandle, CBTYPE cbType) { return pluginunregistercallback(pluginHandle, cbType); } PLUG_IMPEXP bool _plugin_registercommand(int pluginHandle, const char* command, CBPLUGINCOMMAND cbCommand, bool debugonly) { return plugincmdregister(pluginHandle, command, cbCommand, debugonly); } PLUG_IMPEXP bool _plugin_unregistercommand(int pluginHandle, const char* command) { return plugincmdunregister(pluginHandle, command); } PLUG_IMPEXP void _plugin_logprintf(const char* format, ...) { va_list args; va_start(args, format); dprintf_args_untranslated(format, args); va_end(args); } PLUG_IMPEXP void _plugin_lograw_html(const char* text) { dprint_untranslated_html(text); } PLUG_IMPEXP void _plugin_logputs(const char* text) { dputs_untranslated(text); } PLUG_IMPEXP void _plugin_logprint(const char* text) { dprintf_untranslated("%s", text); } PLUG_IMPEXP void _plugin_debugpause() { DebugUpdateGuiSetStateAsync(GetContextDataEx(hActiveThread, UE_CIP), paused); lock(WAITID_RUN); dbgsetforeground(); dbgsetskipexceptions(false); // Plugin callback PLUG_CB_PAUSEDEBUG pauseInfo = { nullptr }; plugincbcall(CB_PAUSEDEBUG, &pauseInfo); wait(WAITID_RUN); } PLUG_IMPEXP void _plugin_debugskipexceptions(bool skip) { dbgsetskipexceptions(skip); } PLUG_IMPEXP int _plugin_menuadd(int hMenu, const char* title) { return pluginmenuadd(hMenu, title); } PLUG_IMPEXP bool _plugin_menuaddentry(int hMenu, int hEntry, const char* title) { return pluginmenuaddentry(hMenu, hEntry, title); } PLUG_IMPEXP bool _plugin_menuaddseparator(int hMenu) { return pluginmenuaddseparator(hMenu); } PLUG_IMPEXP bool _plugin_menuclear(int hMenu) { return pluginmenuclear(hMenu, false); } PLUG_IMPEXP void _plugin_menuseticon(int hMenu, const ICONDATA* icon) { pluginmenuseticon(hMenu, icon); } PLUG_IMPEXP void _plugin_menuentryseticon(int pluginHandle, int hEntry, const ICONDATA* icon) { pluginmenuentryseticon(pluginHandle, hEntry, icon); } PLUG_IMPEXP void _plugin_menuentrysetchecked(int pluginHandle, int hEntry, bool checked) { pluginmenuentrysetchecked(pluginHandle, hEntry, checked); } PLUG_IMPEXP void _plugin_menusetvisible(int pluginHandle, int hMenu, bool visible) { pluginmenusetvisible(pluginHandle, hMenu, visible); } PLUG_IMPEXP void _plugin_menuentrysetvisible(int pluginHandle, int hEntry, bool visible) { pluginmenuentrysetvisible(pluginHandle, hEntry, visible); } PLUG_IMPEXP void _plugin_menusetname(int pluginHandle, int hMenu, const char* name) { pluginmenusetname(pluginHandle, hMenu, name); } PLUG_IMPEXP void _plugin_menuentrysetname(int pluginHandle, int hEntry, const char* name) { pluginmenuentrysetname(pluginHandle, hEntry, name); } PLUG_IMPEXP void _plugin_menuentrysethotkey(int pluginHandle, int hEntry, const char* hotkey) { pluginmenuentrysethotkey(pluginHandle, hEntry, hotkey); } PLUG_IMPEXP bool _plugin_menuremove(int hMenu) { return pluginmenuremove(hMenu); } PLUG_IMPEXP bool _plugin_menuentryremove(int pluginHandle, int hEntry) { return pluginmenuentryremove(pluginHandle, hEntry); } PLUG_IMPEXP void _plugin_startscript(CBPLUGINSCRIPT cbScript) { dbgstartscriptthread(cbScript); } PLUG_IMPEXP bool _plugin_waituntilpaused() { while(DbgIsDebugging() && dbgisrunning()) //wait until the debugger paused { Sleep(1); GuiProcessEvents(); //workaround for scripts being executed on the GUI thread } return DbgIsDebugging(); } bool _plugin_registerexprfunction(int pluginHandle, const char* name, int argc, CBPLUGINEXPRFUNCTION cbFunction, void* userdata) { return pluginexprfuncregister(pluginHandle, name, argc, cbFunction, userdata); } bool _plugin_registerexprfunctionex(int pluginHandle, const char* name, const ValueType & returnType, const ValueType* argTypes, size_t argCount, CBPLUGINEXPRFUNCTIONEX cbFunction, void* userdata) { return pluginexprfuncregisterex(pluginHandle, name, returnType, argTypes, argCount, cbFunction, userdata); } bool _plugin_unregisterexprfunction(int pluginHandle, const char* name) { return pluginexprfuncunregister(pluginHandle, name); } PLUG_IMPEXP bool _plugin_unload(const char* pluginName) { return pluginunload(pluginName); } PLUG_IMPEXP bool _plugin_load(const char* pluginName) { return pluginload(pluginName); } duint _plugin_hash(const void* data, duint size) { return murmurhash(data, int(size)); } PLUG_IMPEXP bool _plugin_registerformatfunction(int pluginHandle, const char* type, CBPLUGINFORMATFUNCTION cbFunction, void* userdata) { return pluginformatfuncregister(pluginHandle, type, cbFunction, userdata); } PLUG_IMPEXP bool _plugin_unregisterformatfunction(int pluginHandle, const char* type) { return pluginformatfuncunregister(pluginHandle, type); }
C/C++
x64dbg-development/src/dbg/_plugins.h
#ifndef _PLUGINS_H #define _PLUGINS_H #ifndef __cplusplus #include <stdbool.h> #endif #ifndef PLUG_IMPEXP #ifdef BUILD_DBG #define PLUG_IMPEXP __declspec(dllexport) #else #define PLUG_IMPEXP __declspec(dllimport) #endif //BUILD_DBG #endif //PLUG_IMPEXP #include "_plugin_types.h" //default structure alignments forced #ifdef _WIN64 #pragma pack(push, 16) #else //x86 #pragma pack(push, 8) #endif //_WIN64 //defines #define PLUG_SDKVERSION 1 #define PLUG_DB_LOADSAVE_DATA 1 #define PLUG_DB_LOADSAVE_ALL 2 //structures typedef struct { //provided by the debugger int pluginHandle; //provided by the pluginit function int sdkVersion; int pluginVersion; char pluginName[256]; } PLUG_INITSTRUCT; typedef struct { //provided by the debugger HWND hwndDlg; //gui window handle int hMenu; //plugin menu handle int hMenuDisasm; //plugin disasm menu handle int hMenuDump; //plugin dump menu handle int hMenuStack; //plugin stack menu handle int hMenuGraph; //plugin graph menu handle int hMenuMemmap; //plugin memory map menu handle int hMenuSymmod; //plugin symbol module menu handle } PLUG_SETUPSTRUCT; typedef struct { void* data; //user data } PLUG_SCRIPTSTRUCT; //callback structures typedef struct { const char* szFileName; } PLUG_CB_INITDEBUG; typedef struct { void* reserved; } PLUG_CB_STOPDEBUG; typedef struct { void* reserved; } PLUG_CB_STOPPINGDEBUG; typedef struct { CREATE_PROCESS_DEBUG_INFO* CreateProcessInfo; IMAGEHLP_MODULE64* modInfo; const char* DebugFileName; PROCESS_INFORMATION* fdProcessInfo; } PLUG_CB_CREATEPROCESS; typedef struct { EXIT_PROCESS_DEBUG_INFO* ExitProcess; } PLUG_CB_EXITPROCESS; typedef struct { CREATE_THREAD_DEBUG_INFO* CreateThread; DWORD dwThreadId; } PLUG_CB_CREATETHREAD; typedef struct { EXIT_THREAD_DEBUG_INFO* ExitThread; DWORD dwThreadId; } PLUG_CB_EXITTHREAD; typedef struct { void* reserved; } PLUG_CB_SYSTEMBREAKPOINT; typedef struct { LOAD_DLL_DEBUG_INFO* LoadDll; IMAGEHLP_MODULE64* modInfo; const char* modname; } PLUG_CB_LOADDLL; typedef struct { UNLOAD_DLL_DEBUG_INFO* UnloadDll; } PLUG_CB_UNLOADDLL; typedef struct { OUTPUT_DEBUG_STRING_INFO* DebugString; } PLUG_CB_OUTPUTDEBUGSTRING; typedef struct { EXCEPTION_DEBUG_INFO* Exception; } PLUG_CB_EXCEPTION; typedef struct { BRIDGEBP* breakpoint; } PLUG_CB_BREAKPOINT; typedef struct { void* reserved; } PLUG_CB_PAUSEDEBUG; typedef struct { void* reserved; } PLUG_CB_RESUMEDEBUG; typedef struct { void* reserved; } PLUG_CB_STEPPED; typedef struct { DWORD dwProcessId; } PLUG_CB_ATTACH; typedef struct { PROCESS_INFORMATION* fdProcessInfo; } PLUG_CB_DETACH; typedef struct { DEBUG_EVENT* DebugEvent; } PLUG_CB_DEBUGEVENT; typedef struct { int hEntry; } PLUG_CB_MENUENTRY; typedef struct { MSG* message; long* result; bool retval; } PLUG_CB_WINEVENT; typedef struct { MSG* message; bool retval; } PLUG_CB_WINEVENTGLOBAL; typedef struct { json_t* root; int loadSaveType; } PLUG_CB_LOADSAVEDB; typedef struct { const char* symbol; bool retval; } PLUG_CB_FILTERSYMBOL; typedef struct { duint cip; bool stop; } PLUG_CB_TRACEEXECUTE; typedef struct { int hWindow; duint VA; } PLUG_CB_SELCHANGED; typedef struct { BridgeCFGraphList graph; } PLUG_CB_ANALYZE; typedef struct { duint addr; BRIDGE_ADDRINFO* addrinfo; bool retval; } PLUG_CB_ADDRINFO; typedef struct { const char* string; duint value; int* value_size; bool* isvar; bool* hexonly; bool retval; } PLUG_CB_VALFROMSTRING; typedef struct { const char* string; duint value; bool retval; } PLUG_CB_VALTOSTRING; typedef struct { GUIMENUTYPE hMenu; } PLUG_CB_MENUPREPARE; typedef enum { ValueTypeNumber, ValueTypeString, ValueTypeAny, // Cannot be used for values, only for argTypes (to accept any type) } ValueType; typedef struct { const char* ptr; // Should be allocated with BridgeAlloc bool isOwner; // When set to true BridgeFree will be called on ptr } StringValue; typedef struct { ValueType type; duint number; StringValue string; } ExpressionValue; //enums typedef enum { CB_INITDEBUG, //PLUG_CB_INITDEBUG CB_STOPDEBUG, //PLUG_CB_STOPDEBUG CB_CREATEPROCESS, //PLUG_CB_CREATEPROCESS CB_EXITPROCESS, //PLUG_CB_EXITPROCESS CB_CREATETHREAD, //PLUG_CB_CREATETHREAD CB_EXITTHREAD, //PLUG_CB_EXITTHREAD CB_SYSTEMBREAKPOINT, //PLUG_CB_SYSTEMBREAKPOINT CB_LOADDLL, //PLUG_CB_LOADDLL CB_UNLOADDLL, //PLUG_CB_UNLOADDLL CB_OUTPUTDEBUGSTRING, //PLUG_CB_OUTPUTDEBUGSTRING CB_EXCEPTION, //PLUG_CB_EXCEPTION CB_BREAKPOINT, //PLUG_CB_BREAKPOINT CB_PAUSEDEBUG, //PLUG_CB_PAUSEDEBUG CB_RESUMEDEBUG, //PLUG_CB_RESUMEDEBUG CB_STEPPED, //PLUG_CB_STEPPED CB_ATTACH, //PLUG_CB_ATTACHED (before attaching, after CB_INITDEBUG) CB_DETACH, //PLUG_CB_DETACH (before detaching, before CB_STOPDEBUG) CB_DEBUGEVENT, //PLUG_CB_DEBUGEVENT (called on any debug event) CB_MENUENTRY, //PLUG_CB_MENUENTRY CB_WINEVENT, //PLUG_CB_WINEVENT CB_WINEVENTGLOBAL, //PLUG_CB_WINEVENTGLOBAL CB_LOADDB, //PLUG_CB_LOADSAVEDB CB_SAVEDB, //PLUG_CB_LOADSAVEDB CB_FILTERSYMBOL, //PLUG_CB_FILTERSYMBOL CB_TRACEEXECUTE, //PLUG_CB_TRACEEXECUTE CB_SELCHANGED, //PLUG_CB_SELCHANGED CB_ANALYZE, //PLUG_CB_ANALYZE CB_ADDRINFO, //PLUG_CB_ADDRINFO CB_VALFROMSTRING, //PLUG_CB_VALFROMSTRING CB_VALTOSTRING, //PLUG_CB_VALTOSTRING CB_MENUPREPARE, //PLUG_CB_MENUPREPARE CB_STOPPINGDEBUG, //PLUG_CB_STOPDEBUG CB_LAST } CBTYPE; typedef enum { FORMAT_ERROR, //generic failure (no message) FORMAT_SUCCESS, //success FORMAT_ERROR_MESSAGE, //formatting failed but an error was put in the buffer (there are always at least 511 characters available). FORMAT_BUFFER_TOO_SMALL //buffer too small (x64dbg will retry until the buffer is big enough) } FORMATRESULT; //typedefs typedef void (*CBPLUGIN)(CBTYPE cbType, void* callbackInfo); typedef bool (*CBPLUGINCOMMAND)(int argc, char** argv); typedef void (*CBPLUGINSCRIPT)(); typedef duint(*CBPLUGINEXPRFUNCTION)(int argc, const duint* argv, void* userdata); typedef bool(*CBPLUGINEXPRFUNCTIONEX)(ExpressionValue* result, int argc, const ExpressionValue* argv, void* userdata); typedef FORMATRESULT(*CBPLUGINFORMATFUNCTION)(char* dest, size_t destCount, int argc, char* argv[], duint value, void* userdata); typedef bool (*CBPLUGINPREDICATE)(void* userdata); //exports #ifdef __cplusplus extern "C" { #endif PLUG_IMPEXP void _plugin_registercallback(int pluginHandle, CBTYPE cbType, CBPLUGIN cbPlugin); PLUG_IMPEXP bool _plugin_unregistercallback(int pluginHandle, CBTYPE cbType); PLUG_IMPEXP bool _plugin_registercommand(int pluginHandle, const char* command, CBPLUGINCOMMAND cbCommand, bool debugonly); PLUG_IMPEXP bool _plugin_unregistercommand(int pluginHandle, const char* command); PLUG_IMPEXP void _plugin_logprintf(const char* format, ...); PLUG_IMPEXP void _plugin_lograw_html(const char* text); PLUG_IMPEXP void _plugin_logputs(const char* text); PLUG_IMPEXP void _plugin_logprint(const char* text); PLUG_IMPEXP void _plugin_debugpause(); PLUG_IMPEXP void _plugin_debugskipexceptions(bool skip); PLUG_IMPEXP int _plugin_menuadd(int hMenu, const char* title); PLUG_IMPEXP bool _plugin_menuaddentry(int hMenu, int hEntry, const char* title); PLUG_IMPEXP bool _plugin_menuaddseparator(int hMenu); PLUG_IMPEXP bool _plugin_menuclear(int hMenu); PLUG_IMPEXP void _plugin_menuseticon(int hMenu, const ICONDATA* icon); PLUG_IMPEXP void _plugin_menuentryseticon(int pluginHandle, int hEntry, const ICONDATA* icon); PLUG_IMPEXP void _plugin_menuentrysetchecked(int pluginHandle, int hEntry, bool checked); PLUG_IMPEXP void _plugin_menusetvisible(int pluginHandle, int hMenu, bool visible); PLUG_IMPEXP void _plugin_menuentrysetvisible(int pluginHandle, int hEntry, bool visible); PLUG_IMPEXP void _plugin_menusetname(int pluginHandle, int hMenu, const char* name); PLUG_IMPEXP void _plugin_menuentrysetname(int pluginHandle, int hEntry, const char* name); PLUG_IMPEXP void _plugin_menuentrysethotkey(int pluginHandle, int hEntry, const char* hotkey); PLUG_IMPEXP bool _plugin_menuremove(int hMenu); PLUG_IMPEXP bool _plugin_menuentryremove(int pluginHandle, int hEntry); PLUG_IMPEXP void _plugin_startscript(CBPLUGINSCRIPT cbScript); PLUG_IMPEXP bool _plugin_waituntilpaused(); PLUG_IMPEXP bool _plugin_registerexprfunction(int pluginHandle, const char* name, int argc, CBPLUGINEXPRFUNCTION cbFunction, void* userdata); PLUG_IMPEXP bool _plugin_registerexprfunctionex(int pluginHandle, const char* name, const ValueType & returnType, const ValueType* argTypes, size_t argCount, CBPLUGINEXPRFUNCTIONEX cbFunction, void* userdata); PLUG_IMPEXP bool _plugin_unregisterexprfunction(int pluginHandle, const char* name); PLUG_IMPEXP bool _plugin_unload(const char* pluginName); PLUG_IMPEXP bool _plugin_load(const char* pluginName); PLUG_IMPEXP duint _plugin_hash(const void* data, duint size); PLUG_IMPEXP bool _plugin_registerformatfunction(int pluginHandle, const char* type, CBPLUGINFORMATFUNCTION cbFunction, void* userdata); PLUG_IMPEXP bool _plugin_unregisterformatfunction(int pluginHandle, const char* type); #ifdef __cplusplus } #endif #pragma pack(pop) #endif // _PLUGINS_H
C/C++
x64dbg-development/src/dbg/_plugin_types.h
#ifndef _PLUGIN_DATA_H #define _PLUGIN_DATA_H #ifdef BUILD_DBG #include "_global.h" #include "jansson/jansson.h" #pragma warning(push) #pragma warning(disable:4091) #include <dbghelp.h> #pragma warning(pop) #else #ifdef __GNUC__ #include "dbghelp/dbghelp.h" #else #pragma warning(push) #pragma warning(disable:4091) #include <dbghelp.h> #pragma warning(pop) #endif // __GNUC__ #ifndef deflen #define deflen 1024 #endif // deflen #include "bridgemain.h" #include "_dbgfunctions.h" #include "jansson/jansson.h" #endif // BUILD_DBG #endif // _PLUGIN_DATA_H
C/C++
x64dbg-development/src/dbg/_scriptapi.h
#ifndef _SCRIPT_API_H #define _SCRIPT_API_H #include "_plugins.h" #define SCRIPT_EXPORT PLUG_IMPEXP #endif //_SCRIPT_API_H
C++
x64dbg-development/src/dbg/_scriptapi_argument.cpp
#include "_scriptapi_argument.h" #include "_scriptapi_module.h" #include "argument.h" SCRIPT_EXPORT bool Script::Argument::Add(duint start, duint end, bool manual, duint instructionCount) { return ArgumentAdd(start, end, manual, instructionCount); } SCRIPT_EXPORT bool Script::Argument::Add(const ArgumentInfo* info) { if(!info) return false; auto base = Module::BaseFromName(info->mod); if(!base) return false; return Add(base + info->rvaStart, base + info->rvaEnd, info->manual, info->instructioncount); } SCRIPT_EXPORT bool Script::Argument::Get(duint addr, duint* start, duint* end, duint* instructionCount) { return ArgumentGet(addr, start, end, instructionCount); } SCRIPT_EXPORT bool Script::Argument::GetInfo(duint addr, ArgumentInfo* info) { ARGUMENTSINFO argument; if(!ArgumentGetInfo(addr, argument)) return false; if(info) { strcpy_s(info->mod, argument.mod().c_str()); info->rvaStart = argument.start; info->rvaEnd = argument.end; info->manual = argument.manual; info->instructioncount = argument.instructioncount; } return true; } SCRIPT_EXPORT bool Script::Argument::Overlaps(duint start, duint end) { return ArgumentOverlaps(start, end); } SCRIPT_EXPORT bool Script::Argument::Delete(duint address) { return ArgumentDelete(address); } SCRIPT_EXPORT void Script::Argument::DeleteRange(duint start, duint end, bool deleteManual) { ArgumentDelRange(start, end, deleteManual); } SCRIPT_EXPORT void Script::Argument::Clear() { ArgumentClear(); } SCRIPT_EXPORT bool Script::Argument::GetList(ListOf(ArgumentInfo) list) { std::vector<ARGUMENTSINFO> argumentList; ArgumentGetList(argumentList); std::vector<ArgumentInfo> argumentScriptList; argumentScriptList.reserve(argumentList.size()); for(const auto & argument : argumentList) { ArgumentInfo scriptArgument; strcpy_s(scriptArgument.mod, argument.mod().c_str()); scriptArgument.rvaStart = argument.start; scriptArgument.rvaEnd = argument.end; scriptArgument.manual = argument.manual; scriptArgument.instructioncount = argument.instructioncount; argumentScriptList.push_back(scriptArgument); } return BridgeList<ArgumentInfo>::CopyData(list, argumentScriptList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_argument.h
#ifndef _SCRIPTAPI_ARGUMENT_H #define _SCRIPTAPI_ARGUMENT_H #include "_scriptapi.h" namespace Script { namespace Argument { struct ArgumentInfo { char mod[MAX_MODULE_SIZE]; duint rvaStart; duint rvaEnd; bool manual; duint instructioncount; }; SCRIPT_EXPORT bool Add(duint start, duint end, bool manual, duint instructionCount = 0); SCRIPT_EXPORT bool Add(const ArgumentInfo* info); SCRIPT_EXPORT bool Get(duint addr, duint* start = nullptr, duint* end = nullptr, duint* instructionCount = nullptr); SCRIPT_EXPORT bool GetInfo(duint addr, ArgumentInfo* info); SCRIPT_EXPORT bool Overlaps(duint start, duint end); SCRIPT_EXPORT bool Delete(duint address); SCRIPT_EXPORT void DeleteRange(duint start, duint end, bool deleteManual = false); SCRIPT_EXPORT void Clear(); SCRIPT_EXPORT bool GetList(ListOf(ArgumentInfo) list); //caller has the responsibility to free the list }; //Argument }; //Script #endif //_SCRIPTAPI_ARGUMENT_H
C++
x64dbg-development/src/dbg/_scriptapi_assembler.cpp
#include "_scriptapi_assembler.h" #include "assemble.h" SCRIPT_EXPORT bool Script::Assembler::Assemble(duint addr, unsigned char* dest, int* size, const char* instruction) { return assemble(addr, dest, size, instruction, nullptr); } SCRIPT_EXPORT bool Script::Assembler::AssembleEx(duint addr, unsigned char* dest, int* size, const char* instruction, char* error) { return assemble(addr, dest, size, instruction, error); } SCRIPT_EXPORT bool Script::Assembler::AssembleMem(duint addr, const char* instruction) { return assembleat(addr, instruction, nullptr, nullptr, false); } SCRIPT_EXPORT bool Script::Assembler::AssembleMemEx(duint addr, const char* instruction, int* size, char* error, bool fillnop) { return assembleat(addr, instruction, size, error, fillnop); }
C/C++
x64dbg-development/src/dbg/_scriptapi_assembler.h
#ifndef _SCRIPTAPI_ASSEMBLER_H #define _SCRIPTAPI_ASSEMBLER_H #include "_scriptapi.h" namespace Script { namespace Assembler { SCRIPT_EXPORT bool Assemble(duint addr, unsigned char* dest, int* size, const char* instruction); //dest[16] SCRIPT_EXPORT bool AssembleEx(duint addr, unsigned char* dest, int* size, const char* instruction, char* error); //dest[16], error[MAX_ERROR_SIZE] SCRIPT_EXPORT bool AssembleMem(duint addr, const char* instruction); SCRIPT_EXPORT bool AssembleMemEx(duint addr, const char* instruction, int* size, char* error, bool fillnop); //error[MAX_ERROR_SIZE] }; //Assembler }; //Script #endif //_SCRIPTAPI_ASSEMBLER_H
C++
x64dbg-development/src/dbg/_scriptapi_bookmark.cpp
#include "_scriptapi_bookmark.h" #include "_scriptapi_module.h" #include "bookmark.h" SCRIPT_EXPORT bool Script::Bookmark::Set(duint addr, bool manual) { return BookmarkSet(addr, manual); } SCRIPT_EXPORT bool Script::Bookmark::Set(const BookmarkInfo* info) { if(!info) return false; auto base = Module::BaseFromName(info->mod); if(!base) return false; return Set(base + info->rva, info->manual); } SCRIPT_EXPORT bool Script::Bookmark::Get(duint addr) { return BookmarkGet(addr); } SCRIPT_EXPORT bool Script::Bookmark::GetInfo(duint addr, BookmarkInfo* info) { BOOKMARKSINFO comment; if(!BookmarkGetInfo(addr, &comment)) return false; if(info) { strcpy_s(info->mod, comment.mod().c_str()); info->rva = comment.addr; info->manual = comment.manual; } return true; } SCRIPT_EXPORT bool Script::Bookmark::Delete(duint addr) { return BookmarkDelete(addr); } SCRIPT_EXPORT void Script::Bookmark::DeleteRange(duint start, duint end) { BookmarkDelRange(start, end, false); } SCRIPT_EXPORT void Script::Bookmark::Clear() { BookmarkClear(); } SCRIPT_EXPORT bool Script::Bookmark::GetList(ListOf(BookmarkInfo) list) { std::vector<BOOKMARKSINFO> bookmarkList; BookmarkGetList(bookmarkList); std::vector<BookmarkInfo> bookmarkScriptList; bookmarkScriptList.reserve(bookmarkList.size()); for(const auto & bookmark : bookmarkList) { BookmarkInfo scriptComment; strcpy_s(scriptComment.mod, bookmark.mod().c_str()); scriptComment.rva = bookmark.addr; scriptComment.manual = bookmark.manual; bookmarkScriptList.push_back(scriptComment); } return BridgeList<BookmarkInfo>::CopyData(list, bookmarkScriptList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_bookmark.h
#ifndef _SCRIPTAPI_BOOKMARK_H #define _SCRIPTAPI_BOOKMARK_H #include "_scriptapi.h" namespace Script { namespace Bookmark { struct BookmarkInfo { char mod[MAX_MODULE_SIZE]; duint rva; bool manual; }; SCRIPT_EXPORT bool Set(duint addr, bool manual = false); SCRIPT_EXPORT bool Set(const BookmarkInfo* info); SCRIPT_EXPORT bool Get(duint addr); SCRIPT_EXPORT bool GetInfo(duint addr, BookmarkInfo* info); SCRIPT_EXPORT bool Delete(duint addr); SCRIPT_EXPORT void DeleteRange(duint start, duint end); SCRIPT_EXPORT void Clear(); SCRIPT_EXPORT bool GetList(ListOf(BookmarkInfo) list); //caller has the responsibility to free the list }; //Bookmark }; //Script #endif //_SCRIPTAPI_BOOKMARK_H
C++
x64dbg-development/src/dbg/_scriptapi_comment.cpp
#include "_scriptapi_comment.h" #include "_scriptapi_module.h" #include "comment.h" SCRIPT_EXPORT bool Script::Comment::Set(duint addr, const char* text, bool manual) { return CommentSet(addr, text, manual); } SCRIPT_EXPORT bool Script::Comment::Set(const CommentInfo* info) { if(!info) return false; auto base = Module::BaseFromName(info->mod); if(!base) return false; return Set(base + info->rva, info->text, info->manual); } SCRIPT_EXPORT bool Script::Comment::Get(duint addr, char* text) { return CommentGet(addr, text); } SCRIPT_EXPORT bool Script::Comment::GetInfo(duint addr, CommentInfo* info) { COMMENTSINFO comment; if(!CommentGetInfo(addr, &comment)) return false; if(info) { strcpy_s(info->mod, comment.mod().c_str()); info->rva = comment.addr; strcpy_s(info->text, comment.text.c_str()); info->manual = comment.manual; } return true; } SCRIPT_EXPORT bool Script::Comment::Delete(duint addr) { return CommentDelete(addr); } SCRIPT_EXPORT void Script::Comment::DeleteRange(duint start, duint end) { CommentDelRange(start, end, false); } SCRIPT_EXPORT void Script::Comment::Clear() { CommentClear(); } SCRIPT_EXPORT bool Script::Comment::GetList(ListOf(CommentInfo) list) { std::vector<COMMENTSINFO> commentList; CommentGetList(commentList); std::vector<CommentInfo> commentScriptList; commentScriptList.reserve(commentList.size()); for(const auto & comment : commentList) { CommentInfo scriptComment; strcpy_s(scriptComment.mod, comment.mod().c_str()); scriptComment.rva = comment.addr; strcpy_s(scriptComment.text, comment.text.c_str()); scriptComment.manual = comment.manual; commentScriptList.push_back(scriptComment); } return BridgeList<CommentInfo>::CopyData(list, commentScriptList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_comment.h
#ifndef _SCRIPTAPI_COMMENT_H #define _SCRIPTAPI_COMMENT_H #include "_scriptapi.h" namespace Script { namespace Comment { struct CommentInfo { char mod[MAX_MODULE_SIZE]; duint rva; char text[MAX_LABEL_SIZE]; bool manual; }; SCRIPT_EXPORT bool Set(duint addr, const char* text, bool manual = false); SCRIPT_EXPORT bool Set(const CommentInfo* info); SCRIPT_EXPORT bool Get(duint addr, char* text); //text[MAX_COMMENT_SIZE] SCRIPT_EXPORT bool GetInfo(duint addr, CommentInfo* info); SCRIPT_EXPORT bool Delete(duint addr); SCRIPT_EXPORT void DeleteRange(duint start, duint end); SCRIPT_EXPORT void Clear(); SCRIPT_EXPORT bool GetList(ListOf(CommentInfo) list); //caller has the responsibility to free the list }; //Comment }; //Script #endif //_SCRIPTAPI_COMMENT_H
C++
x64dbg-development/src/dbg/_scriptapi_debug.cpp
#include "_scriptapi_debug.h" SCRIPT_EXPORT void Script::Debug::Wait() { _plugin_waituntilpaused(); } SCRIPT_EXPORT void Script::Debug::Run() { if(DbgCmdExecDirect("run")) Wait(); } SCRIPT_EXPORT void Script::Debug::Pause() { if(DbgCmdExecDirect("pause")) Wait(); } SCRIPT_EXPORT void Script::Debug::Stop() { if(DbgCmdExecDirect("StopDebug")) Wait(); } SCRIPT_EXPORT void Script::Debug::StepIn() { if(DbgCmdExecDirect("StepInto")) Wait(); } SCRIPT_EXPORT void Script::Debug::StepOver() { if(DbgCmdExecDirect("StepOver")) Wait(); } SCRIPT_EXPORT void Script::Debug::StepOut() { if(DbgCmdExecDirect("StepOut")) Wait(); } SCRIPT_EXPORT bool Script::Debug::SetBreakpoint(duint address) { char command[128] = ""; sprintf_s(command, "bp %p", address); return DbgCmdExecDirect(command); } SCRIPT_EXPORT bool Script::Debug::DeleteBreakpoint(duint address) { char command[128] = ""; sprintf_s(command, "bc %p", address); return DbgCmdExecDirect(command); } SCRIPT_EXPORT bool Script::Debug::DisableBreakpoint(duint address) { char command[128] = ""; sprintf_s(command, "bd %p", address); return DbgCmdExecDirect(command); } SCRIPT_EXPORT bool Script::Debug::SetHardwareBreakpoint(duint address, HardwareType type) { char command[128] = ""; const char* types[] = { "rw", "w", "x" }; sprintf_s(command, "bphws %p, %s", address, types[type]); return DbgCmdExecDirect(command); } SCRIPT_EXPORT bool Script::Debug::DeleteHardwareBreakpoint(duint address) { char command[128] = ""; sprintf_s(command, "bphwc %p", address); return DbgCmdExecDirect(command); }
C/C++
x64dbg-development/src/dbg/_scriptapi_debug.h
#ifndef _SCRIPTAPI_DEBUG_H #define _SCRIPTAPI_DEBUG_H #include "_scriptapi.h" namespace Script { namespace Debug { enum HardwareType { HardwareAccess, HardwareWrite, HardwareExecute }; SCRIPT_EXPORT void Wait(); SCRIPT_EXPORT void Run(); SCRIPT_EXPORT void Pause(); SCRIPT_EXPORT void Stop(); SCRIPT_EXPORT void StepIn(); SCRIPT_EXPORT void StepOver(); SCRIPT_EXPORT void StepOut(); SCRIPT_EXPORT bool SetBreakpoint(duint address); SCRIPT_EXPORT bool DeleteBreakpoint(duint address); SCRIPT_EXPORT bool DisableBreakpoint(duint address); SCRIPT_EXPORT bool SetHardwareBreakpoint(duint address, HardwareType type = HardwareExecute); SCRIPT_EXPORT bool DeleteHardwareBreakpoint(duint address); }; //Debug }; //Script #endif //_SCRIPTAPI_DEBUG_H
C++
x64dbg-development/src/dbg/_scriptapi_flag.cpp
#include "_scriptapi_flag.h" #include "value.h" static const char* flagTable[] = { "_ZF", "_OF", "_CF", "_PF", "_SF", "_TF", "_AF", "_DF", "_IF" }; SCRIPT_EXPORT bool Script::Flag::Get(FlagEnum flag) { duint value; return valfromstring(flagTable[flag], &value) ? !!value : false; } SCRIPT_EXPORT bool Script::Flag::Set(FlagEnum flag, bool value) { return setflag(flagTable[flag], value); } SCRIPT_EXPORT bool Script::Flag::GetZF() { return Get(ZF); } SCRIPT_EXPORT bool Script::Flag::SetZF(bool value) { return Set(ZF, value); } SCRIPT_EXPORT bool Script::Flag::GetOF() { return Get(OF); } SCRIPT_EXPORT bool Script::Flag::SetOF(bool value) { return Set(OF, value); } SCRIPT_EXPORT bool Script::Flag::GetCF() { return Get(CF); } SCRIPT_EXPORT bool Script::Flag::SetCF(bool value) { return Set(CF, value); } SCRIPT_EXPORT bool Script::Flag::GetPF() { return Get(PF); } SCRIPT_EXPORT bool Script::Flag::SetPF(bool value) { return Set(PF, value); } SCRIPT_EXPORT bool Script::Flag::GetSF() { return Get(SF); } SCRIPT_EXPORT bool Script::Flag::SetSF(bool value) { return Set(SF, value); } SCRIPT_EXPORT bool Script::Flag::GetTF() { return Get(TF); } SCRIPT_EXPORT bool Script::Flag::SetTF(bool value) { return Set(TF, value); } SCRIPT_EXPORT bool Script::Flag::GetAF() { return Get(AF); } SCRIPT_EXPORT bool Script::Flag::SetAF(bool value) { return Set(AF, value); } SCRIPT_EXPORT bool Script::Flag::GetDF() { return Get(DF); } SCRIPT_EXPORT bool Script::Flag::SetDF(bool value) { return Set(DF, value); } SCRIPT_EXPORT bool Script::Flag::GetIF() { return Get(IF); } SCRIPT_EXPORT bool Script::Flag::SetIF(bool value) { return Set(IF, value); }
C/C++
x64dbg-development/src/dbg/_scriptapi_flag.h
#ifndef _SCRIPTAPI_FLAG_H #define _SCRIPTAPI_FLAG_H #include "_scriptapi.h" namespace Script { namespace Flag { enum FlagEnum { ZF, OF, CF, PF, SF, TF, AF, DF, IF }; SCRIPT_EXPORT bool Get(FlagEnum flag); SCRIPT_EXPORT bool Set(FlagEnum flag, bool value); SCRIPT_EXPORT bool GetZF(); SCRIPT_EXPORT bool SetZF(bool value); SCRIPT_EXPORT bool GetOF(); SCRIPT_EXPORT bool SetOF(bool value); SCRIPT_EXPORT bool GetCF(); SCRIPT_EXPORT bool SetCF(bool value); SCRIPT_EXPORT bool GetPF(); SCRIPT_EXPORT bool SetPF(bool value); SCRIPT_EXPORT bool GetSF(); SCRIPT_EXPORT bool SetSF(bool value); SCRIPT_EXPORT bool GetTF(); SCRIPT_EXPORT bool SetTF(bool value); SCRIPT_EXPORT bool GetAF(); SCRIPT_EXPORT bool SetAF(bool value); SCRIPT_EXPORT bool GetDF(); SCRIPT_EXPORT bool SetDF(bool value); SCRIPT_EXPORT bool GetIF(); SCRIPT_EXPORT bool SetIF(bool value); }; }; #endif //_SCRIPTAPI_FLAG_H
C++
x64dbg-development/src/dbg/_scriptapi_function.cpp
#include "_scriptapi_function.h" #include "_scriptapi_module.h" #include "function.h" SCRIPT_EXPORT bool Script::Function::Add(duint start, duint end, bool manual, duint instructionCount) { return FunctionAdd(start, end, manual, instructionCount); } SCRIPT_EXPORT bool Script::Function::Add(const FunctionInfo* info) { if(!info) return false; auto base = Module::BaseFromName(info->mod); if(!base) return false; return Add(base + info->rvaStart, base + info->rvaEnd, info->manual, info->instructioncount); } SCRIPT_EXPORT bool Script::Function::Get(duint addr, duint* start, duint* end, duint* instructionCount) { return FunctionGet(addr, start, end, instructionCount); } SCRIPT_EXPORT bool Script::Function::GetInfo(duint addr, FunctionInfo* info) { FUNCTIONSINFO function; if(!FunctionGetInfo(addr, function)) return false; if(info) { strcpy_s(info->mod, function.mod().c_str()); info->rvaStart = function.start; info->rvaEnd = function.end; info->manual = function.manual; info->instructioncount = function.instructioncount; } return true; } SCRIPT_EXPORT bool Script::Function::Overlaps(duint start, duint end) { return FunctionOverlaps(start, end); } SCRIPT_EXPORT bool Script::Function::Delete(duint address) { return FunctionDelete(address); } SCRIPT_EXPORT void Script::Function::DeleteRange(duint start, duint end, bool deleteManual) { FunctionDelRange(start, end, deleteManual); } SCRIPT_EXPORT void Script::Function::DeleteRange(duint start, duint end) { DeleteRange(start, end, false); } SCRIPT_EXPORT void Script::Function::Clear() { FunctionClear(); } SCRIPT_EXPORT bool Script::Function::GetList(ListOf(FunctionInfo) list) { std::vector<FUNCTIONSINFO> functionList; FunctionGetList(functionList); std::vector<FunctionInfo> functionScriptList; functionScriptList.reserve(functionList.size()); for(const auto & function : functionList) { FunctionInfo scriptFunction; strcpy_s(scriptFunction.mod, function.mod().c_str()); scriptFunction.rvaStart = function.start; scriptFunction.rvaEnd = function.end; scriptFunction.manual = function.manual; scriptFunction.instructioncount = function.instructioncount; functionScriptList.push_back(scriptFunction); } return BridgeList<FunctionInfo>::CopyData(list, functionScriptList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_function.h
#ifndef _SCRIPTAPI_FUNCTION_H #define _SCRIPTAPI_FUNCTION_H #include "_scriptapi.h" namespace Script { namespace Function { struct FunctionInfo { char mod[MAX_MODULE_SIZE]; duint rvaStart; duint rvaEnd; bool manual; duint instructioncount; }; SCRIPT_EXPORT bool Add(duint start, duint end, bool manual, duint instructionCount = 0); SCRIPT_EXPORT bool Add(const FunctionInfo* info); SCRIPT_EXPORT bool Get(duint addr, duint* start = nullptr, duint* end = nullptr, duint* instructionCount = nullptr); SCRIPT_EXPORT bool GetInfo(duint addr, FunctionInfo* info); SCRIPT_EXPORT bool Overlaps(duint start, duint end); SCRIPT_EXPORT bool Delete(duint address); SCRIPT_EXPORT void DeleteRange(duint start, duint end, bool deleteManual); SCRIPT_EXPORT void DeleteRange(duint start, duint end); SCRIPT_EXPORT void Clear(); SCRIPT_EXPORT bool GetList(ListOf(FunctionInfo) list); //caller has the responsibility to free the list }; //Function }; //Script #endif //_SCRIPTAPI_FUNCTION_H
C++
x64dbg-development/src/dbg/_scriptapi_gui.cpp
#include "_scriptapi_gui.h" #include "_scriptapi_misc.h" SCRIPT_EXPORT bool Script::Gui::Disassembly::SelectionGet(duint* start, duint* end) { return Gui::SelectionGet(DisassemblyWindow, start, end); } SCRIPT_EXPORT bool Script::Gui::Disassembly::SelectionSet(duint start, duint end) { return Gui::SelectionSet(DisassemblyWindow, start, end); } SCRIPT_EXPORT duint Script::Gui::Disassembly::SelectionGetStart() { return Gui::SelectionGetStart(DisassemblyWindow); } SCRIPT_EXPORT duint Script::Gui::Disassembly::SelectionGetEnd() { return Gui::SelectionGetEnd(DisassemblyWindow); } SCRIPT_EXPORT bool Script::Gui::Dump::SelectionGet(duint* start, duint* end) { return Gui::SelectionGet(DumpWindow, start, end); } SCRIPT_EXPORT bool Script::Gui::Dump::SelectionSet(duint start, duint end) { return Gui::SelectionSet(DumpWindow, start, end); } SCRIPT_EXPORT duint Script::Gui::Dump::SelectionGetStart() { return Gui::SelectionGetStart(DumpWindow); } SCRIPT_EXPORT duint Script::Gui::Dump::SelectionGetEnd() { return Gui::SelectionGetEnd(DumpWindow); } SCRIPT_EXPORT bool Script::Gui::Stack::SelectionGet(duint* start, duint* end) { return Gui::SelectionGet(StackWindow, start, end); } SCRIPT_EXPORT bool Script::Gui::Stack::SelectionSet(duint start, duint end) { return Gui::SelectionSet(StackWindow, start, end); } SCRIPT_EXPORT duint Script::Gui::Stack::SelectionGetStart() { return Gui::SelectionGetStart(StackWindow); } SCRIPT_EXPORT duint Script::Gui::Stack::SelectionGetEnd() { return Gui::SelectionGetEnd(StackWindow); } SCRIPT_EXPORT duint Script::Gui::Graph::SelectionGetStart() { return SelectionGetStart(GraphWindow); } SCRIPT_EXPORT duint Script::Gui::MemMap::SelectionGetStart() { return SelectionGetStart(MemMapWindow); } SCRIPT_EXPORT duint Script::Gui::SymMod::SelectionGetStart() { return SelectionGetStart(SymModWindow); } static inline GUISELECTIONTYPE windowToBridge(Script::Gui::Window window) { switch(window) { case Script::Gui::DisassemblyWindow: return GUI_DISASSEMBLY; case Script::Gui::DumpWindow: return GUI_DUMP; case Script::Gui::StackWindow: return GUI_STACK; case Script::Gui::GraphWindow: return GUI_GRAPH; case Script::Gui::MemMapWindow: return GUI_MEMMAP; case Script::Gui::SymModWindow: return GUI_SYMMOD; default: return GUI_DISASSEMBLY; } } SCRIPT_EXPORT bool Script::Gui::SelectionGet(Script::Gui::Window window, duint* start, duint* end) { SELECTIONDATA selection; if(!GuiSelectionGet(windowToBridge(window), &selection)) return false; if(start) *start = selection.start; if(end) *end = selection.end; return true; } SCRIPT_EXPORT bool Script::Gui::SelectionSet(Script::Gui::Window window, duint start, duint end) { SELECTIONDATA selection; selection.start = start; selection.end = end; return GuiSelectionSet(windowToBridge(window), &selection); } SCRIPT_EXPORT duint Script::Gui::SelectionGetStart(Script::Gui::Window window) { duint start; return Gui::SelectionGet(window, &start, nullptr) ? start : 0; } SCRIPT_EXPORT duint Script::Gui::SelectionGetEnd(Script::Gui::Window window) { duint end; return Gui::SelectionGet(window, nullptr, &end) ? end : 0; } SCRIPT_EXPORT void Script::Gui::Message(const char* message) { GuiScriptMessage(message); } SCRIPT_EXPORT bool Script::Gui::MessageYesNo(const char* message) { return !!GuiScriptMsgyn(message); } SCRIPT_EXPORT bool Script::Gui::InputLine(const char* title, char* text) { return GuiGetLineWindow(title, text); } SCRIPT_EXPORT bool Script::Gui::InputValue(const char* title, duint* value) { Memory<char*> line(GUI_MAX_LINE_SIZE); if(!GuiGetLineWindow(title, line())) return false; return Misc::ParseExpression(line(), value); } SCRIPT_EXPORT void Script::Gui::Refresh() { GuiUpdateAllViews(); } SCRIPT_EXPORT void Script::Gui::AddQWidgetTab(void* qWidget) { GuiAddQWidgetTab(qWidget); } SCRIPT_EXPORT void Script::Gui::ShowQWidgetTab(void* qWidget) { GuiShowQWidgetTab(qWidget); } SCRIPT_EXPORT void Script::Gui::CloseQWidgetTab(void* qWidget) { GuiCloseQWidgetTab(qWidget); }
C/C++
x64dbg-development/src/dbg/_scriptapi_gui.h
#ifndef _SCRIPTAPI_GUI_H #define _SCRIPTAPI_GUI_H #include "_scriptapi.h" namespace Script { namespace Gui { namespace Disassembly { SCRIPT_EXPORT bool SelectionGet(duint* start, duint* end); SCRIPT_EXPORT bool SelectionSet(duint start, duint end); SCRIPT_EXPORT duint SelectionGetStart(); SCRIPT_EXPORT duint SelectionGetEnd(); }; //Disassembly namespace Dump { SCRIPT_EXPORT bool SelectionGet(duint* start, duint* end); SCRIPT_EXPORT bool SelectionSet(duint start, duint end); SCRIPT_EXPORT duint SelectionGetStart(); SCRIPT_EXPORT duint SelectionGetEnd(); }; //Dump namespace Stack { SCRIPT_EXPORT bool SelectionGet(duint* start, duint* end); SCRIPT_EXPORT bool SelectionSet(duint start, duint end); SCRIPT_EXPORT duint SelectionGetStart(); SCRIPT_EXPORT duint SelectionGetEnd(); }; //Stack namespace Graph { SCRIPT_EXPORT duint SelectionGetStart(); }; //Graph namespace MemMap { SCRIPT_EXPORT duint SelectionGetStart(); }; //MemoryMap namespace SymMod { SCRIPT_EXPORT duint SelectionGetStart(); }; //SymMod }; //Gui namespace Gui { enum Window { DisassemblyWindow, DumpWindow, StackWindow, GraphWindow, MemMapWindow, SymModWindow }; SCRIPT_EXPORT bool SelectionGet(Window window, duint* start, duint* end); SCRIPT_EXPORT bool SelectionSet(Window window, duint start, duint end); SCRIPT_EXPORT duint SelectionGetStart(Window window); SCRIPT_EXPORT duint SelectionGetEnd(Window window); SCRIPT_EXPORT void Message(const char* message); SCRIPT_EXPORT bool MessageYesNo(const char* message); SCRIPT_EXPORT bool InputLine(const char* title, char* text); //text[GUI_MAX_LINE_SIZE] SCRIPT_EXPORT bool InputValue(const char* title, duint* value); SCRIPT_EXPORT void Refresh(); SCRIPT_EXPORT void AddQWidgetTab(void* qWidget); SCRIPT_EXPORT void ShowQWidgetTab(void* qWidget); SCRIPT_EXPORT void CloseQWidgetTab(void* qWidget); }; //Gui }; //Script #endif //_SCRIPTAPI_GUI_H
C++
x64dbg-development/src/dbg/_scriptapi_label.cpp
#include "_scriptapi_label.h" #include "_scriptapi_module.h" #include "label.h" SCRIPT_EXPORT bool Script::Label::Set(duint addr, const char* text, bool manual) { return LabelSet(addr, text, manual); } SCRIPT_EXPORT bool Script::Label::Set(duint addr, const char* text, bool manual, bool temporary) { return LabelSet(addr, text, manual, temporary); } SCRIPT_EXPORT bool Script::Label::Set(const LabelInfo* info) { if(!info) return false; auto base = Module::BaseFromName(info->mod); if(!base) return false; return Set(base + info->rva, info->text, info->manual, false); } SCRIPT_EXPORT bool Script::Label::FromString(const char* label, duint* addr) { return LabelFromString(label, addr); } SCRIPT_EXPORT bool Script::Label::Get(duint addr, char* text) { return LabelGet(addr, text); } SCRIPT_EXPORT bool Script::Label::IsTemporary(duint addr) { return LabelIsTemporary(addr); } SCRIPT_EXPORT bool Script::Label::GetInfo(duint addr, LabelInfo* info) { LABELSINFO label; if(!LabelGetInfo(addr, &label)) return false; if(info) { strcpy_s(info->mod, label.mod().c_str()); info->rva = label.addr; strcpy_s(info->text, label.text.c_str()); info->manual = label.manual; } return true; } SCRIPT_EXPORT bool Script::Label::Delete(duint addr) { return LabelDelete(addr); } SCRIPT_EXPORT void Script::Label::DeleteRange(duint start, duint end) { LabelDelRange(start, end, false); } SCRIPT_EXPORT void Script::Label::Clear() { LabelClear(); } SCRIPT_EXPORT bool Script::Label::GetList(ListOf(LabelInfo) list) { std::vector<LABELSINFO> labelList; LabelGetList(labelList); std::vector<LabelInfo> labelScriptList; labelScriptList.reserve(labelList.size()); for(const auto & label : labelList) { LabelInfo scriptLabel; strcpy_s(scriptLabel.mod, label.mod().c_str()); scriptLabel.rva = label.addr; strcpy_s(scriptLabel.text, label.text.c_str()); scriptLabel.manual = label.manual; labelScriptList.push_back(scriptLabel); } return BridgeList<LabelInfo>::CopyData(list, labelScriptList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_label.h
#ifndef _SCRIPTAPI_LABEL_H #define _SCRIPTAPI_LABEL_H #include "_scriptapi.h" namespace Script { namespace Label { struct LabelInfo { char mod[MAX_MODULE_SIZE]; duint rva; char text[MAX_LABEL_SIZE]; bool manual; }; SCRIPT_EXPORT bool Set(duint addr, const char* text, bool manual = false); SCRIPT_EXPORT bool Set(duint addr, const char* text, bool manual = false, bool temporary = false); SCRIPT_EXPORT bool Set(const LabelInfo* info); SCRIPT_EXPORT bool FromString(const char* label, duint* addr); SCRIPT_EXPORT bool Get(duint addr, char* text); //text[MAX_LABEL_SIZE] SCRIPT_EXPORT bool IsTemporary(duint addr); SCRIPT_EXPORT bool GetInfo(duint addr, LabelInfo* info); SCRIPT_EXPORT bool Delete(duint addr); SCRIPT_EXPORT void DeleteRange(duint start, duint end); SCRIPT_EXPORT void Clear(); SCRIPT_EXPORT bool GetList(ListOf(LabelInfo) list); //caller has the responsibility to free the list }; //Label }; //Script #endif //_SCRIPTAPI_LABEL_H
C++
x64dbg-development/src/dbg/_scriptapi_memory.cpp
#include "_scriptapi_memory.h" #include "memory.h" #include "threading.h" SCRIPT_EXPORT bool Script::Memory::Read(duint addr, void* data, duint size, duint* sizeRead) { return MemRead(addr, data, size, sizeRead); } SCRIPT_EXPORT bool Script::Memory::Write(duint addr, const void* data, duint size, duint* sizeWritten) { return MemWrite(addr, data, size, sizeWritten); } SCRIPT_EXPORT bool Script::Memory::IsValidPtr(duint addr) { return MemIsValidReadPtr(addr); } SCRIPT_EXPORT duint Script::Memory::RemoteAlloc(duint addr, duint size) { return MemAllocRemote(addr, size); } SCRIPT_EXPORT bool Script::Memory::RemoteFree(duint addr) { return MemFreeRemote(addr); } SCRIPT_EXPORT unsigned int Script::Memory::GetProtect(duint addr, bool reserved, bool cache) { unsigned int prot = 0; if(!MemGetProtect(addr, reserved, cache, &prot)) return 0; return prot; } SCRIPT_EXPORT bool Script::Memory::SetProtect(duint addr, unsigned int protect, duint size) { return MemSetProtect(addr, protect, size); } SCRIPT_EXPORT duint Script::Memory::GetBase(duint addr, bool reserved, bool cache) { return MemFindBaseAddr(addr, nullptr, !cache, reserved); } SCRIPT_EXPORT duint Script::Memory::GetSize(duint addr, bool reserved, bool cache) { duint size = 0; MemFindBaseAddr(addr, &size, !cache, reserved); return size; } SCRIPT_EXPORT unsigned char Script::Memory::ReadByte(duint addr) { unsigned char data = 0; Read(addr, &data, sizeof(data), nullptr); return data; } SCRIPT_EXPORT bool Script::Memory::WriteByte(duint addr, unsigned char data) { return Write(addr, &data, sizeof(data), nullptr); } SCRIPT_EXPORT unsigned short Script::Memory::ReadWord(duint addr) { unsigned short data = 0; Read(addr, &data, sizeof(data), nullptr); return data; } SCRIPT_EXPORT bool Script::Memory::WriteWord(duint addr, unsigned short data) { return Write(addr, &data, sizeof(data), nullptr); } SCRIPT_EXPORT unsigned int Script::Memory::ReadDword(duint addr) { unsigned int data = 0; Read(addr, &data, sizeof(data), nullptr); return data; } SCRIPT_EXPORT bool Script::Memory::WriteDword(duint addr, unsigned int data) { return Write(addr, &data, sizeof(data), nullptr); } SCRIPT_EXPORT unsigned long long Script::Memory::ReadQword(duint addr) { unsigned long long data = 0; Read(addr, &data, sizeof(data), nullptr); return data; } SCRIPT_EXPORT bool Script::Memory::WriteQword(duint addr, unsigned long long data) { return Write(addr, &data, sizeof(data), nullptr); } SCRIPT_EXPORT duint Script::Memory::ReadPtr(duint addr) { duint data = 0; Read(addr, &data, sizeof(data), nullptr); return data; } SCRIPT_EXPORT bool Script::Memory::WritePtr(duint addr, duint data) { return Write(addr, &data, sizeof(data), nullptr); }
C/C++
x64dbg-development/src/dbg/_scriptapi_memory.h
#ifndef _SCRIPTAPI_MEMORY_H #define _SCRIPTAPI_MEMORY_H #include "_scriptapi.h" namespace Script { namespace Memory { SCRIPT_EXPORT bool Read(duint addr, void* data, duint size, duint* sizeRead); SCRIPT_EXPORT bool Write(duint addr, const void* data, duint size, duint* sizeWritten); SCRIPT_EXPORT bool IsValidPtr(duint addr); SCRIPT_EXPORT duint RemoteAlloc(duint addr, duint size); SCRIPT_EXPORT bool RemoteFree(duint addr); SCRIPT_EXPORT unsigned int GetProtect(duint addr, bool reserved = false, bool cache = true); SCRIPT_EXPORT bool SetProtect(duint addr, unsigned int protect, duint size); SCRIPT_EXPORT duint GetBase(duint addr, bool reserved = false, bool cache = true); SCRIPT_EXPORT duint GetSize(duint addr, bool reserved = false, bool cache = true); SCRIPT_EXPORT unsigned char ReadByte(duint addr); SCRIPT_EXPORT bool WriteByte(duint addr, unsigned char data); SCRIPT_EXPORT unsigned short ReadWord(duint addr); SCRIPT_EXPORT bool WriteWord(duint addr, unsigned short data); SCRIPT_EXPORT unsigned int ReadDword(duint addr); SCRIPT_EXPORT bool WriteDword(duint addr, unsigned int data); SCRIPT_EXPORT unsigned long long ReadQword(duint addr); SCRIPT_EXPORT bool WriteQword(duint addr, unsigned long long data); SCRIPT_EXPORT duint ReadPtr(duint addr); SCRIPT_EXPORT bool WritePtr(duint addr, duint data); }; //Memory }; //Script #endif //_SCRIPTAPI_MEMORY_H
C++
x64dbg-development/src/dbg/_scriptapi_misc.cpp
#include "_scriptapi_misc.h" #include "value.h" SCRIPT_EXPORT bool Script::Misc::ParseExpression(const char* expression, duint* value) { return valfromstring(expression, value); } SCRIPT_EXPORT duint Script::Misc::RemoteGetProcAddress(const char* module, const char* api) { duint value; if(!ParseExpression(StringUtils::sprintf("%s:%s", module, api).c_str(), &value)) return 0; return value; } SCRIPT_EXPORT duint Script::Misc::ResolveLabel(const char* label) { duint value; if(!ParseExpression(label, &value)) return 0; return value; } SCRIPT_EXPORT void* Script::Misc::Alloc(duint size) { return BridgeAlloc(size); } SCRIPT_EXPORT void Script::Misc::Free(void* ptr) { return BridgeFree(ptr); }
C/C++
x64dbg-development/src/dbg/_scriptapi_misc.h
#ifndef _SCRIPTAPI_MISC_H #define _SCRIPTAPI_MISC_H #include "_scriptapi.h" namespace Script { namespace Misc { /// <summary> /// Evaluates an expression and returns the result. Analagous to using the Command field in x64dbg. /// /// Expressions can consist of memory locations, registers, flags, API names, labels, symbols, variables etc. /// <example> /// Shows how to read from stack at esp+8 /// <code> /// bool success = ParseExpression("[esp+8]", &amp;val) /// </code> /// </example> /// </summary> /// <param name="expression">The expression to evaluate.</param> /// <param name="value">The result of the expression.</param> /// <returns>True on success, False on failure.</returns> SCRIPT_EXPORT bool ParseExpression(const char* expression, duint* value); /// <summary> /// Returns the address of a function in the debuggee's memory space. /// </summary> /// <example> /// <code> /// duint addr = RemoteGetProcAddress("kernel32.dll", "GetProcAddress") /// </code> /// </example> /// <param name="module">The name of the module.</param> /// <param name="api">The name of the function.</param> /// <returns>The address of the function in the debuggee.</returns> SCRIPT_EXPORT duint RemoteGetProcAddress(const char* module, const char* api); /// <summary> /// Returns the address for a label created in the disassembly window. /// </summary> /// <example> /// <code> /// duint addr = ResolveLabel("sneaky_crypto") /// </code> /// </example> /// <param name="label">The name of the label to resolve.</param> /// <returns>The memory address for the label.</returns> SCRIPT_EXPORT duint ResolveLabel(const char* label); /// <summary> /// Allocates the requested number of bytes from x64dbg's default process heap. /// /// Note: this allocation is in the debugger, not the debuggee. /// /// Memory allocated using this function should be Free'd after use. /// </summary> /// <example> /// <code> /// void* addr = Alloc(0x100000) /// </code> /// </example> /// <param name="size">Number of bytes to allocate.</param> /// <returns>A pointer to the newly allocated memory.</returns> SCRIPT_EXPORT void* Alloc(duint size); /// <summary> /// Frees memory previously allocated by Alloc. /// </summary> /// <example> /// <code> /// Free(addr) /// </code> /// </example> /// <param name="ptr">Pointer returned by Alloc.</param> /// <returns>Nothing.</returns> SCRIPT_EXPORT void Free(void* ptr); }; //Misc }; //Script #endif //_SCRIPTAPI_MISC_H
C++
x64dbg-development/src/dbg/_scriptapi_module.cpp
#include "_scriptapi_module.h" #include "threading.h" #include "module.h" #include "debugger.h" SCRIPT_EXPORT bool Script::Module::InfoFromAddr(duint addr, ModuleInfo* info) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(addr); if(!info || !modInfo) return false; info->base = modInfo->base; info->size = modInfo->size; info->entry = modInfo->entry; info->sectionCount = int(modInfo->sections.size()); strcpy_s(info->name, modInfo->name); strcat_s(info->name, modInfo->extension); strcpy_s(info->path, modInfo->path); return true; } SCRIPT_EXPORT bool Script::Module::InfoFromName(const char* name, ModuleInfo* info) { return InfoFromAddr(BaseFromName(name), info); } SCRIPT_EXPORT duint Script::Module::BaseFromAddr(duint addr) { return ModBaseFromAddr(addr); } SCRIPT_EXPORT duint Script::Module::BaseFromName(const char* name) { return ModBaseFromName(name); } SCRIPT_EXPORT duint Script::Module::SizeFromAddr(duint addr) { return ModSizeFromAddr(addr); } SCRIPT_EXPORT duint Script::Module::SizeFromName(const char* name) { return SizeFromAddr(BaseFromName(name)); } SCRIPT_EXPORT bool Script::Module::NameFromAddr(duint addr, char* name) { return ModNameFromAddr(addr, name, true); } SCRIPT_EXPORT bool Script::Module::PathFromAddr(duint addr, char* path) { return !!ModPathFromAddr(addr, path, MAX_PATH); } SCRIPT_EXPORT bool Script::Module::PathFromName(const char* name, char* path) { return PathFromAddr(BaseFromName(name), path); } SCRIPT_EXPORT duint Script::Module::EntryFromAddr(duint addr) { return ModEntryFromAddr(addr); } SCRIPT_EXPORT duint Script::Module::EntryFromName(const char* name) { return EntryFromAddr(BaseFromName(name)); } SCRIPT_EXPORT int Script::Module::SectionCountFromAddr(duint addr) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(addr); return modInfo ? int(modInfo->sections.size()) : 0; } SCRIPT_EXPORT int Script::Module::SectionCountFromName(const char* name) { return SectionCountFromAddr(BaseFromName(name)); } SCRIPT_EXPORT bool Script::Module::SectionFromAddr(duint addr, int number, ModuleSectionInfo* section) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(addr); if(!section || !modInfo || number < 0 || number >= int(modInfo->sections.size())) return false; const auto & secInfo = modInfo->sections.at(number); section->addr = secInfo.addr; section->size = secInfo.size; strcpy_s(section->name, secInfo.name); return true; } SCRIPT_EXPORT bool Script::Module::SectionFromName(const char* name, int number, ModuleSectionInfo* section) { return SectionFromAddr(BaseFromName(name), number, section); } SCRIPT_EXPORT bool Script::Module::SectionListFromAddr(duint addr, ListOf(ModuleSectionInfo) list) { SHARED_ACQUIRE(LockModules); auto modInfo = ModInfoFromAddr(addr); if(!modInfo) return false; std::vector<ModuleSectionInfo> scriptSectionList; scriptSectionList.reserve(modInfo->sections.size()); for(const auto & section : modInfo->sections) { ModuleSectionInfo scriptSection; scriptSection.addr = section.addr; scriptSection.size = section.size; strcpy_s(scriptSection.name, section.name); scriptSectionList.push_back(scriptSection); } return BridgeList<ModuleSectionInfo>::CopyData(list, scriptSectionList); } SCRIPT_EXPORT bool Script::Module::SectionListFromName(const char* name, ListOf(ModuleSectionInfo) list) { return SectionListFromAddr(BaseFromName(name), list); } SCRIPT_EXPORT bool Script::Module::GetMainModuleInfo(ModuleInfo* info) { return InfoFromAddr(GetMainModuleBase(), info); } SCRIPT_EXPORT duint Script::Module::GetMainModuleBase() { return dbgdebuggedbase(); } SCRIPT_EXPORT duint Script::Module::GetMainModuleSize() { return SizeFromAddr(GetMainModuleBase()); } SCRIPT_EXPORT duint Script::Module::GetMainModuleEntry() { return EntryFromAddr(GetMainModuleBase()); } SCRIPT_EXPORT int Script::Module::GetMainModuleSectionCount() { return SectionCountFromAddr(GetMainModuleBase()); } SCRIPT_EXPORT bool Script::Module::GetMainModuleName(char* name) { return NameFromAddr(GetMainModuleBase(), name); } SCRIPT_EXPORT bool Script::Module::GetMainModulePath(char* path) { return PathFromAddr(GetMainModuleBase(), path); } SCRIPT_EXPORT bool Script::Module::GetMainModuleSectionList(ListOf(ModuleSectionInfo) list) { return SectionListFromAddr(GetMainModuleBase(), list); } SCRIPT_EXPORT bool Script::Module::GetList(ListOf(ModuleInfo) list) { std::vector<ModuleInfo> modScriptList; ModEnum([&modScriptList](const MODINFO & mod) { ModuleInfo scriptMod; scriptMod.base = mod.base; scriptMod.size = mod.size; scriptMod.entry = mod.entry; scriptMod.sectionCount = int(mod.sections.size()); strcpy_s(scriptMod.name, mod.name); strcat_s(scriptMod.name, mod.extension); strcpy_s(scriptMod.path, mod.path); modScriptList.push_back(scriptMod); }); return BridgeList<ModuleInfo>::CopyData(list, modScriptList); } SCRIPT_EXPORT bool Script::Module::GetExports(const ModuleInfo* mod, ListOf(ModuleExport) list) { SHARED_ACQUIRE(LockModules); if(mod == nullptr) return false; MODINFO* modInfo = ModInfoFromAddr(mod->base); if(modInfo == nullptr) return false; std::vector<ModuleExport> modExportList; modExportList.reserve(modInfo->exports.size()); for(auto & modExport : modInfo->exports) { ModuleExport entry; entry.ordinal = modExport.ordinal; entry.rva = modExport.rva; entry.va = modExport.rva + modInfo->base; entry.forwarded = modExport.forwarded; strncpy_s(entry.forwardName, modExport.forwardName.c_str(), _TRUNCATE); strncpy_s(entry.name, modExport.name.c_str(), _TRUNCATE); strncpy_s(entry.undecoratedName, modExport.undecoratedName.c_str(), _TRUNCATE); modExportList.push_back(entry); } return BridgeList<ModuleExport>::CopyData(list, modExportList); } SCRIPT_EXPORT bool Script::Module::GetImports(const ModuleInfo* mod, ListOf(ModuleImport) list) { SHARED_ACQUIRE(LockModules); if(mod == nullptr) return false; MODINFO* modInfo = ModInfoFromAddr(mod->base); if(modInfo == nullptr) return false; std::vector<ModuleImport> modImportList; modImportList.reserve(modInfo->imports.size()); for(auto & modImport : modInfo->imports) { ModuleImport entry; entry.ordinal = modImport.ordinal; entry.iatRva = modImport.iatRva; entry.iatVa = modImport.iatRva + modInfo->base; strncpy_s(entry.name, modImport.name.c_str(), _TRUNCATE); strncpy_s(entry.undecoratedName, modImport.undecoratedName.c_str(), _TRUNCATE); modImportList.push_back(entry); } return BridgeList<ModuleImport>::CopyData(list, modImportList); }
C/C++
x64dbg-development/src/dbg/_scriptapi_module.h
#ifndef _SCRIPTAPI_MODULE_H #define _SCRIPTAPI_MODULE_H #include "_scriptapi.h" namespace Script { namespace Module { struct ModuleInfo { duint base; duint size; duint entry; int sectionCount; char name[MAX_MODULE_SIZE]; char path[MAX_PATH]; }; struct ModuleSectionInfo { duint addr; duint size; char name[MAX_SECTION_SIZE * 5]; }; struct ModuleExport { duint ordinal; duint rva; duint va; bool forwarded; char forwardName[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; char undecoratedName[MAX_STRING_SIZE]; }; struct ModuleImport { duint iatRva; duint iatVa; duint ordinal; //equal to -1 if imported by name char name[MAX_STRING_SIZE]; char undecoratedName[MAX_STRING_SIZE]; }; SCRIPT_EXPORT bool InfoFromAddr(duint addr, ModuleInfo* info); SCRIPT_EXPORT bool InfoFromName(const char* name, ModuleInfo* info); SCRIPT_EXPORT duint BaseFromAddr(duint addr); SCRIPT_EXPORT duint BaseFromName(const char* name); SCRIPT_EXPORT duint SizeFromAddr(duint addr); SCRIPT_EXPORT duint SizeFromName(const char* name); SCRIPT_EXPORT bool NameFromAddr(duint addr, char* name); //name[MAX_MODULE_SIZE] SCRIPT_EXPORT bool PathFromAddr(duint addr, char* path); //path[MAX_PATH] SCRIPT_EXPORT bool PathFromName(const char* name, char* path); //path[MAX_PATH] SCRIPT_EXPORT duint EntryFromAddr(duint addr); SCRIPT_EXPORT duint EntryFromName(const char* name); SCRIPT_EXPORT int SectionCountFromAddr(duint addr); SCRIPT_EXPORT int SectionCountFromName(const char* name); SCRIPT_EXPORT bool SectionFromAddr(duint addr, int number, ModuleSectionInfo* section); SCRIPT_EXPORT bool SectionFromName(const char* name, int number, ModuleSectionInfo* section); SCRIPT_EXPORT bool SectionListFromAddr(duint addr, ListOf(ModuleSectionInfo) list); SCRIPT_EXPORT bool SectionListFromName(const char* name, ListOf(ModuleSectionInfo) list); SCRIPT_EXPORT bool GetMainModuleInfo(ModuleInfo* info); SCRIPT_EXPORT duint GetMainModuleBase(); SCRIPT_EXPORT duint GetMainModuleSize(); SCRIPT_EXPORT duint GetMainModuleEntry(); SCRIPT_EXPORT int GetMainModuleSectionCount(); SCRIPT_EXPORT bool GetMainModuleName(char* name); //name[MAX_MODULE_SIZE] SCRIPT_EXPORT bool GetMainModulePath(char* path); //path[MAX_PATH] SCRIPT_EXPORT bool GetMainModuleSectionList(ListOf(ModuleSectionInfo) list); //caller has the responsibility to free the list SCRIPT_EXPORT bool GetList(ListOf(ModuleInfo) list); //caller has the responsibility to free the list SCRIPT_EXPORT bool GetExports(const ModuleInfo* mod, ListOf(ModuleExport) list); //caller has the responsibility to free the list SCRIPT_EXPORT bool GetImports(const ModuleInfo* mod, ListOf(ModuleImport) list); //caller has the responsibility to free the list }; //Module }; //Script #endif //_SCRIPTAPI_MODULE_H
C++
x64dbg-development/src/dbg/_scriptapi_pattern.cpp
#include "_scriptapi_pattern.h" #include "patternfind.h" #include "memory.h" SCRIPT_EXPORT duint Script::Pattern::Find(unsigned char* data, duint datasize, const char* pattern) { return patternfind(data, datasize, pattern); } SCRIPT_EXPORT duint Script::Pattern::FindMem(duint start, duint size, const char* pattern) { Memory<unsigned char*> data(size, "Script::Pattern::FindMem::data"); if(!MemRead(start, data(), size)) return -1; auto found = Pattern::Find(data(), data.size(), pattern); return found == -1 ? 0 : found + start; } SCRIPT_EXPORT void Script::Pattern::Write(unsigned char* data, duint datasize, const char* pattern) { patternwrite(data, datasize, pattern); } SCRIPT_EXPORT void Script::Pattern::WriteMem(duint start, duint size, const char* pattern) { Memory<unsigned char*> data(size, "Script::Pattern::WriteMem::data"); if(!MemRead(start, data(), data.size())) return; patternwrite(data(), data.size(), pattern); MemWrite(start, data(), data.size()); } SCRIPT_EXPORT bool Script::Pattern::SearchAndReplace(unsigned char* data, duint datasize, const char* searchpattern, const char* replacepattern) { return patternsnr(data, datasize, searchpattern, replacepattern); } SCRIPT_EXPORT bool Script::Pattern::SearchAndReplaceMem(duint start, duint size, const char* searchpattern, const char* replacepattern) { Memory<unsigned char*> data(size, "Script::Pattern::SearchAndReplaceMem::data"); if(!MemRead(start, data(), size)) return false; auto found = patternfind(data(), data.size(), searchpattern); if(found == -1) return false; patternwrite(data() + found, data.size() - found, replacepattern); MemWrite((start + found), data() + found, data.size() - found); return true; }
C/C++
x64dbg-development/src/dbg/_scriptapi_pattern.h
#ifndef _SCRIPTAPI_PATTERN_H #define _SCRIPTAPI_PATTERN_H #include "_scriptapi.h" namespace Script { namespace Pattern { SCRIPT_EXPORT duint Find(unsigned char* data, duint datasize, const char* pattern); SCRIPT_EXPORT duint FindMem(duint start, duint size, const char* pattern); SCRIPT_EXPORT void Write(unsigned char* data, duint datasize, const char* pattern); SCRIPT_EXPORT void WriteMem(duint start, duint size, const char* pattern); SCRIPT_EXPORT bool SearchAndReplace(unsigned char* data, duint datasize, const char* searchpattern, const char* replacepattern); SCRIPT_EXPORT bool SearchAndReplaceMem(duint start, duint size, const char* searchpattern, const char* replacepattern); }; }; #endif //_SCRIPTAPI_FIND_H