BVB Source Codes

x64dbg Show _global.cpp Source code

Return Download x64dbg: download _global.cpp Source code - Download x64dbg Source code - Type:.cpp
  1. /**
  2. \file _global.cpp
  3. \brief Implements the global class.
  4. */
  5.  
  6. #include "_global.h"
  7. #include <objbase.h>
  8. #include <shlobj.h>
  9.  
  10. /**
  11. \brief x64dbg library instance.
  12. */
  13. HINSTANCE hInst;
  14.  
  15. /**
  16. \brief Number of allocated buffers by emalloc(). This should be 0 when x64dbg ends.
  17. */
  18. static int emalloc_count = 0;
  19. #ifdef ENABLE_MEM_TRACE
  20. /**
  21. \brief Path for debugging, used to create an allocation trace file on emalloc() or efree(). Not used.
  22. */
  23. static char alloctrace[MAX_PATH] = "";
  24. static std::unordered_map<void*, int> alloctracemap;
  25. static CRITICAL_SECTION criticalSection;
  26. #endif
  27.  
  28. /**
  29. \brief Allocates a new buffer.
  30. \param size The size of the buffer to allocate (in bytes).
  31. \param reason The reason for allocation (can be used for memory allocation tracking).
  32. \return Always returns a valid pointer to the buffer you requested. Will quit the application on errors.
  33. */
  34. void* emalloc(size_t size, const char* reason)
  35. {
  36.     ASSERT_NONZERO(size);
  37. #ifdef ENABLE_MEM_TRACE
  38.     unsigned char* a = (unsigned char*)GlobalAlloc(GMEM_FIXED, size + sizeof(void*));
  39. #else
  40.     unsigned char* a = (unsigned char*)GlobalAlloc(GMEM_FIXED, size);
  41. #endif //ENABLE_MEM_TRACE
  42.     if(!a)
  43.     {
  44.         MessageBoxW(0, L"Could not allocate memory", L"Error", MB_ICONERROR);
  45.         ExitProcess(1);
  46.     }
  47.     emalloc_count++;
  48. #ifdef ENABLE_MEM_TRACE
  49.     EnterCriticalSection(&criticalSection);
  50.     memset(a, 0, size + sizeof(void*));
  51.     FILE* file = fopen(alloctrace, "a+");
  52.     fprintf(file, "DBG%.5d:  alloc:%p:%p:%s:%p\n", emalloc_count, a, _ReturnAddress(), reason, size);
  53.     fclose(file);
  54.     alloctracemap[_ReturnAddress()]++;
  55.     *(void**)a = _ReturnAddress();
  56.     LeaveCriticalSection(&criticalSection);
  57.     return a + sizeof(void*);
  58. #else
  59.     memset(a, 0, size);
  60.     return a;
  61. #endif //ENABLE_MEM_TRACE
  62. }
  63.  
  64. /**
  65. \brief Reallocates a buffer allocated with emalloc().
  66. \param [in] Pointer to memory previously allocated with emalloc(). When NULL a new buffer will be allocated by emalloc().
  67. \param size The new memory size.
  68. \param reason The reason for allocation (can be used for memory allocation tracking).
  69. \return Always returns a valid pointer to the buffer you requested. Will quit the application on errors.
  70. */
  71. void* erealloc(void* ptr, size_t size, const char* reason)
  72. {
  73.     ASSERT_NONZERO(size);
  74.  
  75.     // Free the memory if the pointer was set (as per documentation).
  76.     if(ptr)
  77.         efree(ptr, reason);
  78.  
  79.     return emalloc(size, reason);
  80. }
  81.  
  82. /**
  83. \brief Free memory previously allocated with emalloc().
  84. \param [in] Pointer to the memory to free.
  85. \param reason The reason for freeing, should be the same as the reason for allocating.
  86. */
  87. void efree(void* ptr, const char* reason)
  88. {
  89.     emalloc_count--;
  90. #ifdef ENABLE_MEM_TRACE
  91.     EnterCriticalSection(&criticalSection);
  92.     char* ptr2 = (char*)ptr - sizeof(void*);
  93.     FILE* file = fopen(alloctrace, "a+");
  94.     fprintf(file, "DBG%.5d:   free:%p:%p:%s\n", emalloc_count, ptr, *(void**)ptr2, reason);
  95.     fclose(file);
  96.     if(alloctracemap.find(*(void**)ptr2) != alloctracemap.end())
  97.     {
  98.         if(--alloctracemap.at(*(void**)ptr2) < 0)
  99.         {
  100.             String str = StringUtils::sprintf("address %p, reason %s", *(void**)ptr2, reason);
  101.             MessageBoxA(0, str.c_str(), "Freed memory more than once", MB_OK);
  102.             __debugbreak();
  103.         }
  104.     }
  105.     else
  106.     {
  107.         String str = StringUtils::sprintf("address %p, reason %s", *(void**)ptr2, reason);
  108.         MessageBoxA(0, str.c_str(), "Trying to free const memory", MB_OK);
  109.         __debugbreak();
  110.     }
  111.     LeaveCriticalSection(&criticalSection);
  112.     GlobalFree(ptr2);
  113. #else
  114.     GlobalFree(ptr);
  115. #endif //ENABLE_MEM_TRACE
  116. }
  117.  
  118. void* json_malloc(size_t size)
  119. {
  120. #ifdef ENABLE_MEM_TRACE
  121.     return emalloc(size, "json:ptr");
  122. #else
  123.     return emalloc(size);
  124. #endif
  125. }
  126.  
  127. void json_free(void* ptr)
  128. {
  129. #ifdef ENABLE_MEM_TRACE
  130.     return efree(ptr, "json:ptr");
  131. #else
  132.     return efree(ptr);
  133. #endif
  134. }
  135.  
  136. /**
  137. \brief Gets the number of memory leaks. This number is only valid in _dbg_dbgexitsignal().
  138. \return The number of memory leaks.
  139. */
  140. int memleaks()
  141. {
  142. #ifdef ENABLE_MEM_TRACE
  143.     EnterCriticalSection(&criticalSection);
  144.     auto leaked = false;
  145.     for(auto & i : alloctracemap)
  146.     {
  147.         if(i.second != 0)
  148.         {
  149.             String str = StringUtils::sprintf("memory leak at %p : count %d", i.first, i.second);
  150.             MessageBoxA(0, str.c_str(), "memory leak", MB_OK);
  151.             leaked = true;
  152.         }
  153.     }
  154.     if(leaked)
  155.         __debugbreak();
  156.     LeaveCriticalSection(&criticalSection);
  157. #endif
  158.     return emalloc_count;
  159. }
  160.  
  161. #ifdef ENABLE_MEM_TRACE
  162. /**
  163. \brief Sets the path for the allocation trace file.
  164. \param file UTF-8 filepath.
  165. */
  166. void setalloctrace(const char* file)
  167. {
  168.     InitializeCriticalSection(&criticalSection);
  169.     strcpy_s(alloctrace, file);
  170. }
  171. #endif //ENABLE_MEM_TRACE
  172.  
  173. /**
  174. \brief Compares two strings without case-sensitivity.
  175. \param a The first string.
  176. \param b The second string.
  177. \return true if the strings are equal (case-insensitive).
  178. */
  179. bool scmp(const char* a, const char* b)
  180. {
  181.     if(!a || !b)
  182.         return false;
  183.     return !_stricmp(a, b);
  184. }
  185.  
  186. /**
  187. \brief Formats a string to hexadecimal format (removes all non-hex characters).
  188. \param [in,out] String to format.
  189. */
  190. void formathex(char* string)
  191. {
  192.     int len = (int)strlen(string);
  193.     _strupr(string);
  194.     Memory<char*> new_string(len + 1, "formathex:new_string");
  195.     for(int i = 0, j = 0; i < len; i++)
  196.         if(isxdigit(string[i]))
  197.             j += sprintf(new_string() + j, "%c", string[i]);
  198.     strcpy_s(string, len + 1, new_string());
  199. }
  200.  
  201. /**
  202. \brief Formats a string to decimal format (removed all non-numeric characters).
  203. \param [in,out] String to format.
  204. */
  205. void formatdec(char* string)
  206. {
  207.     int len = (int)strlen(string);
  208.     _strupr(string);
  209.     Memory<char*> new_string(len + 1, "formatdec:new_string");
  210.     for(int i = 0, j = 0; i < len; i++)
  211.         if(isdigit(string[i]))
  212.             j += sprintf(new_string() + j, "%c", string[i]);
  213.     strcpy_s(string, len + 1, new_string());
  214. }
  215.  
  216. /**
  217. \brief Queries if a given file exists.
  218. \param file Path to the file to check (UTF-8).
  219. \return true if the file exists on the hard drive.
  220. */
  221. bool FileExists(const char* file)
  222. {
  223.     DWORD attrib = GetFileAttributesW(StringUtils::Utf8ToUtf16(file).c_str());
  224.     return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY));
  225. }
  226.  
  227. /**
  228. \brief Queries if a given directory exists.
  229. \param dir Path to the directory to check (UTF-8).
  230. \return true if the directory exists.
  231. */
  232. bool DirExists(const char* dir)
  233. {
  234.     DWORD attrib = GetFileAttributesW(StringUtils::Utf8ToUtf16(dir).c_str());
  235.     return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0);
  236. }
  237.  
  238. /**
  239. \brief Gets file path from a file handle.
  240. \param hFile File handle to get the path from.
  241. \param [in,out] szFileName Buffer of size MAX_PATH.
  242. \return true if it succeeds, false if it fails.
  243. */
  244. bool GetFileNameFromHandle(HANDLE hFile, char* szFileName)
  245. {
  246.     if(!hFile)
  247.         return false;
  248.     wchar_t wszFileName[MAX_PATH] = L"";
  249.     if(!PathFromFileHandleW(hFile, wszFileName, _countof(wszFileName)))
  250.         return false;
  251.     strcpy_s(szFileName, MAX_PATH, StringUtils::Utf16ToUtf8(wszFileName).c_str());
  252.     return true;
  253. }
  254.  
  255. bool GetFileNameFromProcessHandle(HANDLE hProcess, char* szFileName)
  256. {
  257.     wchar_t wszDosFileName[MAX_PATH] = L"";
  258.     wchar_t wszFileName[MAX_PATH] = L"";
  259.     auto result = false;
  260.     if(GetProcessImageFileNameW(hProcess, wszDosFileName, _countof(wszDosFileName)))
  261.     {
  262.         if(!DevicePathToPathW(wszDosFileName, wszFileName, _countof(wszFileName)))
  263.             result = !!GetModuleFileNameExW(hProcess, 0, wszFileName, _countof(wszFileName));
  264.         else
  265.             result = true;
  266.     }
  267.     else
  268.         result = !!GetModuleFileNameExW(hProcess, 0, wszFileName, _countof(wszFileName));
  269.     if(result)
  270.         strcpy_s(szFileName, MAX_PATH, StringUtils::Utf16ToUtf8(wszFileName).c_str());
  271.     return result;
  272. }
  273.  
  274. bool GetFileNameFromModuleHandle(HANDLE hProcess, HMODULE hModule, char* szFileName)
  275. {
  276.     wchar_t wszDosFileName[MAX_PATH] = L"";
  277.     wchar_t wszFileName[MAX_PATH] = L"";
  278.     auto result = false;
  279.     if(GetMappedFileNameW(hProcess, hModule, wszDosFileName, _countof(wszDosFileName)))
  280.     {
  281.         if(!DevicePathToPathW(wszDosFileName, wszFileName, _countof(wszFileName)))
  282.             result = !!GetModuleFileNameExW(hProcess, hModule, wszFileName, _countof(wszFileName));
  283.         else
  284.             result = true;
  285.     }
  286.     else
  287.         result = !!GetModuleFileNameExW(hProcess, hModule, wszFileName, _countof(wszFileName));
  288.     if(result)
  289.         strcpy_s(szFileName, MAX_PATH, StringUtils::Utf16ToUtf8(wszFileName).c_str());
  290.     return result;
  291. }
  292.  
  293. /**
  294. \brief Get a boolean setting from the configuration file.
  295. \param section The section of the setting (UTF-8).
  296. \param name The name of the setting (UTF-8).
  297. \return true if the setting was set and equals to true, otherwise returns false.
  298. */
  299. bool settingboolget(const char* section, const char* name)
  300. {
  301.     duint setting;
  302.     if(!BridgeSettingGetUint(section, name, &setting))
  303.         return false;
  304.     if(setting)
  305.         return true;
  306.     return false;
  307. }
  308.  
  309. /**
  310. \brief Gets file architecture.
  311. \param szFileName UTF-8 encoded file path.
  312. \return The file architecture (::arch).
  313. */
  314. arch GetFileArchitecture(const char* szFileName)
  315. {
  316.     arch retval = notfound;
  317.     HANDLE hFile = CreateFileW(StringUtils::Utf8ToUtf16(szFileName).c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  318.     if(hFile != INVALID_HANDLE_VALUE)
  319.     {
  320.         IMAGE_DOS_HEADER idh;
  321.         DWORD read = 0;
  322.         if(ReadFile(hFile, &idh, sizeof(idh), &read, nullptr))
  323.         {
  324.             if(idh.e_magic == IMAGE_DOS_SIGNATURE)
  325.             {
  326.                 IMAGE_NT_HEADERS inth;
  327.                 memset(&inth, 0, sizeof(inth));
  328.                 PIMAGE_NT_HEADERS pnth = nullptr;
  329.                 if(SetFilePointer(hFile, idh.e_lfanew, nullptr, FILE_BEGIN) != INVALID_SET_FILE_POINTER)
  330.                 {
  331.                     if(ReadFile(hFile, &inth, sizeof(inth), &read, nullptr))
  332.                         pnth = &inth;
  333.                     else if(ReadFile(hFile, &inth, sizeof(DWORD) + sizeof(WORD), &read, nullptr))
  334.                         pnth = &inth;
  335.                 }
  336.                 if(pnth && pnth->Signature == IMAGE_NT_SIGNATURE)
  337.                 {
  338.                     if(pnth->OptionalHeader.DataDirectory[15].VirtualAddress != 0 && pnth->OptionalHeader.DataDirectory[15].Size != 0 && (pnth->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0)
  339.                         retval = dotnet;
  340.                     else if(pnth->FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
  341.                         retval = x32;
  342.                     else if(pnth->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
  343.                         retval = x64;
  344.                 }
  345.             }
  346.         }
  347.         CloseHandle(hFile);
  348.     }
  349.     return retval;
  350. }
  351.  
  352. /**
  353. \brief Query if x64dbg is running in Wow64 mode.
  354. \return true if running in Wow64, false otherwise.
  355. */
  356. bool IsWow64()
  357. {
  358.     BOOL bIsWow64Process = FALSE;
  359.     //x64dbg supports WinXP SP3 and later only, so ignore the GetProcAddress crap :D
  360.     IsWow64Process(GetCurrentProcess(), &bIsWow64Process);
  361.     return !!bIsWow64Process;
  362. }
  363.  
  364. //Taken from: http://www.cplusplus.com/forum/windows/64088/
  365. bool ResolveShortcut(HWND hwnd, const wchar_t* szShortcutPath, char* szResolvedPath, size_t nSize)
  366. {
  367.     if(szResolvedPath == NULL)
  368.         return SUCCEEDED(E_INVALIDARG);
  369.  
  370.     //Initialize COM stuff
  371.     if(!SUCCEEDED(CoInitialize(NULL)))
  372.         return false;
  373.  
  374.     //Get a pointer to the IShellLink interface.
  375.     IShellLink* psl = NULL;
  376.     HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
  377.     if(SUCCEEDED(hres))
  378.     {
  379.         //Get a pointer to the IPersistFile interface.
  380.         IPersistFile* ppf = NULL;
  381.         hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
  382.         if(SUCCEEDED(hres))
  383.         {
  384.             //Load the shortcut.
  385.             hres = ppf->Load(szShortcutPath, STGM_READ);
  386.  
  387.             if(SUCCEEDED(hres))
  388.             {
  389.                 //Resolve the link.
  390.                 hres = psl->Resolve(hwnd, 0);
  391.  
  392.                 if(SUCCEEDED(hres))
  393.                 {
  394.                     //Get the path to the link target.
  395.                     char szGotPath[MAX_PATH] = {0};
  396.                     hres = psl->GetPath(szGotPath, _countof(szGotPath), NULL, SLGP_SHORTPATH);
  397.  
  398.                     if(SUCCEEDED(hres))
  399.                     {
  400.                         strcpy_s(szResolvedPath, nSize, szGotPath);
  401.                     }
  402.                 }
  403.             }
  404.  
  405.             //Release the pointer to the IPersistFile interface.
  406.             ppf->Release();
  407.         }
  408.  
  409.         //Release the pointer to the IShellLink interface.
  410.         psl->Release();
  411.     }
  412.  
  413.     //Uninitialize COM stuff
  414.     CoUninitialize();
  415.     return SUCCEEDED(hres);
  416. }
  417.  
  418. void WaitForThreadTermination(HANDLE hThread, DWORD timeout)
  419. {
  420.     WaitForSingleObject(hThread, timeout);
  421.     CloseHandle(hThread);
  422. }
  423.  
  424. void WaitForMultipleThreadsTermination(const HANDLE* hThread, int count, DWORD timeout)
  425. {
  426.     WaitForMultipleObjects(count, hThread, TRUE, timeout);
  427.     for(int i = 0; i < count; i++)
  428.         CloseHandle(hThread[i]);
  429. }
  430.  
download_global.cpp Source code - Download x64dbg Source code
Related Source Codes/Software:
pencil - Multiplatform GUI Prototyping/Wireframing 2017-04-16
rainloop-webmail - Simple, modern & fast web-based email client ... 2017-04-16
qt - Qt binding for Go (Golang) which supports Windows ... 2017-04-16
MLeaksFinder - Find memory leaks in your iOS app at develop time. 2017-04-16
jsfeat - JavaScript Computer Vision library. 2017-04-16
later - A javascript library for defining recurring schedu... 2017-04-16
Android-ItemTouchHelper-Demo - Basic example of using ItemTouchHelper to add drag... 2017-04-16
onionshare - Securely and anonymously share a file of any size ... 2017-04-16
android-viewflow - A horizontal view scroller library for Android 2017-04-16
css-in-js - React: CSS in JS techniques comparison. 2017-04-16
mama2 - Mother plan - all firewood high flame 2017-04-23
BlurEffectForAndroidDesign - Sample to show how to implement blur graphical tri... 2017-04-23
sphinx_rtd_theme - Sphinx theme for readthedocs.org 2017-04-23
rouge - A pure-ruby code highlighter that is compatible wi... 2017-04-23
spring-security-oauth - Support for adding OAuth1(a) and OAuth2 features (... 2017-04-23
Toucan - Fabulous Image Processing in Swift 2017-04-23
CoffeeScriptRedux - 2017-04-23
breakpoint - Really simple media queries in Sa 2017-04-23
libsvm - 2017-04-22
grr - GRR Rapid Response: remote live forensics for inci... 2017-04-22

 Back to top