[hackers] [scc] [libc] Fix exit() and atexit() || Roberto E. Vargas Caballero

From: <git_AT_suckless.org>
Date: Tue, 7 Mar 2017 22:24:33 +0100 (CET)

commit 33b9f7476c6f730def0034b2b36ad14dde30d2f2
Author: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
AuthorDate: Tue Mar 7 20:56:46 2017 +0100
Commit: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
CommitDate: Tue Mar 7 20:56:46 2017 +0100

    [libc] Fix exit() and atexit()
    
    Functions registered with atexit() must be called
    in reverse order. This implementation also protects
    against calling exit() from an atexit() handler.

diff --git a/libc/include/errno.h b/libc/include/errno.h
index 5f14aa6..ebb5461 100644
--- a/libc/include/errno.h
+++ b/libc/include/errno.h
_AT_@ -5,6 +5,7 @@
 #define EDOM 1
 #define EILSEQ 2
 #define ERANGE 3
+#define ENOMEN 4
 
 extern int errno;
 
diff --git a/libc/src/atexit.c b/libc/src/atexit.c
index 712b7f6..be270db 100644
--- a/libc/src/atexit.c
+++ b/libc/src/atexit.c
_AT_@ -1,19 +1,19 @@
 /* See LICENSE file for copyright and license details. */
 
 #include <stdlib.h>
+#include <errno.h>
 #undef atexit
 
-extern void (*_atexitf[_ATEXIT_MAX])(void);
+extern void (*_exitf[_ATEXIT_MAX])(void);
+extern unsigned _exitn;
 
 int
 atexit(void (*fun)(void))
 {
- void (**bp)(void);
-
- for (bp = _atexitf; bp < &_atexitf[_ATEXIT_MAX] && *bp; ++bp)
- /* nothing */;
- if (bp == &_atexitf[_ATEXIT_MAX])
- return 0;
- *bp = fun;
- return 1;
+ if (_exitn == _ATEXIT_MAX) {
+ errno = ENOMEN;
+ return -1;
+ }
+ _exitf[_exitn++] = fun;
+ return 0;
 }
diff --git a/libc/src/exit.c b/libc/src/exit.c
index 0712378..1da149e 100644
--- a/libc/src/exit.c
+++ b/libc/src/exit.c
_AT_@ -3,19 +3,13 @@
 #include <stdlib.h>
 #undef exit
 
-void (*_atexitf[_ATEXIT_MAX])(void);
+void (*_exitf[_ATEXIT_MAX])(void);
+unsigned _exitn;
 
 void
 exit(int status)
 {
- void (**bp)(void);
- int i;
-
- for (i = _ATEXIT_MAX-1; i >= 0; --i) {
- if (bp = _atexit[i]) {
- *_atexit[i] = NULL;
- (*bp)();
- }
- }
+ while (_exitn > 0)
+ (*_exitf[--exitn])();
         _Exit(status);
 }
Received on Tue Mar 07 2017 - 22:24:33 CET

This archive was generated by hypermail 2.3.0 : Tue Mar 07 2017 - 22:36:22 CET