1 //===-- Implementation header for exit_handler ------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H
10 #define LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H
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"
19 namespace LIBC_NAMESPACE_DECL
{
21 using AtExitCallback
= void(void *);
22 using StdCAtExitCallback
= void(void);
23 constexpr size_t CALLBACK_LIST_SIZE_FOR_TESTS
= 1024;
26 AtExitCallback
*callback
= nullptr;
27 void *payload
= nullptr;
28 LIBC_INLINE
constexpr AtExitUnit() = default;
29 LIBC_INLINE
constexpr AtExitUnit(AtExitCallback
*c
, void *p
)
30 : callback(c
), payload(p
) {}
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>;
38 using ExitCallbackList
= FixedVector
<AtExitUnit
, CALLBACK_LIST_SIZE_FOR_TESTS
>;
41 // This is handled by the 'atexit' implementation and shared by 'at_quick_exit'.
42 extern Mutex handler_list_mtx
;
44 LIBC_INLINE
void stdc_at_exit_func(void *payload
) {
45 reinterpret_cast<StdCAtExitCallback
*>(payload
)();
48 LIBC_INLINE
void call_exit_callbacks(ExitCallbackList
&callbacks
) {
49 handler_list_mtx
.lock();
50 while (!callbacks
.empty()) {
51 AtExitUnit
&unit
= callbacks
.back();
53 handler_list_mtx
.unlock();
54 unit
.callback(unit
.payload
);
55 handler_list_mtx
.lock();
57 ExitCallbackList::destroy(&callbacks
);
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
))
68 } // namespace LIBC_NAMESPACE_DECL
70 #endif // LLVM_LIBC_SRC_STDLIB_EXIT_HANDLER_H