c++ - Initialize before any global objects -


i writing c++ memory profiler.

as knows, executable program may contain many global objects, , dll modules may contain global objects well. these global objects initialized crt initialization - after entry point , before winmain; dlls, entry point _dllmaincrtstartup, before dllmain, global objects of dll initialized.

a global object may allocate memory. memory profiler must initialized before global object initialization. after doing lot of researching, found not easy job.

one idea using createprocess create_suspended flag - try first chance. after that, use createremotethread call loadlibrary in target process load injection dll, , initialize dll. doesn't work because load implicit-linking dlls of executable program first. maybe createremotethread triggers behavior?

so, how first chance?

there might way otherwise using platform-specific ways, 1 way solve issue combine lazy initialization dylib loading.

for example, memory allocator functions exported this:

api void* exported_alloc(); api void exported_free(void* mem); 

... inside dylib called mem.dll.

in case, ensure of other dylibs can when being loaded, can create central statically-linked library (ex: sdk.lib) of dylibs link against header so:

#ifndef memory_h #define memory_h  // memory.h void* my_alloc(); void my_free(void* mem);  #endif 

... can implement so:

static void* (exported_alloc)() = 0; static void (exported_free)(void* mem) = 0;  static void initialize() {     if (!exported_alloc)     {          // load 'mem.dll' (ex: 'loadlibrary') ,          // symbols `exported_alloc` , `exported_free`          // (ex: getprocaddress).     } }  void* my_alloc() {           initialize();     return exported_alloc(); }  void my_free(void* mem) {     initialize();     exported_free(mem); } 

.. call freelibrary @ appropriate time when you're finished dll. incurs bit of run-time overhead (similar overhead of accessing singleton), cross-platform solution (provided have cross-platform means of loading/unloading dylibs/shared libs @ runtime).

with solution, of dlls allocating memory @ global scope load mem.dll prior performing memory allocations in lazy-initialized kind of way, ensuring have access memory functions @ appropriate time.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

node.js - Using Node without global install -

php - CakePHP HttpSockets send array of paramms -