1 //===--- Implementation of exit_handler------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "src/stdlib/exit_handler.h" 10 #include "src/__support/CPP/mutex.h" // lock_guard 11 12 namespace LIBC_NAMESPACE { 13 14 constinit ExitCallbackList at_quick_exit_callbacks; 15 constinit ExitCallbackList atexit_callbacks; 16 17 Mutex handler_list_mtx(false, false, false, false); 18 stdc_at_exit_func(void * payload)19void stdc_at_exit_func(void *payload) { 20 reinterpret_cast<StdCAtExitCallback *>(payload)(); 21 } 22 call_exit_callbacks(ExitCallbackList & callbacks)23void call_exit_callbacks(ExitCallbackList &callbacks) { 24 handler_list_mtx.lock(); 25 while (!callbacks.empty()) { 26 AtExitUnit &unit = callbacks.back(); 27 callbacks.pop_back(); 28 handler_list_mtx.unlock(); 29 unit.callback(unit.payload); 30 handler_list_mtx.lock(); 31 } 32 ExitCallbackList::destroy(&callbacks); 33 } 34 add_atexit_unit(ExitCallbackList & callbacks,const AtExitUnit & unit)35int add_atexit_unit(ExitCallbackList &callbacks, const AtExitUnit &unit) { 36 cpp::lock_guard lock(handler_list_mtx); 37 if (callbacks.push_back(unit)) 38 return 0; 39 return -1; 40 } 41 42 } // namespace LIBC_NAMESPACE 43