Andrew Parker
Andrew Parker

Reputation: 1465

How can macho sections of type S_THREAD_LOCAL_INIT_FUNCTION_POINTERS ever occur?

The macho file specification includes a section of type S_THREAD_LOCAL_INIT_FUNCTION_POINTERS. In the llvm source in MCSectionMachO.h I found the comment:

S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - Section with thread local variable initialization pointers to functions.

Furthermore in the libdylib source there is explicit code to handle these:

http://www.opensource.apple.com/source/dyld/dyld-195.6/src/threadLocalVariables.c

Specifically, after allocating TLS for sections of type S_THREAD_LOCAL_VARIABLES the code can run static constructors functions "over the top" of the allocated memory to initialize it in a custom way.

The problem is that I can't see how one could possibly cause such sections to be emitted by the compiler. The obvious thing to do would be to initialize a thread_local variable using a function, e.g.

__thread int tl_int = foo();

However this is disallowed by the c++ standard:

In C++, if an initializer is present for a thread-local variable, it must be a constant-expression, as defined in 5.19.2 of the ANSI/ISO C++ standard.

See https://gcc.gnu.org/onlinedocs/gcc/Thread-Local.html.

Does anyone know how I might generate such a section using high level code? Obviously doing it via assembly, manual hacking or any other dark arts aren't what I'm looking for here.

(Note that I use __thread above and not thread_local as clang doesn't seem to support the c++11 keyword thread_local. Bonus points for insight on that one - I haven't put much effort into finding out the answer to that yet!).

Upvotes: 1

Views: 326

Answers (1)

Oleg Kulchytskyi
Oleg Kulchytskyi

Reputation: 1

With clang you can use

__attribute__((section("__DATA,__thread_init")))

This create section with S_THREAD_LOCAL_INIT_FUNCTION_POINTERS attribute.

Upvotes: 0

Related Questions