From 02e740c90dcd368f8de9db00ca34ac4923ffc0e6 Mon Sep 17 00:00:00 2001 From: mintsuki Date: Sat, 28 Sep 2019 11:54:38 +0200 Subject: [PATCH] elf/startup: Add __mlibc_run_constructors() function for static linking --- options/elf/generic/startup.cpp | 24 ++++++++++++++++++++++++ options/elf/include/mlibc/elf/startup.h | 2 ++ 2 files changed, 26 insertions(+) diff --git a/options/elf/generic/startup.cpp b/options/elf/generic/startup.cpp index 66ff3e5c..c1c4e2e0 100644 --- a/options/elf/generic/startup.cpp +++ b/options/elf/generic/startup.cpp @@ -6,6 +6,30 @@ #include #include +extern "C" size_t __init_array_start[]; +extern "C" size_t __init_array_end[]; + +static int constructors_ran_already = 0; + +struct global_constructor_guard { + global_constructor_guard() { + constructors_ran_already = 1; + } +}; + +static global_constructor_guard g; + +void __mlibc_run_constructors() { + if (!constructors_ran_already) { + size_t constructor_count = (size_t)__init_array_end - (size_t)__init_array_start; + constructor_count /= sizeof(void*); + for (size_t i = 0; i < constructor_count; i++) { + void (*ptr)(void) = (void(*)(void))(__init_array_start[i]); + ptr(); + } + } +} + namespace mlibc { void parse_exec_stack(void *opaque_sp, exec_stack_data *data) { diff --git a/options/elf/include/mlibc/elf/startup.h b/options/elf/include/mlibc/elf/startup.h index cf29d966..728422b0 100644 --- a/options/elf/include/mlibc/elf/startup.h +++ b/options/elf/include/mlibc/elf/startup.h @@ -1,6 +1,8 @@ #ifndef MLIBC_ELF_STARTUP #define MLIBC_ELF_STARTUP +void __mlibc_run_constructors(); + namespace mlibc { struct exec_stack_data {