nuttx/libs/libc/stdlib/lib_atexit.c
Junbo Zheng 7797b12244
Some checks are pending
Build Documentation / build-html (push) Waiting to run
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
libc/atexit: honor registrations made during exit processing
atexit_call_exitfuncs() cached its loop bound on entry
(for (idx = aehead->nfuncs - 1; idx >= 0; idx--)), while
atexit_register() appends new entries at funcs[nfuncs] and bumps nfuncs.
Any function registered by an exit handler via atexit() / on_exit() /
__cxa_atexit() lands above the cached bound and is never invoked, even
though the registration returns OK.

This contradicts the exit(3) documentation that NuttX mirrors verbatim
in its own exit() docstring (libs/libc/stdlib/lib_exit.c):

  It is possible for one of these functions to use atexit(3) or
  on_exit(3) to register an additional function to be executed
  during exit processing; the new registration is added to the
  front of the list of functions that remain to be called.

The same restructure closes a second defect: atexit_call_exitfuncs()
read and cleared the task-group-shared ta_exit list without holding
ta_lock, while atexit_register() takes it ("The following must be
atomic").  Entries are now claimed under the lock and the handler is
invoked with the lock released, so a handler re-entering
atexit_register() cannot deadlock (also safe with the non-recursive
nxmutex used here).

Evidence: exit(3) man page, DESCRIPTION -
https://man7.org/linux/man-pages/man3/exit.3.html
NuttX mirrors this passage verbatim in its own exit() docstring --
5a209a853e/libs/libc/stdlib/lib_exit.c (L65-L70)

Before:
```
A handler that registers another function during exit processing
gets a success return from atexit(), but the new function is never
invoked - it lands above the loop bound cached on entry.
```

After:
```
A registration made during exit processing runs before the older
remaining handlers (order A -> B -> C below), matching the exit(3)
guarantee, and the list is consumed under ta_lock.
```

Testing:

Simulated (sim:nsh, CONFIG_LIBC_MAX_EXITFUNS=8).

Build and run:
```
cmake -B build -DBOARD_CONFIG=sim:nsh -GNinja
cmake -S . -B build   # after setting CONFIG_LIBC_MAX_EXITFUNS=8
                       # in build/.config (sim:nsh default is 1)
cmake --build build -j$(nproc)
(echo hello; echo poweroff) | ./build/nuttx
```
"hello" runs the test at the NSH prompt; poweroff terminates the sim.

The test was carried by apps/examples/hello/hello_main.c (scratch only,
not part of this commit); its diff:

```
--- a/examples/hello/hello_main.c
+++ b/examples/hello/hello_main.c
@@ -24,6 +24,7 @@

 #include <nuttx/config.h>
 #include <stdio.h>
+#include <stdlib.h>

 /****************************************************************************
  * Public Functions
@@ -33,8 +34,29 @@
  * hello_main
  ****************************************************************************/

+static void handler_b(void)
+{
+  printf("ATEXIT-TEST: handler B called (registered during exit)\n");
+}
+
+static void handler_a(void)
+{
+  int ret;
+
+  printf("ATEXIT-TEST: handler A called\n");
+  ret = atexit(handler_b);
+  printf("ATEXIT-TEST: atexit(handler_b) inside A returned %d\n", ret);
+}
+
+static void handler_c(void)
+{
+  printf("ATEXIT-TEST: handler C called\n");
+}
+
 int main(int argc, FAR char *argv[])
 {
   printf("Hello, World!!\n");
+  atexit(handler_c);   /* older entry, must run LAST */
+  atexit(handler_a);   /* registers handler_b during exit */
   return 0;
 }
```

Before the fix:
```
Hello, World!!
ATEXIT-TEST: handler A called
ATEXIT-TEST: atexit(handler_b) inside A returned 0
ATEXIT-TEST: handler C called
```
(handler B is never invoked although its registration returned 0)

After the fix:
```
Hello, World!!
ATEXIT-TEST: handler A called
ATEXIT-TEST: atexit(handler_b) inside A returned 0
ATEXIT-TEST: handler B called (registered during exit)
ATEXIT-TEST: handler C called
```

Assisted-by: Claude Code (GLM-5.3) <claude@anthropic.com>
Signed-off-by: Junbo Zheng <zhengjunbo1@xiaomi.com>
2026-09-14 18:52:46 -03:00

288 lines
8.5 KiB
C

/****************************************************************************
* libs/libc/stdlib/lib_atexit.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdlib.h>
#include <nuttx/atexit.h>
#include <nuttx/mutex.h>
#include <nuttx/tls.h>
#if CONFIG_LIBC_MAX_EXITFUNS > 0
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: get_exitfuncs
*
* Description:
* Obtain the list of exit functions.
*
* Input Parameters:
* None
*
* Returned Value:
* Pointer to the list of exit functions.
*
****************************************************************************/
static FAR struct atexit_list_s *get_exitfuncs(void)
{
FAR struct task_info_s *info;
info = task_get_info();
return &info->ta_exit;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int atexit_register(int type, CODE void (*func)(void), FAR void *arg,
FAR void *dso)
{
FAR struct task_info_s *info = task_get_info();
FAR struct atexit_list_s *aehead;
int idx;
int ret = ERROR;
/* REVISIT: Missing logic */
UNUSED(dso);
/* The following must be atomic */
aehead = get_exitfuncs();
if (func)
{
ret = nxmutex_lock(&info->ta_lock);
if (ret < 0)
{
return -ret;
}
if ((idx = aehead->nfuncs) < ATEXIT_MAX)
{
aehead->funcs[idx].type = type;
aehead->funcs[idx].func = func;
aehead->funcs[idx].arg = arg;
aehead->nfuncs++;
ret = OK;
}
else
{
ret = ERROR;
}
nxmutex_unlock(&info->ta_lock);
}
return ret;
}
void atexit_call_exitfuncs(int status, bool quick)
{
FAR struct atexit_list_s *aehead;
FAR struct task_info_s *info = task_get_info();
CODE void (*func)(void);
FAR void *arg;
int idx;
int type;
/* Call exit functions in reverse order */
aehead = get_exitfuncs();
while (aehead->nfuncs > 0)
{
/* Claim the newest entry under the lock. A handler may register
* further functions during exit processing; those land in the slot
* just freed here and are executed on the next iteration, i.e.
* before the older remaining ones, as documented in exit(3).
*/
if (nxmutex_lock(&info->ta_lock) < 0)
{
break;
}
idx = aehead->nfuncs - 1;
type = aehead->funcs[idx].type;
func = aehead->funcs[idx].func;
arg = aehead->funcs[idx].arg;
/* Remove the function to prevent recursive call to it */
aehead->funcs[idx].func = NULL;
aehead->funcs[idx].arg = NULL;
aehead->nfuncs--;
nxmutex_unlock(&info->ta_lock);
if (!func)
{
continue;
}
if (quick != (type == ATTYPE_ATQUICKEXIT))
{
continue;
}
/* Call the atexit/on_exit/cxa_atexit() function */
if (type == ATTYPE_ATEXIT || type == ATTYPE_ATQUICKEXIT)
{
(*func)();
}
else if (type == ATTYPE_ONEXIT)
{
(*((CODE void (*)(int, FAR void *))func))(status, arg);
}
else if (type == ATTYPE_CXA)
{
(*((CODE void (*)(FAR void *))func))(arg);
}
}
}
#endif
/****************************************************************************
* Name: atexit
*
* Description:
* Registers a function to be called at program exit.
* The atexit() function registers the given function to be called
* at normal process termination, whether via exit or via return from
* the program's main().
*
* Limitations in the current implementation:
*
* 1. Only a single atexit function can be registered unless
* CONFIG_LIBC_MAX_EXITFUNS defines a larger number.
* 2. atexit functions are not inherited when a new task is
* created.
*
* Input Parameters:
* func - A pointer to the function to be called when the task exits.
*
* Returned Value:
* Zero on success. Non-zero on failure.
*
****************************************************************************/
int atexit(CODE void (*func)(void))
{
return atexit_register(ATTYPE_ATEXIT, func, NULL, NULL);
}
/****************************************************************************
* Name: at_quick_exit
*
* Description:
* Registers the function pointed to by func to be called on quick
* program termination (via quick_exit).
*
* Input Parameters:
* func - A pointer to the function to be called when the task exits.
*
* Returned Value:
* Zero on success. Non-zero on failure.
*
****************************************************************************/
int at_quick_exit(CODE void (*func)(void))
{
return atexit_register(ATTYPE_ATQUICKEXIT, func, NULL, NULL);
}
/****************************************************************************
* Name: on_exit
*
* Description:
* Registers a function to be called at program exit.
* The on_exit() function registers the given function to be called
* at normal process termination, whether via exit or via return from
* the program's main(). The function is passed the status argument
* given to the last call to exit and the arg argument from on_exit().
*
* NOTE 1: This function comes from SunOS 4, but is also present in
* libc4, libc5 and glibc. It no longer occurs in Solaris (SunOS 5).
* Avoid this function, and use the standard atexit() instead.
*
* Limitations in the current implementation:
*
* 1. Only a single on_exit function can be registered unless
* CONFIG_LIBC_MAX_EXITFUNS defines a larger number.
* 2. on_exit functions are not inherited when a new task is
* created.
*
* Input Parameters:
* func - A pointer to the function to be called when the task exits.
* arg - An argument that will be provided to the on_exit() function when
* the task exits.
*
* Returned Value:
* Zero on success. Non-zero on failure.
*
****************************************************************************/
int on_exit(CODE void (*func)(int, FAR void *), FAR void *arg)
{
return atexit_register(ATTYPE_ONEXIT, (CODE void (*)(void))func, arg,
NULL);
}
/****************************************************************************
* Name: __cxa_atexit
*
* Description:
* __cxa_atexit() registers a destructor function to be called by exit().
* On a call to exit(), the registered functions should be called with
* the single argument 'arg'. Destructor functions shall always be
* called in the reverse order to their registration (i.e. the most
* recently registered function shall be called first),
*
* If shared libraries were supported, the callbacks should be invoked
* when the shared library is unloaded as well.
*
* Reference:
* Linux base
*
****************************************************************************/
int __cxa_atexit(CODE void (*func)(FAR void *), FAR void *arg,
FAR void *dso_handle)
{
return atexit_register(ATTYPE_CXA, (CODE void (*)(void))func, arg,
dso_handle);
}