1 //===-- Implementation of at-fork callback helpers -----------------------===//
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 #include "fork_callbacks.h"
11 #include "src/__support/threads/mutex.h"
13 #include <stddef.h> // For size_t
15 namespace __llvm_libc
{
19 struct ForkCallbackTriple
{
20 ForkCallback
*prepare
= nullptr;
21 ForkCallback
*parent
= nullptr;
22 ForkCallback
*child
= nullptr;
23 constexpr ForkCallbackTriple() = default;
26 class AtForkCallbackManager
{
27 static constexpr size_t CALLBACK_SIZE
= 32;
28 // TODO: Replace this with block store when integration tests
29 // can use allocators.
30 ForkCallbackTriple list
[CALLBACK_SIZE
];
35 constexpr AtForkCallbackManager() : mtx(false, false, false), next_index(0) {}
37 bool register_triple(const ForkCallbackTriple
&triple
) {
39 if (next_index
>= CALLBACK_SIZE
)
41 list
[next_index
] = triple
;
46 void invoke_prepare() {
48 for (size_t i
= 0; i
< next_index
; ++i
) {
49 auto prepare
= list
[i
].prepare
;
55 void invoke_parent() {
57 for (size_t i
= 0; i
< next_index
; ++i
) {
58 auto parent
= list
[i
].parent
;
66 for (size_t i
= 0; i
< next_index
; ++i
) {
67 auto child
= list
[i
].child
;
74 AtForkCallbackManager cb_manager
;
76 } // Anonymous namespace
78 bool register_atfork_callbacks(ForkCallback
*prepare_cb
,
79 ForkCallback
*parent_cb
,
80 ForkCallback
*child_cb
) {
81 return cb_manager
.register_triple({prepare_cb
, parent_cb
, child_cb
});
84 void invoke_child_callbacks() { cb_manager
.invoke_child(); }
86 void invoke_prepare_callbacks() { cb_manager
.invoke_prepare(); }
88 void invoke_parent_callbacks() { cb_manager
.invoke_parent(); }
90 } // namespace __llvm_libc