Skip to content

Commit f4f8b49

Browse files
committed
Override exit and atexit functions from newlib.
This change simplify the exit and initialization process. It also reduce the number of hidden memory allocation made by atexit.
1 parent ce23ec3 commit f4f8b49

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

hal/common/retarget.cpp

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ extern "C" void exit(int return_code) {
629629
} //namespace std
630630
#endif
631631

632-
#if defined(TOOLCHAIN_ARM)
632+
#if defined(TOOLCHAIN_ARM) || defined(TOOLCHAIN_GCC)
633633

634634
// This series of function disable the registration of global destructors
635635
// in a dynamic table which will be called when the application exit.
@@ -650,6 +650,39 @@ void __cxa_finalize(void *handle) {
650650

651651
} // end of extern "C"
652652

653+
#endif
654+
655+
656+
#if defined(TOOLCHAIN_GCC)
657+
658+
/*
659+
* Depending on how newlib is configured, it is often not enough to define
660+
* __aeabi_atexit, __cxa_atexit and __cxa_finalize in order to override the
661+
* behavior regarding the registration of handlers with atexit.
662+
*
663+
* To overcome this limitation, exit and atexit are overriden here.
664+
*/
665+
extern "C"{
666+
667+
/**
668+
* @brief Retarget of exit for GCC.
669+
* @details Unlike the standard version, this function doesn't call any function
670+
* registered with atexit before calling _exit.
671+
*/
672+
void __wrap_exit(int return_code) {
673+
_exit(return_code);
674+
}
675+
676+
/**
677+
* @brief Retarget atexit from GCC.
678+
* @details This function will always fail and never register any handler to be
679+
* called at exit.
680+
*/
681+
int __wrap_atexit(void (*func)()) {
682+
return 1;
683+
}
684+
685+
}
653686

654687
#endif
655688

tools/toolchains/gcc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ class GCC(mbedToolchain):
4040
'c': ["-std=gnu99"],
4141
'cxx': ["-std=gnu++98", "-fno-rtti", "-Wvla"],
4242
'ld': ["-Wl,--gc-sections", "-Wl,--wrap,main",
43-
"-Wl,--wrap,_malloc_r", "-Wl,--wrap,_free_r", "-Wl,--wrap,_realloc_r", "-Wl,--wrap,_calloc_r"],
43+
"-Wl,--wrap,_malloc_r", "-Wl,--wrap,_free_r", "-Wl,--wrap,_realloc_r", "-Wl,--wrap,_calloc_r",
44+
"-Wl,--wrap,exit", "-Wl,--wrap,atexit"],
4445
}
4546

4647
def __init__(self, target, options=None, notify=None, macros=None, silent=False, tool_path="", extra_verbose=False):

0 commit comments

Comments
 (0)