Skip to content

Instantly share code, notes, and snippets.

@mjansson
Created April 16, 2020 13:17
Show Gist options
  • Select an option

  • Save mjansson/8a573974473e1d69a2299444cd41bea9 to your computer and use it in GitHub Desktop.

Select an option

Save mjansson/8a573974473e1d69a2299444cd41bea9 to your computer and use it in GitHub Desktop.
DLL init & fini order
//
// For information on how the runtime deals with initialization and finalization, read
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization
//
extern void rpmalloc_initialize();
extern void rpmalloc_finalize();
static void _global_rpmalloc_init(void);
static void _global_rpmalloc_fini(void);
// This puts the initialing function in the CRT segment for C constructors (.CRT$XIx)
// which are basically a list of function pointers executing in order from XIA to XIZ
#pragma section(".CRT$XIB",read)
__declspec(allocate(".CRT$XIB")) void (*_rpmllinit_)(void) = _global_rpmalloc_init;
// Using the CRT terminator segment does not seem to work, does not get called
// on DLL detach. Use atexit instead.
// #pragma section(".CRT$XTZ",read)
// __declspec(allocate(".CRT$XTZ")) void (*_rpmllfini_)(void) = _global_rpmalloc_fini;
extern int atexit(void (__cdecl*)());
static void
_global_rpmalloc_init(void) {
rpmalloc_initialize();
atexit(_global_rpmalloc_fini);
}
static void
_global_rpmalloc_fini(void) {
rpmalloc_finalize();
}
// Make sure symbols are not purged in linker
#pragma comment(linker, "/include:_rpmllinit_")
//#pragma comment(linker, "/include:_rpmllfini_")
#pragma comment(linker, "/merge:.CRT=.rdata")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment