From c0d25e8683a2bf18da8c640814c659d397741869 Mon Sep 17 00:00:00 2001 From: Ali Gholami Rudi Date: Tue, 2 Dec 2014 06:35:33 +0330 Subject: [PATCH] stdlib: atexit() --- stdlib.c | 20 ++++++++++++++++++++ stdlib.h | 2 ++ x64/start.s | 5 ++++- x86/start.s | 2 ++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/stdlib.c b/stdlib.c index 1413bd4..c45e4c3 100644 --- a/stdlib.c +++ b/stdlib.c @@ -3,6 +3,8 @@ #include #include +#define ATEXIT_MAX 32 + char **environ; void exit(int status) @@ -46,3 +48,21 @@ int system(char *cmd) return -1; return ret; } + +static void (*atexit_func[ATEXIT_MAX])(void); +static int atexit_cnt; + +int atexit(void (*func)(void)) +{ + if (atexit_cnt >= ATEXIT_MAX) + return -1; + atexit_func[atexit_cnt++] = func; + return 0; +} + +void __neatlibc_exit(void) +{ + int i; + for (i = 0; i < atexit_cnt; i++) + atexit_func[i](); +} diff --git a/stdlib.h b/stdlib.h index cb88d05..891d5ac 100644 --- a/stdlib.h +++ b/stdlib.h @@ -12,6 +12,8 @@ long labs(long n); void exit(int status); void abort(void); +int atexit(void (*func)(void)); + char *getenv(char *name); void qsort(void *a, int n, int sz, int (*cmp)(void *, void *)); int mkstemp(char *t); diff --git a/x64/start.s b/x64/start.s index daa4078..a32ea0d 100644 --- a/x64/start.s +++ b/x64/start.s @@ -3,6 +3,7 @@ format ELF64 extrn environ extrn main +extrn __neatlibc_exit public _start _start: xor rbp, rbp @@ -14,6 +15,8 @@ _start: and rsp, -16 ; align rsp call main - mov rdi, rax + mov rbx, rax + call __neatlibc_exit + mov rdi, rbx mov rax, 60 syscall diff --git a/x86/start.s b/x86/start.s index 1f1e854..306fe50 100644 --- a/x86/start.s +++ b/x86/start.s @@ -3,6 +3,7 @@ format ELF extrn environ extrn main +extrn __neatlibc_exit public _start _start: xor ebp, ebp @@ -18,5 +19,6 @@ _start: push ecx call main mov ebx, eax + call __neatlibc_exit mov eax, 0x1 int 0x80 -- 2.11.4.GIT