1 /** 2 * This file has no copyright assigned and is placed in the Public Domain. 3 * This file is part of the mingw-w64 runtime package. 4 * No warranty is given; refer to the file DISCLAIMER.PD within this package. 5 */ 6 7 #include <process.h> 8 #include <stdlib.h> 9 10 #define _EXIT_LOCK1 8 11 12 void __cdecl _lock (int _File); 13 void __cdecl _unlock (int _File); 14 _initialize_onexit_table(_onexit_table_t * table)15int __cdecl _initialize_onexit_table(_onexit_table_t *table) 16 { 17 if (!table) return -1; 18 table->_first = table->_last = table->_end = NULL; 19 return 0; 20 } 21 _register_onexit_function(_onexit_table_t * table,_onexit_t func)22int __cdecl _register_onexit_function(_onexit_table_t *table, _onexit_t func) 23 { 24 if (!table) return -1; 25 26 _lock(_EXIT_LOCK1); 27 28 if (!table->_first) { 29 table->_first = calloc(32, sizeof(void*)); 30 if (!table->_first) { 31 _unlock(_EXIT_LOCK1); 32 return -1; 33 } 34 table->_last = table->_first; 35 table->_end = table->_first + 32; 36 } 37 38 if (table->_last == table->_end) { 39 size_t len = table->_end - table->_first; 40 _PVFV *new_buf = realloc(table->_first, len * sizeof(void*) * 2); 41 if (!new_buf) { 42 _unlock(_EXIT_LOCK1); 43 return -1; 44 } 45 table->_first = new_buf; 46 table->_last = new_buf + len; 47 table->_end = new_buf + len * 2; 48 } 49 50 *table->_last++ = (_PVFV)func; 51 _unlock(_EXIT_LOCK1); 52 return 0; 53 } 54 _execute_onexit_table(_onexit_table_t * table)55int __cdecl _execute_onexit_table(_onexit_table_t *table) 56 { 57 _PVFV *first, *last; 58 59 _lock(_EXIT_LOCK1); 60 first = table->_first; 61 last = table->_last; 62 _initialize_onexit_table(table); 63 _unlock(_EXIT_LOCK1); 64 65 if (!first) return 0; 66 67 while (--last >= first) 68 if (*last) 69 (**last)(); 70 71 free(first); 72 return 0; 73 } 74 75 typeof(_initialize_onexit_table) *__MINGW_IMP_SYMBOL(_initialize_onexit_table) = _initialize_onexit_table; 76 typeof(_register_onexit_function) *__MINGW_IMP_SYMBOL(_register_onexit_function) = _register_onexit_function; 77 typeof(_execute_onexit_table) *__MINGW_IMP_SYMBOL(_execute_onexit_table) = _execute_onexit_table; 78