#include <stdio.h>\r
#include "lib.h"\r
\r
-extern void *_crt0_exit_handler;\r
+extern void _stdio_cleanup(void);\r
+\r
+#define MAX_ATEXIT_HANDLERS 64 // Standard defines >=32\r
\r
// === PROTOTYPES ===\r
EXPORT int atoi(const char *str);\r
EXPORT void exit(int status);\r
\r
// === GLOBALS ===\r
-void (*g_stdlib_exithandler)(void);\r
+typedef void (*stdlib_exithandler_t)(void);\r
+stdlib_exithandler_t g_stdlib_exithandlers[MAX_ATEXIT_HANDLERS];\r
+ int g_stdlib_num_exithandlers;\r
\r
// === CODE ===\r
-void atexit(void (*__func)(void))\r
+void _call_atexit_handlers(void)\r
+{\r
+ int i;\r
+ for( i = g_stdlib_num_exithandlers; i --; )\r
+ g_stdlib_exithandlers[i]();\r
+ _stdio_cleanup();\r
+}\r
+\r
+EXPORT void atexit(void (*__func)(void))\r
{\r
- g_stdlib_exithandler = __func;\r
- // TODO: Replace with meta-function to allow multiple atexit() handlers\r
- _crt0_exit_handler = __func; \r
+ if( g_stdlib_num_exithandlers < MAX_ATEXIT_HANDLERS )\r
+ {\r
+ g_stdlib_exithandlers[g_stdlib_num_exithandlers++] = __func;\r
+ }\r
}\r
\r
/**\r
*/\r
EXPORT void exit(int status)\r
{\r
- if( g_stdlib_exithandler )\r
- g_stdlib_exithandler();\r
+ _call_atexit_handlers();\r
_exit(status);\r
}\r
\r