xref: /aosp_15_r20/external/llvm-libc/src/stdlib/exit_handler.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Implementation header for exit_handler ------------------*- C++ -*-===//
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 #ifndef LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H
10 #define LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H
11 
12 #include "src/__support/CPP/mutex.h" // lock_guard
13 #include "src/__support/blockstore.h"
14 #include "src/__support/common.h"
15 #include "src/__support/fixedvector.h"
16 #include "src/__support/macros/config.h"
17 #include "src/__support/threads/mutex.h"
18 
19 namespace LIBC_NAMESPACE_DECL {
20 
21 using AtExitCallback = void(void *);
22 using StdCAtExitCallback = void(void);
23 constexpr size_t CALLBACK_LIST_SIZE_FOR_TESTS = 1024;
24 
25 struct AtExitUnit {
26   AtExitCallback *callback = nullptr;
27   void *payload = nullptr;
28   LIBC_INLINE constexpr AtExitUnit() = default;
AtExitUnitAtExitUnit29   LIBC_INLINE constexpr AtExitUnit(AtExitCallback *c, void *p)
30       : callback(c), payload(p) {}
31 };
32 
33 #if defined(LIBC_TARGET_ARCH_IS_GPU)
34 using ExitCallbackList = FixedVector<AtExitUnit, 64>;
35 #elif defined(LIBC_COPT_PUBLIC_PACKAGING)
36 using ExitCallbackList = ReverseOrderBlockStore<AtExitUnit, 32>;
37 #else
38 using ExitCallbackList = FixedVector<AtExitUnit, CALLBACK_LIST_SIZE_FOR_TESTS>;
39 #endif
40 
41 // This is handled by the 'atexit' implementation and shared by 'at_quick_exit'.
42 extern Mutex handler_list_mtx;
43 
stdc_at_exit_func(void * payload)44 LIBC_INLINE void stdc_at_exit_func(void *payload) {
45   reinterpret_cast<StdCAtExitCallback *>(payload)();
46 }
47 
call_exit_callbacks(ExitCallbackList & callbacks)48 LIBC_INLINE void call_exit_callbacks(ExitCallbackList &callbacks) {
49   handler_list_mtx.lock();
50   while (!callbacks.empty()) {
51     AtExitUnit &unit = callbacks.back();
52     callbacks.pop_back();
53     handler_list_mtx.unlock();
54     unit.callback(unit.payload);
55     handler_list_mtx.lock();
56   }
57   ExitCallbackList::destroy(&callbacks);
58 }
59 
add_atexit_unit(ExitCallbackList & callbacks,const AtExitUnit & unit)60 LIBC_INLINE int add_atexit_unit(ExitCallbackList &callbacks,
61                                 const AtExitUnit &unit) {
62   cpp::lock_guard lock(handler_list_mtx);
63   if (callbacks.push_back(unit))
64     return 0;
65   return -1;
66 }
67 
68 } // namespace LIBC_NAMESPACE_DECL
69 
70 #endif // LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H
71