atexit considered harmful?
Asked Answered
S

2

5

Are there inherent dangers in using atexit in large projects such as libraries?

If so, what is it about the technical nature behind atexit that may lead to problems in larger projects?

Swallowtailed answered 27/6, 2013 at 18:9 Comment(0)
R
7

The main reason I would avoid using atexit in libraries is that any use of it involves global state. A good library should avoid having global state.

However, there are also other technical reasons:

  1. Implementations are only required to support a small number (32, I think) of atexit handlers. After that, it's possible that all calls to atexit fail, or that they succeed or fail depending on resource availability. Thus, you have to deal with what to do if you can't register your atexit handler, and there might not be any good way to proceed.

  2. Interaction of atexit with dlopen or other methods of loading libraries dynamically is not defined. A library which has registered atexit handlers cannot safely be unloaded, and the ways different implementations deal with this situation can vary.

  3. Poorly written atexit handlers could have interactions with one another, or just bad behaviors, that prevent the program from properly exiting. For instance, if an atexit handler attempts to obtain a lock that's held in another thread and that can't be released due to the state at the time exit was called.

Rossiya answered 27/6, 2013 at 19:10 Comment(1)
"Since glibc 2.2.3, atexit() (and on_exit(3)) can be used within a shared library to establish functions that are called when the shared library is unloaded." Taken from man atexit. However, I am not sure, whether the same behavior is enforced on other C libs. So, if you're targeting glibc solely, this doesn't apply to you.Willette
O
1

Secure CERT has an entry about atexit when not used correctly:

ENV32-C. All atexit handlers must return normally

https://www.securecoding.cert.org/confluence/display/seccode/ENV32-C.+All+atexit+handlers+must+return+normally

Opprobrium answered 27/6, 2013 at 18:15 Comment(2)
So the problems typically arise when a function passed to atexit has the potential to call exit or otherwise not return normally?Swallowtailed
The C++ equivalent of this bug actually exists somewhere (I forget where) in the LLVM codebase. They have a destructor that calls exit...Rossiya

© 2022 - 2024 — McMap. All rights reserved.