DebugManager.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  1. #include "DebugManager.h"
  2. #include "BeefySysLib/util/CritSect.h"
  3. #include "Compiler/BfSystem.h"
  4. #include "Compiler/BfParser.h"
  5. #include "Compiler/MemReporter.h"
  6. #include "Compiler/BfIRCodeGen.h"
  7. #include "Debugger.h"
  8. #include "DebugVisualizers.h"
  9. #include "RadixMap.h"
  10. #include "Compiler/BfDemangler.h"
  11. #include "llvm/Support/ErrorHandling.h"
  12. #include "BeefySysLib/util/BeefPerf.h"
  13. #include "NetManager.h"
  14. #ifdef BF_PLATFORM_WINDOWS
  15. #include "DbgMiniDump.h"
  16. #endif
  17. #include <iostream>
  18. #pragma warning(push)
  19. #pragma warning(disable:4141)
  20. #pragma warning(disable:4146)
  21. #pragma warning(disable:4291)
  22. #pragma warning(disable:4244)
  23. #pragma warning(disable:4267)
  24. #pragma warning(disable:4624)
  25. #pragma warning(disable:4800)
  26. #pragma warning(disable:4996)
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IRReader/IRReader.h"
  29. //#include "llvm/Bitcode/ReaderWriter.h"
  30. #pragma warning(pop)
  31. #ifdef BF_PLATFORM_WINDOWS
  32. #include <psapi.h>
  33. #include <shlobj.h>
  34. #endif
  35. #include "BeefySysLib/util/AllocDebug.h"
  36. #pragma warning(disable:4190)
  37. #define ENABLE_DBG_32
  38. //#define BF_DBG_32
  39. //#include "WinDebugger.h"
  40. //#undef BF_DBG_32
  41. /*#define BF_DBG_64
  42. #include "WinDebugger.h"
  43. #undef BF_DBG_64*/
  44. int Beefy::sRadixMapCount = 0;
  45. int Beefy::sRootSize = 0;
  46. int Beefy::sMidSize = 0;
  47. int Beefy::sLeafSize = 0;
  48. USING_NS_BF;
  49. DebugManager* Beefy::gDebugManager = NULL;
  50. Debugger* Beefy::gDebugger = NULL;
  51. PerfManager* Beefy::gDbgPerfManager = NULL;
  52. int64 gBfAllocCount = 0;
  53. int64 gBfFreeCount = 0;
  54. static Dictionary<long, int> gBfAllocMap;
  55. static Dictionary<void*, long> gBfAllocAddrMap;
  56. //////////////////////////////////////////////////////////////////////////
  57. DebugManager::DebugManager()
  58. {
  59. gDbgPerfManager = new PerfManager();
  60. mDebugVisualizers = new DebugVisualizers();
  61. mStepFilterVersion = 0;
  62. mStepOverExternalFiles = false;
  63. mDebugger32 = NULL;
  64. mDebugger64 = NULL;
  65. mNetManager = new NetManager();
  66. mNetManager->mDebugManager = this;
  67. mSymSrvOptions.mCacheDir = "C:\\SymCache";
  68. mSymSrvOptions.mSymbolServers.Add("C:\\BeefSyms");
  69. mSymSrvOptions.mSymbolServers.Add("https://msdl.microsoft.com/download/symbols");
  70. mSymSrvOptions.mSymbolServers.Add("http://wintest.beefy2d.com/symbols/");
  71. mSymSrvOptions.mSymbolServers.Add("https://chromium-browser-symsrv.commondatastorage.googleapis.com");
  72. //TODO: Just for testing
  73. mSymSrvOptions.mSymbolServers.Add("http://127.0.0.1/symbols");
  74. SetSourceServerCacheDir();
  75. }
  76. DebugManager::~DebugManager()
  77. {
  78. delete mNetManager;
  79. delete mDebugger64;
  80. delete mDebugger32;
  81. /*for (auto stepFilter : mStepFilters)
  82. {
  83. }*/
  84. delete mDebugVisualizers;
  85. }
  86. void DebugManager::OutputMessage(const StringImpl& msg)
  87. {
  88. AutoCrit autoCrit(mCritSect);
  89. mOutMessages.push_back("msg " + msg);
  90. }
  91. void DebugManager::OutputRawMessage(const StringImpl& msg)
  92. {
  93. AutoCrit autoCrit(mCritSect);
  94. mOutMessages.push_back(msg);
  95. }
  96. void DebugManager::SetSourceServerCacheDir()
  97. {
  98. #ifdef BF_PLATFORM_WINDOWS
  99. AutoCrit autoCrit(mCritSect);
  100. WCHAR appDataPath[MAX_PATH] = { 0 };
  101. SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, appDataPath);
  102. mSymSrvOptions.mSourceServerCacheDir = UTF8Encode(appDataPath);
  103. mSymSrvOptions.mSourceServerCacheDir += "\\SourceServer";
  104. if (mSymSrvOptions.mFlags & BfSymSrvFlag_TempCache)
  105. {
  106. mSymSrvOptions.mSourceServerCacheDir += "\\temp";
  107. RecursiveDeleteDirectory(mSymSrvOptions.mSourceServerCacheDir);
  108. }
  109. #endif
  110. }
  111. //#define CAPTURE_ALLOC_BACKTRACE
  112. //#define CAPTURE_ALLOC_SOURCES
  113. #ifdef CAPTURE_ALLOC_BACKTRACE
  114. const int sNumAllocAddrs = 0x300000;
  115. const int sCaptureDepth = 14;
  116. const int sCaptureOffset = 4;
  117. static intptr gAllocAddrs[sNumAllocAddrs][sCaptureDepth];
  118. #endif
  119. #ifdef CAPTURE_ALLOC_SOURCES
  120. #include <Dbghelp.h>
  121. #pragma comment(lib, "dbghelp.lib")
  122. struct CaptureAllocLocation
  123. {
  124. public:
  125. char* mSymName;
  126. int mTotalSize;
  127. bool mIsEndpoint;
  128. };
  129. struct CaptureAllocEntry
  130. {
  131. public:
  132. CaptureAllocLocation* mLoc;
  133. int mAllocSize;
  134. };
  135. std::map<long, CaptureAllocEntry> gBfCaptureSourceAllocMap;
  136. //std::map<void*, CaptureAllocLocation> gBfCaptureAllocLocation;
  137. #define CAPTURE_ALLOC_POOL_SIZE 0x100000
  138. CaptureAllocLocation* gHashCaptureAllocSize[CAPTURE_ALLOC_POOL_SIZE] = { 0 };
  139. static void ReallocEntry(long oldRequest, long newRequest, int newSize)
  140. {
  141. auto itr = gBfCaptureSourceAllocMap.find(oldRequest);
  142. if (itr != gBfCaptureSourceAllocMap.end())
  143. {
  144. CaptureAllocEntry* entry = &itr->second;
  145. entry->mLoc->mTotalSize -= entry->mAllocSize;
  146. entry->mLoc->mTotalSize += newSize;
  147. entry->mAllocSize = newSize;
  148. gBfCaptureSourceAllocMap[newRequest] = *entry;
  149. gBfCaptureSourceAllocMap.erase(itr);
  150. }
  151. }
  152. static void RemoveAllocEntry(long lRequest)
  153. {
  154. auto itr = gBfCaptureSourceAllocMap.find(lRequest);
  155. if (itr != gBfCaptureSourceAllocMap.end())
  156. {
  157. CaptureAllocEntry* entry = &itr->second;
  158. entry->mLoc->mTotalSize -= entry->mAllocSize;
  159. gBfCaptureSourceAllocMap.erase(itr);
  160. }
  161. }
  162. //const LOC_HASHES
  163. #endif
  164. static int gBfNumAllocs = 0;
  165. #ifdef BF_PLATFORM_WINDOWS
  166. static bool gBgTrackingAllocs = false; ///// Leave false most of the time
  167. CritSect gBfCritSect;
  168. static bool gInsideAlloc = false;
  169. static int gLastReqId = 0;
  170. static int BfAllocHook(int nAllocType, void *pvData,
  171. size_t nSize, int nBlockUse, long lRequest,
  172. const unsigned char * szFileName, int nLine)
  173. {
  174. #ifdef CAPTURE_ALLOC_SOURCES
  175. if (gInsideAlloc)
  176. return TRUE;
  177. gInsideAlloc = true;
  178. intptr stackTrace[20];
  179. int traceCount = (int)RtlCaptureStackBackTrace(1, 20, (void**)&stackTrace, 0);
  180. /*intptr ebpVal;
  181. __asm
  182. {
  183. mov ebpVal, ebp
  184. }*/
  185. //intptr ebp = ebpVal;
  186. //intptr eip = 0;
  187. static HANDLE hProcess = 0;
  188. if (hProcess == NULL)
  189. {
  190. hProcess = GetCurrentProcess();
  191. BOOL worked = SymInitialize(hProcess, NULL, TRUE);
  192. }
  193. if (nAllocType == _HOOK_ALLOC)
  194. {
  195. for (int i = 0; i < traceCount; i++)
  196. {
  197. /*__try
  198. {
  199. ebp = *((intptr*)ebp + 0);
  200. if (ebp < 0x100000)
  201. break;
  202. eip = *((intptr*)ebp + 1);
  203. }
  204. __except (EXCEPTION_EXECUTE_HANDLER)
  205. {
  206. break;
  207. }*/
  208. intptr curAddr = stackTrace[i];
  209. const char* name = "?";
  210. int hashVal = (curAddr & 0x7FFFFFFF) % CAPTURE_ALLOC_POOL_SIZE;
  211. if (gHashCaptureAllocSize[hashVal] == NULL)
  212. {
  213. //static HPROCESS hProc = GEtProcessH
  214. char symData[4096];
  215. DWORD64 disp = 0;
  216. SYMBOL_INFO* symInfo = (SYMBOL_INFO*)&symData;
  217. memset(symInfo, 0, sizeof(SYMBOL_INFO));
  218. symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
  219. symInfo->MaxNameLen = sizeof(symData) - sizeof(SYMBOL_INFO);
  220. bool foundSym = false;
  221. if (SymFromAddr(hProcess, (DWORD64)curAddr, &disp, symInfo))
  222. {
  223. name = symInfo->Name;
  224. foundSym = true;
  225. }
  226. CaptureAllocLocation* captureAllocLoc = new CaptureAllocLocation();
  227. captureAllocLoc->mSymName = strdup(name);
  228. captureAllocLoc->mTotalSize = 0;
  229. captureAllocLoc->mIsEndpoint = (!foundSym) || (strncmp(name, "Beefy::", 7) == 0) || (strncmp(name, "llvm::", 6) == 0);
  230. if (strstr(name, "operator new") != NULL)
  231. captureAllocLoc->mIsEndpoint = false;
  232. if (strstr(name, "::allocateBuckets") != NULL)
  233. captureAllocLoc->mIsEndpoint = false;
  234. if (strstr(name, "::grow") != NULL)
  235. captureAllocLoc->mIsEndpoint = false;
  236. if (strstr(name, "::DenseMap") != NULL)
  237. captureAllocLoc->mIsEndpoint = false;
  238. /*if (strstr(name, "::Allocate") != NULL)
  239. captureAllocLoc->mIsEndpoint = false;*/
  240. if (strstr(name, "::Alloc") != NULL)
  241. captureAllocLoc->mIsEndpoint = false;
  242. /*if (strstr(name, "::AllocBytes") != NULL)
  243. captureAllocLoc->mIsEndpoint = false;
  244. if (strstr(name, "::AllocMemoryBlock") != NULL)
  245. captureAllocLoc->mIsEndpoint = false;*/
  246. if (strstr(name, "::GrowPool") != NULL)
  247. captureAllocLoc->mIsEndpoint = false;
  248. // Testing COnstantInt::get
  249. if (strstr(name, "::CreateConst") != NULL)
  250. captureAllocLoc->mIsEndpoint = false;
  251. if (strstr(name, "::get") != NULL)
  252. captureAllocLoc->mIsEndpoint = false;
  253. if ((captureAllocLoc->mIsEndpoint) && (foundSym))
  254. {
  255. }
  256. gHashCaptureAllocSize[hashVal] = captureAllocLoc;
  257. }
  258. CaptureAllocLocation* captureAllocLoc = gHashCaptureAllocSize[hashVal];
  259. if ((i < 19) && (!captureAllocLoc->mIsEndpoint))
  260. {
  261. continue;
  262. }
  263. captureAllocLoc->mTotalSize += (int)nSize;
  264. CaptureAllocEntry entry;
  265. entry.mAllocSize = (int)nSize;
  266. entry.mLoc = captureAllocLoc;
  267. gBfCaptureSourceAllocMap[lRequest] = entry;
  268. break;
  269. //if (i >= sCaptureOffset)
  270. //gAllocAddrs[lRequest][i - sCaptureOffset] = eip;
  271. }
  272. }
  273. else if (nAllocType == _HOOK_REALLOC)
  274. {
  275. long oldRequest = ((int*)pvData)[-2];
  276. ReallocEntry(oldRequest, lRequest, nSize);
  277. }
  278. else if (nAllocType == _HOOK_FREE)
  279. {
  280. lRequest = ((int*)pvData)[-2];
  281. RemoveAllocEntry(lRequest);
  282. }
  283. gInsideAlloc = false;
  284. #endif
  285. #ifdef CAPTURE_ALLOC_BACKTRACE
  286. if (lRequest < sNumAllocAddrs)
  287. {
  288. gAllocAddrs[lRequest][0] = 1;
  289. intptr ebpVal;
  290. __asm
  291. {
  292. mov ebpVal, ebp
  293. }
  294. intptr ebp = ebpVal;
  295. intptr eip = 0;
  296. for (int i = 0; i < sCaptureDepth + sCaptureOffset; i++)
  297. {
  298. __try
  299. {
  300. ebp = *((intptr*)ebp + 0);
  301. if (ebp < 0x100000)
  302. break;
  303. eip = *((intptr*)ebp + 1);
  304. }
  305. __except (EXCEPTION_EXECUTE_HANDLER)
  306. {
  307. break;
  308. }
  309. if (i >= sCaptureOffset)
  310. gAllocAddrs[lRequest][i - sCaptureOffset] = eip;
  311. }
  312. }
  313. #else
  314. if (!gBgTrackingAllocs)
  315. return TRUE;
  316. /*AutoCrit critSect(gBfCritSect);
  317. if (gLastReqId == lRequest)
  318. return TRUE;
  319. if (!gInsideAlloc)
  320. {
  321. gInsideAlloc = true;
  322. if (nAllocType == _HOOK_ALLOC)
  323. {
  324. gBfNumAllocs++;
  325. gBfAllocCount += nSize;
  326. gBfAllocMap[lRequest] = nSize;
  327. }
  328. if (nAllocType == _HOOK_FREE)
  329. {
  330. lRequest = ((int*)pvData)[-2];
  331. auto itr = gBfAllocMap.find(lRequest);
  332. if (itr != gBfAllocMap.end())
  333. {
  334. gBfFreeCount += itr->second;
  335. gBfAllocMap.erase(itr);
  336. }
  337. }
  338. gInsideAlloc = false;
  339. }
  340. gLastReqId = lRequest;
  341. if (szFileName == NULL)
  342. return TRUE; */
  343. /*char str[1024];
  344. sprintf(str, "Alloc: %d File: %s Line: %d\n", lRequest, szFileName, nLine);
  345. OutputDebugStringA(str);*/
  346. #endif
  347. return TRUE;
  348. }
  349. #endif //BF_PLATFORM_WINDOWS
  350. void BfReportMemory()
  351. {
  352. BfLogDbg("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0));
  353. }
  354. void BfFullReportMemory()
  355. {
  356. /*OutputDebugStrF("Testing OOB\n");
  357. char* str = new char[12];
  358. delete str;
  359. char c = str[1];*/
  360. if (gBfParserCache != NULL)
  361. {
  362. MemReporter memReporter;
  363. memReporter.BeginSection("ParserCache");
  364. gBfParserCache->ReportMemory(&memReporter);
  365. memReporter.EndSection();
  366. memReporter.Report();
  367. }
  368. OutputDebugStrF("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0));
  369. OutputDebugStrF("ChunkedDataBuffer allocated blocks: %d\n", ChunkedDataBuffer::sBlocksAllocated);
  370. if (gDebugManager != NULL)
  371. {
  372. MemReporter memReporter;
  373. if (gDebugManager->mDebugger32 != NULL)
  374. {
  375. memReporter.BeginSection("Debugger32");
  376. gDebugManager->mDebugger32->ReportMemory(&memReporter);
  377. memReporter.EndSection();
  378. }
  379. memReporter.BeginSection("Debugger64");
  380. gDebugManager->mDebugger64->ReportMemory(&memReporter);
  381. memReporter.EndSection();
  382. memReporter.Report();
  383. }
  384. BpDump();
  385. #ifdef CAPTURE_ALLOC_SOURCES
  386. int memTotal = 0;
  387. std::map<String, int> byNameMap;
  388. for (int i = 0; i < CAPTURE_ALLOC_POOL_SIZE; i++)
  389. {
  390. CaptureAllocLocation* allocLoc = gHashCaptureAllocSize[i];
  391. if ((allocLoc != NULL) && (allocLoc->mTotalSize > 0))
  392. {
  393. auto itr = byNameMap.insert(std::map<String, int>::value_type(allocLoc->mSymName, 0));
  394. itr.first->second += allocLoc->mTotalSize;
  395. memTotal += allocLoc->mTotalSize;
  396. }
  397. }
  398. std::multimap<int, String> bySizeMap;
  399. for (auto kv : byNameMap)
  400. {
  401. //OutputDebugStrF("%dk %s\n", (kv.second + 1023) / 1024, kv.first.c_str());
  402. bySizeMap.insert(std::multimap<int, String>::value_type(-kv.second, kv.first));
  403. }
  404. for (auto kv : bySizeMap)
  405. {
  406. OutputDebugStrF("%dk %s\n", (-kv.first + 1023) / 1024, kv.second.c_str());
  407. }
  408. OutputDebugStrF("Total %dk\n", memTotal / 1024);
  409. #endif
  410. }
  411. struct _CrtMemBlockHeader
  412. {
  413. _CrtMemBlockHeader* _block_header_next;
  414. _CrtMemBlockHeader* _block_header_prev;
  415. char const* _file_name;
  416. int _line_number;
  417. int _block_use;
  418. size_t _data_size;
  419. long _request_number;
  420. //unsigned char _gap[no_mans_land_size];
  421. // Followed by:
  422. // unsigned char _data[_data_size];
  423. // unsigned char _another_gap[no_mans_land_size];
  424. };
  425. //static _CrtMemBlockHeader* __acrt_first_block;
  426. //static _CrtMemBlockHeader* __acrt_last_block;
  427. void ShowMemoryUsage()
  428. {
  429. #ifdef BF_PLATFORM_WINDOWS
  430. PROCESS_MEMORY_COUNTERS processMemCounters;
  431. processMemCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS);
  432. GetProcessMemoryInfo(GetCurrentProcess(), &processMemCounters, sizeof(PROCESS_MEMORY_COUNTERS));
  433. OutputDebugStrF("WorkingSet : %dk\n", (int)(processMemCounters.WorkingSetSize / 1024));
  434. OutputDebugStrF("VirtualMem : %dk\n", (int)(processMemCounters.PagefileUsage/1024));
  435. static bool hasCheckpoint = true;
  436. _CrtMemState memState;
  437. _CrtMemCheckpoint(&memState);
  438. //OutputDebugStrF("Crt Size: %dk\n", (int)(memState.lTotalCount / 1024));
  439. char* names[6] = { "_FREE_BLOCK", "_NORMAL_BLOCK", "_CRT_BLOCK", "_IGNORE_BLOCK", "_CLIENT_BLOCK", "_MAX_BLOCKS" };
  440. for (int i = 0; i < 5; i++)
  441. {
  442. OutputDebugStrF("%s : %d %dk\n", names[i], memState.lCounts[i], memState.lSizes[i] / 1024);
  443. }
  444. #ifdef _DEBUG
  445. // int64 totalCrtSize = 0;
  446. // int64 totalUseCrtSize = 0;
  447. // _CrtMemBlockHeader* blockPtr = memState.pBlockHeader;
  448. // while (blockPtr != NULL)
  449. // {
  450. // totalCrtSize += blockPtr->_data_size;
  451. // if (blockPtr->_block_use != _FREE_BLOCK)
  452. // totalUseCrtSize += blockPtr->_data_size;
  453. // blockPtr = blockPtr->_block_header_next;
  454. // }
  455. // OutputDebugStrF("Crt Size: %dk Used: %dk\n", (int)(totalCrtSize / 1024), (int)(totalUseCrtSize / 1024));
  456. #endif
  457. _HEAPINFO heapInfo = {0};
  458. int64 heapSize = 0;
  459. int heapStatus;
  460. while ((heapStatus = _heapwalk(&heapInfo)) == _HEAPOK)
  461. {
  462. heapSize += (int64)heapInfo._size;
  463. }
  464. OutputDebugStrF("WALKED HEAP SIZE: %dk\n", heapSize / 1024);
  465. //_CrtMemDumpStatistics(&memState);
  466. #endif
  467. }
  468. /*void* TestHeapAlloc(HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes)
  469. {
  470. return HeapAlloc(hHeap, dwFlags, dwBytes);
  471. }*/
  472. static void BfFatalErrorHandler(void *user_data, const std::string& reason, bool gen_crash_diag)
  473. {
  474. BF_FATAL(reason.c_str());
  475. OutputDebugStrF("LLVM ERROR: %s\n", reason.c_str());
  476. }
  477. #ifdef BF_PLATFORM_WINDOWS
  478. BOOL WINAPI DllMain(
  479. HANDLE hDllHandle,
  480. DWORD dwReason,
  481. LPVOID lpreserved)
  482. {
  483. if (dwReason == DLL_PROCESS_ATTACH)
  484. {
  485. BpInit("127.0.0.1", "Beef IDE");
  486. BpSetThreadName("Main");
  487. BfpThread_SetName(NULL, "Main", NULL);
  488. llvm::install_fatal_error_handler(BfFatalErrorHandler, NULL);
  489. //_CRTDBG_CHECK_EVERY_16_DF
  490. //_CRTDBG_CHECK_ALWAYS_DF
  491. //_CRTDBG_DELAY_FREE_MEM_DF
  492. //_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_ALWAYS_DF*/);
  493. _CrtSetAllocHook(BfAllocHook);
  494. }
  495. if (dwReason == -123)
  496. {
  497. BpDump();
  498. }
  499. return TRUE;
  500. }
  501. #endif //BF_PLATFORM_WINDOWS
  502. //////
  503. void SleepTest()
  504. {
  505. BfpThread_Sleep(3000);
  506. }
  507. void WdAllocTest();
  508. #ifdef BF_PLATFORM_WINDOWS
  509. static _CrtMemState gStartMemCheckpoint;
  510. #endif
  511. BF_EXPORT void BF_CALLTYPE Debugger_Create()
  512. {
  513. //TODO: Very slow, remove
  514. //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF);
  515. //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_EVERY_16_DF);
  516. //TODO: _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_EVERY_16_DF*/);
  517. //_CrtSetAllocHook(BfAllocHook);
  518. #ifdef BF_PLATFORM_WINDOWS
  519. _CrtMemCheckpoint(&gStartMemCheckpoint);
  520. #endif
  521. //_CrtSetBreakAlloc(621);
  522. gDebugManager = new DebugManager();
  523. #ifdef ENABLE_DBG_32
  524. gDebugManager->mDebugger32 = CreateDebugger32(gDebugManager, NULL);
  525. #else
  526. gDebugManager->mDebugger32 = NULL;
  527. #endif
  528. #ifdef BF32
  529. gDebugManager->mDebugger64 = NULL;
  530. #else
  531. gDebugManager->mDebugger64 = CreateDebugger64(gDebugManager, NULL);
  532. #endif
  533. #ifdef BF_PLATFORM_WINDOWS
  534. ::AllowSetForegroundWindow(ASFW_ANY);
  535. #endif
  536. }
  537. BF_EXPORT void BF_CALLTYPE Debugger_SetCallbacks(void* callback)
  538. {
  539. }
  540. BF_EXPORT void BF_CALLTYPE Debugger_FullReportMemory()
  541. {
  542. //WdAllocTest();
  543. ShowMemoryUsage();
  544. BfFullReportMemory();
  545. }
  546. BF_EXPORT void BF_CALLTYPE Debugger_Delete()
  547. {
  548. delete gDebugManager;
  549. gDebugManager = NULL;
  550. delete gPerfManager;
  551. gPerfManager = NULL;
  552. //OutputDebugStrF("Deleting Debugger\n");
  553. //BfReportMemory();
  554. #ifdef BF_PLATFORM_WINDOWS
  555. gBgTrackingAllocs = false;
  556. #endif
  557. }
  558. BF_EXPORT void BF_CALLTYPE IDEHelper_ProgramStart()
  559. {
  560. BfIRCodeGen::StaticInit();
  561. }
  562. BF_EXPORT void BF_CALLTYPE IDEHelper_ProgramDone()
  563. {
  564. //TODO:
  565. //::MessageBoxA(NULL, "Done", "Done", MB_OK);
  566. BF_ASSERT(gDebugger == NULL);
  567. //ShowMemoryUsage();
  568. //BfFullReportMemory();
  569. #ifdef CAPTURE_ALLOC_SOURCES
  570. gInsideAlloc = true;
  571. for (int i = 0; i < CAPTURE_ALLOC_POOL_SIZE; i++)
  572. {
  573. if (gHashCaptureAllocSize[i] != NULL)
  574. {
  575. free(gHashCaptureAllocSize[i]->mSymName);
  576. delete gHashCaptureAllocSize[i];
  577. gHashCaptureAllocSize[i] = NULL;
  578. }
  579. }
  580. gBfCaptureSourceAllocMap.clear();
  581. #endif
  582. #ifdef BF_PLATFORM_WINDOWS
  583. _CrtMemDumpAllObjectsSince(&gStartMemCheckpoint);
  584. /*_CrtMemState curMemCheckpoint;
  585. _CrtMemCheckpoint(&curMemCheckpoint);
  586. _CrtMemState memDiff;
  587. if (_CrtMemDifference(&memDiff, &gStartMemCheckpoint, &curMemCheckpoint))
  588. _CrtMemDumpStatistics(&memDiff);*/
  589. _CrtMemState curMemCheckpoint = { 0 };
  590. _CrtMemCheckpoint(&curMemCheckpoint);
  591. OutputDebugStrF("Heap memory usage: %dk\n", curMemCheckpoint.lTotalCount / 1024);
  592. #endif //BF_PLATFORM_WINDOWS
  593. BpShutdown();
  594. }
  595. BF_EXPORT int BF_CALLTYPE Debugger_GetAddrSize()
  596. {
  597. if (gDebugger == NULL)
  598. return 0;
  599. return gDebugger->GetAddrSize();
  600. }
  601. BF_EXPORT bool BF_CALLTYPE Debugger_OpenFile(const char* launchPath, const char* targetPath, const char* args, const char* workingDir, void* envBlockPtr, int envBlockSize)
  602. {
  603. BF_ASSERT(gDebugger == NULL);
  604. if (!FileExists(launchPath))
  605. {
  606. gDebugManager->mOutMessages.push_back(StrFormat("error Unable to locate specified launch target '%s'", launchPath));
  607. return false;
  608. }
  609. DebuggerResult debuggerResult = DebuggerResult_Ok;
  610. if ((gDebugManager->mDebugger64 != NULL) && (gDebugManager->mDebugger64->CanOpen(launchPath, &debuggerResult)))
  611. gDebugger = gDebugManager->mDebugger64;
  612. else
  613. gDebugger = gDebugManager->mDebugger32;
  614. if (gDebugger == NULL)
  615. {
  616. if (debuggerResult == DebuggerResult_WrongBitSize)
  617. gDebugManager->mOutMessages.push_back(StrFormat("error The file 32-bit file '%s' cannot be debugged because 32-bit debugger has been disabled", launchPath));
  618. return false;
  619. }
  620. Array<uint8> envBlock;
  621. if (envBlockPtr != NULL)
  622. {
  623. if (envBlockSize != 0)
  624. envBlock.Insert(0, (uint8*)envBlockPtr, envBlockSize);
  625. }
  626. gDebugger->OpenFile(launchPath, targetPath, args, workingDir, envBlock);
  627. return true;
  628. }
  629. BF_EXPORT void BF_CALLTYPE Debugger_SetSymSrvOptions(const char* symCacheDir, const char* symSrvStr, int flags)
  630. {
  631. Array<String> symServers;
  632. const char* startStr = symSrvStr;
  633. for (const char* cPtr = symSrvStr; true; cPtr++)
  634. {
  635. if ((*cPtr == '\n') || (*cPtr == 0))
  636. {
  637. String symStr = String(startStr, cPtr - startStr);
  638. symStr.Trim();
  639. if (symStr.EndsWith('/'))
  640. symStr.Remove((int)symStr.length() - 1, 1);
  641. if (!symStr.IsEmpty())
  642. symServers.Add(symStr);
  643. startStr = cPtr;
  644. }
  645. if (*cPtr == 0)
  646. break;
  647. }
  648. AutoCrit autoCrit(gDebugManager->mCritSect);
  649. gDebugManager->mSymSrvOptions.mCacheDir = symCacheDir;
  650. gDebugManager->mSymSrvOptions.mSymbolServers = symServers;
  651. gDebugManager->mSymSrvOptions.mFlags = (BfSymSrvFlags)flags;
  652. gDebugManager->mSymSrvOptions.mCacheDir.Trim();
  653. if (gDebugManager->mSymSrvOptions.mCacheDir.IsEmpty())
  654. gDebugManager->mSymSrvOptions.mFlags = BfSymSrvFlag_Disable;
  655. if (flags & BfSymSrvFlag_TempCache)
  656. {
  657. if (!gDebugManager->mSymSrvOptions.mCacheDir.IsEmpty())
  658. {
  659. gDebugManager->mSymSrvOptions.mCacheDir.Append("\\temp");
  660. RecursiveDeleteDirectory(gDebugManager->mSymSrvOptions.mCacheDir);
  661. }
  662. }
  663. gDebugManager->SetSourceServerCacheDir();
  664. }
  665. BF_EXPORT bool BF_CALLTYPE Debugger_OpenMiniDump(const char* fileName)
  666. {
  667. #ifdef BF_PLATFORM_WINDOWS
  668. DbgMiniDump* dbgMiniDump = new DbgMiniDump();
  669. bool result = dbgMiniDump->StartLoad(fileName);
  670. if (!result)
  671. {
  672. delete dbgMiniDump;
  673. return false;
  674. }
  675. if (dbgMiniDump->GetTargetBitCount() == 32)
  676. gDebugger = CreateDebugger32(gDebugManager, dbgMiniDump);
  677. else
  678. gDebugger = CreateDebugger64(gDebugManager, dbgMiniDump);
  679. return result;
  680. #else //BF_PLATFORM_WINDOWS
  681. return false;
  682. #endif
  683. }
  684. BF_EXPORT bool BF_CALLTYPE Debugger_Attach(int processId, BfDbgAttachFlags attachFlags)
  685. {
  686. BF_ASSERT(gDebugger == NULL);
  687. if (gDebugManager->mDebugger64->Attach(processId, attachFlags))
  688. {
  689. gDebugger = gDebugManager->mDebugger64;
  690. return true;
  691. }
  692. if (gDebugManager->mDebugger32->Attach(processId, attachFlags))
  693. {
  694. gDebugger = gDebugManager->mDebugger32;
  695. return true;
  696. }
  697. return false;
  698. }
  699. BF_EXPORT void BF_CALLTYPE Debugger_Run()
  700. {
  701. gDebugger->Run();
  702. }
  703. BF_EXPORT bool BF_CALLTYPE Debugger_HotLoad(const char* fileNamesStr, int hotIdx)
  704. {
  705. //DbgModule* dwarf = new DbgModule(gDebugger);
  706. //dwarf->ReadPE(fileName);
  707. Array<String> fileNames;
  708. const char* curPtr = fileNamesStr;
  709. for (int i = 0; true; i++)
  710. {
  711. if ((fileNamesStr[i] == '\0') || (fileNamesStr[i] == '\n'))
  712. {
  713. String curFileName = String(curPtr, fileNamesStr + i);
  714. if ((curFileName.IndexOf("/vdata.") != -1) || (curFileName.IndexOf("\\vdata.") != -1))
  715. {
  716. // Do vdata first - so new data and special functions don't have to be deferred resolved
  717. fileNames.Insert(0, curFileName);
  718. }
  719. else
  720. fileNames.Add(curFileName);
  721. curPtr = fileNamesStr + i + 1;
  722. }
  723. if (fileNamesStr[i] == '\0')
  724. break;
  725. }
  726. gDebugger->HotLoad(fileNames, hotIdx);
  727. return true;
  728. }
  729. BF_EXPORT bool BF_CALLTYPE Debugger_LoadDebugVisualizers(const char* fileName)
  730. {
  731. String fn = fileName;
  732. bool worked = false;
  733. worked = gDebugManager->mDebugVisualizers->Load(fileName);
  734. if (!gDebugManager->mDebugVisualizers->mErrorString.empty())
  735. {
  736. gDebugManager->mOutMessages.push_back(StrFormat("msg ERROR: %s\n", gDebugManager->mDebugVisualizers->mErrorString.c_str()));
  737. }
  738. // {
  739. // BF_FATAL(gDebugManager->mDebugVisualizers->mErrorString.c_str());
  740. // }
  741. return worked;
  742. }
  743. BF_EXPORT void BF_CALLTYPE Debugger_StopDebugging()
  744. {
  745. gDebugger->StopDebugging();
  746. }
  747. BF_EXPORT void BF_CALLTYPE Debugger_Terminate()
  748. {
  749. gDebugger->Terminate();
  750. }
  751. BF_EXPORT void BF_CALLTYPE Debugger_Detach()
  752. {
  753. gDebugManager->mNetManager->CancelAll();
  754. gDebugger->Detach();
  755. if (gDebugger->IsOnDemandDebugger())
  756. delete gDebugger;
  757. gDebugger = NULL;
  758. gDebugManager->mNetManager->Clear();
  759. }
  760. BF_EXPORT Breakpoint* BF_CALLTYPE Debugger_CreateBreakpoint(const char* fileName, int lineNum, int wantColumn, int instrOffset)
  761. {
  762. return gDebugger->CreateBreakpoint(fileName, lineNum, wantColumn, instrOffset);
  763. }
  764. BF_EXPORT Breakpoint* BF_CALLTYPE Debugger_CreateMemoryBreakpoint(intptr address, int byteCount)
  765. {
  766. return gDebugger->CreateMemoryBreakpoint(address, byteCount);
  767. }
  768. BF_EXPORT Breakpoint* BF_CALLTYPE Debugger_CreateSymbolBreakpoint(const char* symbolName)
  769. {
  770. return gDebugger->CreateSymbolBreakpoint(symbolName);
  771. }
  772. BF_EXPORT Breakpoint* BF_CALLTYPE Debugger_CreateAddressBreakpoint(intptr address)
  773. {
  774. return gDebugger->CreateAddressBreakpoint(address);
  775. }
  776. BF_EXPORT Breakpoint* BF_CALLTYPE Debugger_GetActiveBreakpoint()
  777. {
  778. return gDebugger->GetActiveBreakpoint();
  779. }
  780. BF_EXPORT void BF_CALLTYPE Breakpoint_Delete(Breakpoint* wdBreakpoint)
  781. {
  782. gDebugger->DeleteBreakpoint(wdBreakpoint);
  783. }
  784. BF_EXPORT void BF_CALLTYPE Breakpoint_Check(Breakpoint* breakpoint)
  785. {
  786. gDebugger->CheckBreakpoint(breakpoint);
  787. }
  788. BF_EXPORT int BF_CALLTYPE Breakpoint_GetPendingHotBindIdx(Breakpoint* breakpoint)
  789. {
  790. return breakpoint->mPendingHotBindIdx;
  791. }
  792. BF_EXPORT void BF_CALLTYPE Breakpoint_HotBindBreakpoint(Breakpoint* breakpoint, int lineNum, int hotIdx)
  793. {
  794. gDebugger->HotBindBreakpoint(breakpoint, lineNum, hotIdx);
  795. }
  796. BF_EXPORT void BF_CALLTYPE Breakpoint_SetThreadId(Breakpoint* breakpoint, intptr threadId)
  797. {
  798. BfLogDbg("Breakpoint %p set ThreadId=%d\n", breakpoint, threadId);
  799. breakpoint->mThreadId = threadId;
  800. gDebugger->CheckBreakpoint(breakpoint);
  801. }
  802. BF_EXPORT int BF_CALLTYPE Breakpoint_GetHitCount(Breakpoint* breapoint)
  803. {
  804. return breapoint->mHitCount;
  805. }
  806. BF_EXPORT void BF_CALLTYPE Breakpoint_ClearHitCount(Breakpoint* breapoint)
  807. {
  808. breapoint->mHitCount = 0;
  809. }
  810. BF_EXPORT void BF_CALLTYPE Breakpoint_SetHitCountTarget(Breakpoint* breakpoint, int targetHitCount, DbgHitCountBreakKind breakKind)
  811. {
  812. breakpoint->mTargetHitCount = targetHitCount;
  813. breakpoint->mHitCountBreakKind = breakKind;
  814. }
  815. BF_EXPORT void BF_CALLTYPE Breakpoint_SetCondition(Breakpoint* wdBreakpoint, const char* condition)
  816. {
  817. gDebugger->SetBreakpointCondition(wdBreakpoint, condition);
  818. }
  819. BF_EXPORT void BF_CALLTYPE Breakpoint_SetLogging(Breakpoint* wdBreakpoint, const char* logging, bool breakAfterLogging)
  820. {
  821. gDebugger->SetBreakpointLogging(wdBreakpoint, logging, breakAfterLogging);
  822. }
  823. BF_EXPORT uintptr BF_CALLTYPE Breakpoint_GetAddress(Breakpoint* wdBreakpoint, Breakpoint** outLinkedSibling)
  824. {
  825. if (outLinkedSibling != NULL)
  826. *outLinkedSibling = wdBreakpoint->mLinkedSibling;
  827. return wdBreakpoint->GetAddr();
  828. }
  829. BF_EXPORT bool BF_CALLTYPE Breakpoint_IsMemoryBreakpointBound(Breakpoint* wdBreakpoint)
  830. {
  831. return wdBreakpoint->IsMemoryBreakpointBound();
  832. }
  833. BF_EXPORT intptr BF_CALLTYPE Breakpoint_GetLineNum(Breakpoint* wdBreakpoint)
  834. {
  835. return wdBreakpoint->mLineNum;
  836. }
  837. BF_EXPORT void BF_CALLTYPE Breakpoint_Move(Breakpoint* breakpoint, int lineNum, int wantColumn, bool rebindNow)
  838. {
  839. gDebugger->MoveBreakpoint(breakpoint, lineNum, wantColumn, rebindNow);
  840. }
  841. BF_EXPORT void BF_CALLTYPE Breakpoint_MoveMemoryBreakpoint(Breakpoint* breakpoint, intptr addr, int byteCount)
  842. {
  843. gDebugger->MoveMemoryBreakpoint(breakpoint, addr, byteCount);
  844. }
  845. BF_EXPORT void BF_CALLTYPE Breakpoint_Disable(Breakpoint* wdBreakpoint)
  846. {
  847. gDebugger->DisableBreakpoint(wdBreakpoint);
  848. }
  849. BF_EXPORT void BF_CALLTYPE Debugger_CreateStepFilter(const char* filter, bool isGlobal, BfStepFilterKind filterKind)
  850. {
  851. AutoCrit autoCrit(gDebugManager->mCritSect);
  852. StepFilter stepFilter;
  853. stepFilter.mFilterKind = filterKind;
  854. gDebugManager->mStepFilters[filter] = stepFilter;
  855. gDebugManager->mStepFilterVersion++;
  856. }
  857. BF_EXPORT void BF_CALLTYPE StepFilter_Delete(const char* filter)
  858. {
  859. AutoCrit autoCrit(gDebugManager->mCritSect);
  860. bool didRemove = gDebugManager->mStepFilters.Remove(filter);
  861. BF_ASSERT(didRemove);
  862. gDebugManager->mStepFilterVersion++;
  863. }
  864. BF_EXPORT int BF_CALLTYPE Debugger_GetRunState()
  865. {
  866. AutoCrit autoCrit(gDebugManager->mCritSect);
  867. if (gDebugger == NULL)
  868. return RunState_NotStarted;
  869. return gDebugger->mRunState;
  870. }
  871. BF_EXPORT bool BF_CALLTYPE Debugger_HasPendingDebugLoads()
  872. {
  873. if (gDebugger == NULL)
  874. return false;
  875. return gDebugger->HasPendingDebugLoads();
  876. }
  877. BF_EXPORT const char* BF_CALLTYPE Debugger_PopMessage()
  878. {
  879. AutoCrit autoCrit(gDebugManager->mCritSect);
  880. if (gDebugManager->mOutMessages.size() == 0)
  881. return NULL;
  882. String& outString = *gTLStrReturn.Get();
  883. outString = gDebugManager->mOutMessages.front();
  884. gDebugManager->mOutMessages.pop_front();
  885. //gDebugManager->mOutMessages.erase(gDebugManager->mOutMessages.begin());
  886. return outString.c_str();
  887. }
  888. BF_EXPORT bool BF_CALLTYPE Debugger_HasMessages()
  889. {
  890. AutoCrit autoCrit(gDebugManager->mCritSect);
  891. return gDebugManager->mOutMessages.size() != 0;
  892. }
  893. BF_EXPORT const char* BF_CALLTYPE Debugger_GetCurrentException()
  894. {
  895. /*outString = StrFormat("Exception at 0x%p, exception code 0x%08X",
  896. gDebugger->mCurException.ExceptionAddress, gDebugger->mCurException.ExceptionCode);*/
  897. String& outString = *gTLStrReturn.Get();
  898. outString = gDebugger->GetCurrentException();
  899. return outString.c_str();
  900. }
  901. BF_EXPORT void BF_CALLTYPE Debugger_BreakAll()
  902. {
  903. if (gDebugger != NULL)
  904. gDebugger->BreakAll();
  905. }
  906. BF_EXPORT void BF_CALLTYPE Debugger_Continue()
  907. {
  908. BfLogDbg("Debugger_Continue\n");
  909. gDebugger->ContinueDebugEvent();
  910. }
  911. BF_EXPORT void BF_CALLTYPE Debugger_StepInto(bool inAssembly)
  912. {
  913. gDebugger->StepInto(inAssembly);
  914. }
  915. BF_EXPORT void BF_CALLTYPE Debugger_StepIntoSpecific(intptr addr)
  916. {
  917. gDebugger->StepIntoSpecific(addr);
  918. }
  919. BF_EXPORT void BF_CALLTYPE Debugger_StepOver(bool inAssembly)
  920. {
  921. gDebugger->StepOver(inAssembly);
  922. }
  923. BF_EXPORT void BF_CALLTYPE Debugger_StepOut(bool inAssembly)
  924. {
  925. gDebugger->StepOut(inAssembly);
  926. }
  927. BF_EXPORT void BF_CALLTYPE Debugger_SetNextStatement(bool inAssembly, const char* fileName, int64 wantLineNumOrAsmAddr, int wantColumn)
  928. {
  929. if (fileName == NULL)
  930. fileName = "";
  931. gDebugger->SetNextStatement(inAssembly, fileName, wantLineNumOrAsmAddr, wantColumn);
  932. }
  933. BF_EXPORT void BF_CALLTYPE Debugger_Update()
  934. {
  935. if (gDebugger != NULL)
  936. gDebugger->Update();
  937. }
  938. BF_EXPORT void BF_CALLTYPE Debugger_SetDisplayTypes(const char* referenceId, int8 intDisplayType, int8 mmDisplayType, int8 floatDisplayType)
  939. {
  940. DwDisplayInfo displayInfo;
  941. displayInfo.mIntDisplayType = (DwIntDisplayType)intDisplayType;
  942. displayInfo.mMmDisplayType = (DwMmDisplayType)mmDisplayType;
  943. displayInfo.mFloatDisplayType = (DwFloatDisplayType)floatDisplayType;
  944. if (referenceId == NULL)
  945. {
  946. gDebugManager->mDefaultDisplayInfo = displayInfo;
  947. }
  948. else if ((displayInfo.mIntDisplayType == DwIntDisplayType_Default) &&
  949. (displayInfo.mMmDisplayType == DwMmDisplayType_Default) &&
  950. (displayInfo.mFloatDisplayType == DwFloatDisplayType_Default))
  951. {
  952. gDebugManager->mDisplayInfos.Remove(referenceId);
  953. }
  954. else
  955. {
  956. gDebugManager->mDisplayInfos[referenceId] = displayInfo;
  957. }
  958. }
  959. BF_EXPORT bool BF_CALLTYPE Debugger_GetDisplayTypes(const char* referenceId, int8* intDisplayType, int8* mmDisplayType, int8* floatDisplayType)
  960. {
  961. bool foundSpecific = false;
  962. DwDisplayInfo* displayInfo = &gDebugManager->mDefaultDisplayInfo;
  963. if (referenceId != NULL)
  964. {
  965. /*auto itr = gDebugManager->mDisplayInfos.find(referenceId);
  966. if (itr != gDebugManager->mDisplayInfos.end())
  967. {
  968. displayInfo = &itr->second;
  969. foundSpecific = true;
  970. }*/
  971. if (gDebugManager->mDisplayInfos.TryGetValue(referenceId, &displayInfo))
  972. {
  973. foundSpecific = true;
  974. }
  975. }
  976. *intDisplayType = (int8)displayInfo->mIntDisplayType;
  977. *mmDisplayType = (int8)displayInfo->mMmDisplayType;
  978. *floatDisplayType = (int8)displayInfo->mFloatDisplayType;
  979. return foundSpecific;
  980. }
  981. BF_EXPORT const char* BF_CALLTYPE Debugger_GetDisplayTypeNames()
  982. {
  983. String& outString = *gTLStrReturn.Get();
  984. outString.clear();
  985. for (auto& displayInfoEntry : gDebugManager->mDisplayInfos)
  986. {
  987. outString += displayInfoEntry.mKey + "\n";
  988. }
  989. return outString.c_str();
  990. }
  991. BF_EXPORT const char* BF_CALLTYPE Debugger_EvaluateContinue()
  992. {
  993. auto debugger = gDebugger;
  994. String& outString = *gTLStrReturn.Get();
  995. outString = debugger->EvaluateContinue();
  996. return outString.c_str();
  997. }
  998. BF_EXPORT void BF_CALLTYPE Debugger_EvaluateContinueKeep()
  999. {
  1000. auto debugger = gDebugger;
  1001. debugger->EvaluateContinueKeep();
  1002. }
  1003. BF_EXPORT StringView BF_CALLTYPE Debugger_Evaluate(const char* expr, int callStackIdx, int cursorPos, int32 language, uint16 expressionFlags)
  1004. {
  1005. auto debugger = gDebugger;
  1006. if (debugger == NULL)
  1007. debugger = gDebugManager->mDebugger64;
  1008. String& outString = *gTLStrReturn.Get();
  1009. outString.clear();
  1010. outString = debugger->Evaluate(expr, callStackIdx, cursorPos, language, (DwEvalExpressionFlags)expressionFlags);
  1011. #ifdef BF_WANTS_LOG_DBG
  1012. {
  1013. int crPos = (int)outString.IndexOf('\n');
  1014. if (crPos != -1)
  1015. BfLogDbg("Debugger_Evaluate Result=%s\n", outString.Substring(0, crPos).c_str());
  1016. else
  1017. BfLogDbg("Debugger_Evaluate Result=%s\n", outString.c_str());
  1018. }
  1019. #endif
  1020. return outString;
  1021. }
  1022. BF_EXPORT const char* BF_CALLTYPE Debugger_EvaluateToAddress(const char* expr, int callStackIdx, int cursorPos)
  1023. {
  1024. String& outString = *gTLStrReturn.Get();
  1025. outString.clear();
  1026. if (gDebugger != NULL)
  1027. outString = gDebugger->EvaluateToAddress(expr, callStackIdx, cursorPos);
  1028. return outString.c_str();
  1029. }
  1030. BF_EXPORT const char* BF_CALLTYPE Debugger_EvaluateAtAddress(const char* expr, intptr atAddr, int cursorPos)
  1031. {
  1032. String& outString = *gTLStrReturn.Get();
  1033. outString.clear();
  1034. if (gDebugger != NULL)
  1035. outString = gDebugger->EvaluateAtAddress(expr, atAddr, cursorPos);
  1036. return outString.c_str();
  1037. }
  1038. BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
  1039. {
  1040. String& outString = *gTLStrReturn.Get();
  1041. outString = gDebugger->GetAutoExpressions(callStackIdx, memoryRangeStart, memoryRangeLen);
  1042. return outString.c_str();
  1043. }
  1044. BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoLocals(int callStackIdx, bool showRegs)
  1045. {
  1046. String& outString = *gTLStrReturn.Get();
  1047. outString = gDebugger->GetAutoLocals(callStackIdx, showRegs);
  1048. return outString.c_str();
  1049. }
  1050. BF_EXPORT const char* BF_CALLTYPE Debugger_CompactChildExpression(const char* expr, const char* parentExpr, int callStackIdx)
  1051. {
  1052. String& outString = *gTLStrReturn.Get();
  1053. outString = gDebugger->CompactChildExpression(expr, parentExpr, callStackIdx);
  1054. return outString.c_str();
  1055. }
  1056. BF_EXPORT const char* BF_CALLTYPE Debugger_GetCollectionContinuation(const char* continuationData, int callStackIdx, int count)
  1057. {
  1058. String& outString = *gTLStrReturn.Get();
  1059. outString = gDebugger->GetCollectionContinuation(continuationData, callStackIdx, count);
  1060. return outString.c_str();
  1061. }
  1062. BF_EXPORT void BF_CALLTYPE Debugger_ForegroundTarget()
  1063. {
  1064. gDebugger->ForegroundTarget();
  1065. //BOOL worked = EnumThreadWindows(gDebugger->mProcessInfo.dwThreadId, WdEnumWindowsProc, 0);
  1066. //BF_ASSERT(worked);
  1067. }
  1068. BF_EXPORT const char* BF_CALLTYPE Debugger_GetProcessInfo()
  1069. {
  1070. String& outString = *gTLStrReturn.Get();
  1071. outString = gDebugger->GetProcessInfo();
  1072. return outString.c_str();
  1073. }
  1074. BF_EXPORT const char* BF_CALLTYPE Debugger_GetThreadInfo()
  1075. {
  1076. String& outString = *gTLStrReturn.Get();
  1077. outString = gDebugger->GetThreadInfo();
  1078. return outString.c_str();
  1079. }
  1080. BF_EXPORT void BF_CALLTYPE Debugger_SetActiveThread(int threadId)
  1081. {
  1082. gDebugger->SetActiveThread(threadId);
  1083. }
  1084. BF_EXPORT int BF_CALLTYPE Debugger_GetActiveThread()
  1085. {
  1086. return gDebugger->GetActiveThread();
  1087. }
  1088. BF_EXPORT void BF_CALLTYPE Debugger_FreezeThread(int threadId)
  1089. {
  1090. gDebugger->FreezeThread(threadId);
  1091. }
  1092. BF_EXPORT void BF_CALLTYPE Debugger_ThawThread(int threadId)
  1093. {
  1094. gDebugger->ThawThread(threadId);
  1095. }
  1096. BF_EXPORT bool BF_CALLTYPE Debugger_IsActiveThreadWaiting()
  1097. {
  1098. return gDebugger->IsActiveThreadWaiting();
  1099. }
  1100. BF_EXPORT void BF_CALLTYPE CallStack_Update()
  1101. {
  1102. gDebugger->UpdateCallStack();
  1103. }
  1104. BF_EXPORT void BF_CALLTYPE CallStack_Rehup()
  1105. {
  1106. AutoCrit autoCrit(gDebugManager->mCritSect);
  1107. gDebugger->ClearCallStack();
  1108. }
  1109. BF_EXPORT int BF_CALLTYPE CallStack_GetCount()
  1110. {
  1111. return gDebugger->GetCallStackCount();
  1112. }
  1113. BF_EXPORT int BF_CALLTYPE CallStack_GetRequestedStackFrameIdx()
  1114. {
  1115. return gDebugger->GetRequestedStackFrameIdx();
  1116. }
  1117. BF_EXPORT int BF_CALLTYPE CallStack_GetBreakStackFrameIdx()
  1118. {
  1119. return gDebugger->GetBreakStackFrameIdx();
  1120. }
  1121. BF_EXPORT const char* BF_CALLTYPE CallStack_GetStackFrameInfo(int stackFrameIdx, intptr* addr, const char** outFile, int32* outHotIdx, int32* outDefLineStart, int32* outDefLineEnd,
  1122. int32* outLine, int32* outColumn, int32* outLanguage, int32* outStackSize, int8* outFlags)
  1123. {
  1124. String& outString = *gTLStrReturn.Get();
  1125. String& outString2 = *gTLStrReturn2.Get();
  1126. outString = gDebugger->GetStackFrameInfo(stackFrameIdx, addr, &outString2, outHotIdx, outDefLineStart, outDefLineEnd, outLine, outColumn, outLanguage, outStackSize, outFlags);
  1127. *outFile = outString2.c_str();
  1128. return outString.c_str();
  1129. }
  1130. BF_EXPORT const char* BF_CALLTYPE Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
  1131. {
  1132. String& outString = *gTLStrReturn.Get();
  1133. outString = gDebugger->Callstack_GetStackFrameOldFileInfo(stackFrameIdx);
  1134. return outString.c_str();
  1135. }
  1136. // -1 = no jump, 0 = won't jump, 1 = will jump
  1137. BF_EXPORT int BF_CALLTYPE CallStack_GetJmpState(int stackFrameIdx)
  1138. {
  1139. return gDebugger->GetJmpState(stackFrameIdx);
  1140. }
  1141. BF_EXPORT intptr BF_CALLTYPE Debugger_GetStackFrameCalleeAddr(int stackFrameIdx)
  1142. {
  1143. return gDebugger->GetStackFrameCalleeAddr(stackFrameIdx);
  1144. }
  1145. BF_EXPORT const char* BF_CALLTYPE Debugger_GetCodeAddrInfo(intptr addr, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn)
  1146. {
  1147. String& outString = *gTLStrReturn.Get();
  1148. outString.clear();
  1149. gDebugger->GetCodeAddrInfo(addr, &outString, outHotIdx, outDefLineStart, outDefLineEnd, outLine, outColumn);
  1150. return outString.c_str();
  1151. }
  1152. BF_EXPORT void BF_CALLTYPE Debugger_GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx)
  1153. {
  1154. gDebugger->GetStackAllocInfo(addr, outThreadId, outStackIdx);
  1155. }
  1156. BF_EXPORT const char* BF_CALLTYPE CallStack_GetStackMethodOwner(int stackFrameIdx, int& language)
  1157. {
  1158. String& outString = *gTLStrReturn.Get();
  1159. outString = gDebugger->GetStackMethodOwner(stackFrameIdx, language);
  1160. return outString.c_str();
  1161. }
  1162. BF_EXPORT const char* BF_CALLTYPE Debugger_FindCodeAddresses(const char* fileName, int line, int column, bool allowAutoResolve)
  1163. {
  1164. String& outString = *gTLStrReturn.Get();
  1165. outString = gDebugger->FindCodeAddresses(fileName, line, column, allowAutoResolve);
  1166. return outString.c_str();
  1167. }
  1168. BF_EXPORT const char* BF_CALLTYPE Debugger_GetAddressSourceLocation(intptr address)
  1169. {
  1170. String& outString = *gTLStrReturn.Get();
  1171. if (gDebugger != NULL)
  1172. outString = gDebugger->GetAddressSourceLocation(address);
  1173. else
  1174. outString = "";
  1175. return outString.c_str();
  1176. }
  1177. BF_EXPORT const char* BF_CALLTYPE Debugger_GetAddressSymbolName(intptr address, bool demangle)
  1178. {
  1179. String& outString = *gTLStrReturn.Get();
  1180. if (gDebugger != NULL)
  1181. outString = gDebugger->GetAddressSymbolName(address, demangle);
  1182. else
  1183. outString = "";
  1184. return outString.c_str();
  1185. }
  1186. BF_EXPORT const char* BF_CALLTYPE Debugger_FindLineCallAddresses(intptr address)
  1187. {
  1188. String& outString = *gTLStrReturn.Get();
  1189. outString = gDebugger->FindLineCallAddresses(address);
  1190. return outString.c_str();
  1191. }
  1192. BF_EXPORT const char* BF_CALLTYPE Debugger_DisassembleAt(intptr address)
  1193. {
  1194. String& outString = *gTLStrReturn.Get();
  1195. outString = gDebugger->DisassembleAt(address);
  1196. return outString.c_str();
  1197. }
  1198. BF_EXPORT void BF_CALLTYPE Debugger_ReadMemory(uintptr address, uintptr size, unsigned char* data)
  1199. {
  1200. if (gDebugger == NULL)
  1201. return;
  1202. gDebugger->ReadMemory(address, size, data);
  1203. }
  1204. BF_EXPORT void BF_CALLTYPE Debugger_WriteMemory(uintptr address, uintptr size, unsigned char* data)
  1205. {
  1206. if (gDebugger == NULL)
  1207. return;
  1208. gDebugger->WriteMemory(address, data, size);
  1209. }
  1210. BF_EXPORT const char* BF_CALLTYPE Debugger_GetModulesInfo()
  1211. {
  1212. String& outString = *gTLStrReturn.Get();
  1213. outString = gDebugger->GetModulesInfo();
  1214. return outString.c_str();
  1215. }
  1216. BF_EXPORT void BF_CALLTYPE Debugger_CancelSymSrv()
  1217. {
  1218. gDebugger->CancelSymSrv();
  1219. }
  1220. BF_EXPORT int BF_CALLTYPE Debugger_LoadImageForModuleWith(const char* moduleName, const char* debugFilePath) // 0 = No Change, 1 = Loaded, 2 = Loading in background
  1221. {
  1222. return gDebugger->LoadImageForModule(moduleName, debugFilePath);
  1223. }
  1224. BF_EXPORT int BF_CALLTYPE Debugger_LoadDebugInfoForModule(const char* moduleName) // 0 = No Change, 1 = Loaded, 2 = Loading in background
  1225. {
  1226. return gDebugger->LoadDebugInfoForModule(moduleName);
  1227. }
  1228. BF_EXPORT int BF_CALLTYPE Debugger_LoadDebugInfoForModuleWith(const char* moduleName, const char* debugFilePath) // 0 = No Change, 1 = Loaded, 2 = Loading in background
  1229. {
  1230. return gDebugger->LoadDebugInfoForModule(moduleName, debugFilePath);
  1231. }
  1232. BF_EXPORT void BF_CALLTYPE Debugger_SetStepOverExternalFiles(bool stepOverExternalFiles)
  1233. {
  1234. gDebugManager->mStepOverExternalFiles = stepOverExternalFiles;
  1235. gDebugManager->mStepFilterVersion++;
  1236. }
  1237. BF_EXPORT void BF_CALLTYPE BfLog_Log(char* str)
  1238. {
  1239. BfLog(str);
  1240. }
  1241. BF_EXPORT void BF_CALLTYPE BfLog_LogDbg(char* str)
  1242. {
  1243. BfLogDbg(str);
  1244. }
  1245. BF_EXPORT Profiler* BF_CALLTYPE Debugger_StartProfiling(intptr threadId, char* desc, int sampleRate)
  1246. {
  1247. BF_ASSERT(sampleRate > 0);
  1248. Profiler* profiler = gDebugger->StartProfiling();
  1249. profiler->mTargetThreadId = threadId;
  1250. if (desc != NULL)
  1251. profiler->mDescription = desc;
  1252. profiler->mSamplesPerSecond = sampleRate;
  1253. profiler->Start();
  1254. return profiler;
  1255. }
  1256. BF_EXPORT Profiler* BF_CALLTYPE Debugger_PopProfiler()
  1257. {
  1258. Profiler* profiler = gDebugger->PopProfiler();
  1259. return profiler;
  1260. }
  1261. BF_EXPORT void BF_CALLTYPE Debugger_InitiateHotResolve(int flags)
  1262. {
  1263. if (gDebugger != NULL)
  1264. gDebugger->InitiateHotResolve((DbgHotResolveFlags)flags);
  1265. }
  1266. BF_EXPORT intptr BF_CALLTYPE Debugger_GetDbgAllocHeapSize()
  1267. {
  1268. AutoCrit autoCrit(gDebugManager->mCritSect);
  1269. return gDebugger->GetDbgAllocHeapSize();
  1270. }
  1271. BF_EXPORT const char* BF_CALLTYPE Debugger_GetDbgAllocInfo()
  1272. {
  1273. AutoCrit autoCrit(gDebugManager->mCritSect);
  1274. String& outString = *gTLStrReturn.Get();
  1275. outString = gDebugger->GetDbgAllocInfo();
  1276. return outString.c_str();
  1277. }
  1278. BF_EXPORT const char* BF_CALLTYPE Debugger_GetHotResolveData(uint8* outTypeData, int* outTypeDataSize)
  1279. {
  1280. AutoCrit autoCrit(gDebugManager->mCritSect);
  1281. if (gDebugger->mHotResolveData == NULL)
  1282. {
  1283. *outTypeDataSize = -1;
  1284. return NULL;
  1285. }
  1286. int dataSize = (int)gDebugger->mHotResolveData->mTypeData.size();
  1287. if (*outTypeDataSize < dataSize)
  1288. {
  1289. *outTypeDataSize = dataSize;
  1290. return NULL;
  1291. }
  1292. *outTypeDataSize = dataSize;
  1293. if (dataSize > 0)
  1294. {
  1295. for (int i = 0; i < dataSize; i++)
  1296. outTypeData[i] = (gDebugger->mHotResolveData->mTypeData[i].mCount > 0) ? 1 : 0;
  1297. }
  1298. String& outString = *gTLStrReturn.Get();
  1299. outString.Clear();
  1300. for (auto& str : gDebugger->mHotResolveData->mBeefCallStackEntries)
  1301. {
  1302. if (!outString.IsEmpty())
  1303. outString += "\n";
  1304. outString += str;
  1305. }
  1306. return outString.c_str();
  1307. }
  1308. BF_EXPORT NetResult* HTTP_GetFile(char* url, char* destPath)
  1309. {
  1310. AutoCrit autoCrit(gDebugManager->mNetManager->mThreadPool.mCritSect);
  1311. auto netResult = gDebugManager->mNetManager->QueueGet(url, destPath, false);
  1312. netResult->mDoneEvent = new SyncEvent();
  1313. return netResult;
  1314. }
  1315. BF_EXPORT int HTTP_GetResult(NetResult* netResult, int waitMS)
  1316. {
  1317. if (netResult->mDoneEvent->WaitFor(waitMS))
  1318. {
  1319. return netResult->mFailed ? 0 : 1;
  1320. }
  1321. else
  1322. {
  1323. return -1;
  1324. }
  1325. }
  1326. BF_EXPORT void HTTP_Delete(NetResult* netResult)
  1327. {
  1328. if (!netResult->mDoneEvent->WaitFor(0))
  1329. {
  1330. ///
  1331. {
  1332. AutoCrit autoCrit(gDebugManager->mNetManager->mThreadPool.mCritSect);
  1333. if (netResult->mCurRequest != NULL)
  1334. netResult->mCurRequest->Cancel();
  1335. }
  1336. netResult->mDoneEvent->WaitFor(-1);
  1337. }
  1338. delete netResult;
  1339. }
  1340. BF_EXPORT void Debugger_SetAliasPath(char* origPath, char* localPath)
  1341. {
  1342. gDebugger->SetAliasPath(origPath, localPath);
  1343. }
  1344. ///
  1345. BF_EXPORT bool BF_CALLTYPE Profiler_IsRunning(Profiler* profiler)
  1346. {
  1347. return profiler->IsSampling();
  1348. }
  1349. BF_EXPORT void BF_CALLTYPE Profiler_Stop(Profiler* profiler)
  1350. {
  1351. profiler->Stop();
  1352. }
  1353. BF_EXPORT void BF_CALLTYPE Profiler_Clear(Profiler* profiler)
  1354. {
  1355. profiler->Clear();
  1356. }
  1357. BF_EXPORT const char* BF_CALLTYPE Profiler_GetOverview(Profiler* profiler)
  1358. {
  1359. String& outString = *gTLStrReturn.Get();
  1360. outString = profiler->GetOverview();
  1361. return outString.c_str();
  1362. }
  1363. BF_EXPORT const char* BF_CALLTYPE Profiler_GetThreadList(Profiler* profiler)
  1364. {
  1365. String& outString = *gTLStrReturn.Get();
  1366. outString = profiler->GetThreadList();
  1367. return outString.c_str();
  1368. }
  1369. BF_EXPORT const char* BF_CALLTYPE Profiler_GetCallTree(Profiler* profiler, int threadId, bool reverse)
  1370. {
  1371. String& outString = *gTLStrReturn.Get();
  1372. outString = profiler->GetCallTree(threadId, reverse);
  1373. return outString.c_str();
  1374. }
  1375. BF_EXPORT void BF_CALLTYPE Profiler_Delete(Profiler* profiler)
  1376. {
  1377. int z = 0;
  1378. delete profiler;
  1379. }
  1380. BF_TLS_DECLSPEC static int gTLSValue = 3;
  1381. BF_EXPORT void BF_CALLTYPE TimeTest(uint32 startTime)
  1382. {
  1383. gTLSValue++;
  1384. int elapsedTime = BFTickCount() - startTime;
  1385. OutputDebugStrF("Load Time: %d\n", elapsedTime);
  1386. }
  1387. BF_EXPORT void BF_CALLTYPE BFTest()
  1388. {
  1389. struct DeferredResolveEntry2
  1390. {
  1391. BfFieldDef* mFieldDef;
  1392. int mTypeArrayIdx;
  1393. };
  1394. DeferredResolveEntry2 entry = { NULL, 333 };
  1395. llvm::SmallVector<DeferredResolveEntry2, 8> vec;
  1396. vec.push_back(DeferredResolveEntry2 { NULL, 111 } );
  1397. vec.push_back(DeferredResolveEntry2 { NULL, 222 } );
  1398. }
  1399. ///
  1400. // __attribute__((weak))
  1401. // Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
  1402. // {
  1403. // return NULL;
  1404. // }