|
| 1 | +//===-- GPU implementation of atexit --------------------------------------===// |
| 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/atexit.h" |
| 10 | +#include "src/__support/common.h" |
| 11 | +#include "src/__support/fixedstack.h" |
| 12 | + |
| 13 | +namespace LIBC_NAMESPACE { |
| 14 | + |
| 15 | +namespace { |
| 16 | + |
| 17 | +using AtExitCallback = void(void *); |
| 18 | +using StdCAtExitCallback = void(void); |
| 19 | + |
| 20 | +struct AtExitUnit { |
| 21 | + AtExitCallback *callback = nullptr; |
| 22 | + void *payload = nullptr; |
| 23 | + constexpr AtExitUnit() = default; |
| 24 | + constexpr AtExitUnit(AtExitCallback *c, void *p) : callback(c), payload(p) {} |
| 25 | +}; |
| 26 | + |
| 27 | +// The GPU interface cannot use the standard implementation because it does not |
| 28 | +// support the Mutex type. Instead we use a lock free stack with a sufficiently |
| 29 | +// large size. |
| 30 | +constinit FixedStack<AtExitUnit, CALLBACK_LIST_SIZE_FOR_TESTS> exit_callbacks; |
| 31 | + |
| 32 | +void stdc_at_exit_func(void *payload) { |
| 33 | + reinterpret_cast<StdCAtExitCallback *>(payload)(); |
| 34 | +} |
| 35 | + |
| 36 | +} // namespace |
| 37 | + |
| 38 | +namespace internal { |
| 39 | + |
| 40 | +void call_exit_callbacks() { |
| 41 | + AtExitUnit unit; |
| 42 | + while (exit_callbacks.pop(unit)) |
| 43 | + unit.callback(unit.payload); |
| 44 | +} |
| 45 | + |
| 46 | +} // namespace internal |
| 47 | + |
| 48 | +static int add_atexit_unit(const AtExitUnit &unit) { |
| 49 | + if (!exit_callbacks.push(unit)) |
| 50 | + return -1; |
| 51 | + return 0; |
| 52 | +} |
| 53 | + |
| 54 | +extern "C" int __cxa_atexit(AtExitCallback *callback, void *payload, void *) { |
| 55 | + return add_atexit_unit({callback, payload}); |
| 56 | +} |
| 57 | + |
| 58 | +LLVM_LIBC_FUNCTION(int, atexit, (StdCAtExitCallback * callback)) { |
| 59 | + return add_atexit_unit( |
| 60 | + {&stdc_at_exit_func, reinterpret_cast<void *>(callback)}); |
| 61 | +} |
| 62 | + |
| 63 | +} // namespace LIBC_NAMESPACE |
0 commit comments