Reorganize static TLS memory for ELF TLS
For ELF TLS "local-exec" accesses, the static linker assumes that an
executable's TLS segment is located at a statically-known offset from the
thread pointer (i.e. "variant 1" for ARM and "variant 2" for x86).
Because these layouts are incompatible, Bionic generally needs to allocate
its TLS slots differently between different architectures.
To allow per-architecture TLS slots:
- Replace the TLS_SLOT_xxx enumerators with macros. New ARM slots are
generally negative, while new x86 slots are generally positive.
- Define a bionic_tcb struct that provides two things:
- a void* raw_slots_storage[BIONIC_TLS_SLOTS] field
- an inline accessor function: void*& tls_slot(size_t tpindex);
For ELF TLS, it's necessary to allocate a temporary TCB (i.e. TLS slots),
because the runtime linker doesn't know how large the static TLS area is
until after it has loaded all of the initial solibs.
To accommodate Golang, it's necessary to allocate the pthread keys at a
fixed, small, positive offset from the thread pointer.
This CL moves the pthread keys into bionic_tls, then allocates a single
mapping per thread that looks like so:
- stack guard
- stack [omitted for main thread and with pthread_attr_setstack]
- static TLS:
- bionic_tcb [exec TLS will either precede or succeed the TCB]
- bionic_tls [prefixed by the pthread keys]
- [solib TLS segments will be placed here]
- guard page
As before, if the new mapping includes a stack, the pthread_internal_t
is allocated on it.
At startup, Bionic allocates a temporary bionic_tcb object on the stack,
then allocates a temporary bionic_tls object using mmap. This mmap is
delayed because the linker can't currently call async_safe_fatal() before
relocating itself.
Later, Bionic allocates a stack-less thread mapping for the main thread,
and copies slots from the temporary TCB to the new TCB.
(See *::copy_from_bootstrap methods.)
Bug: http://b/78026329
Test: bionic unit tests
Test: verify that a Golang app still works
Test: verify that a Golang app crashes if bionic_{tls,tcb} are swapped
Change-Id: I6543063752f4ec8ef6dc9c7f2a06ce2a18fc5af3
diff --git a/libc/private/bionic_asm_tls.h b/libc/private/bionic_asm_tls.h
new file mode 100644
index 0000000..06e3dce
--- /dev/null
+++ b/libc/private/bionic_asm_tls.h
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#pragma once
+
+/** WARNING WARNING WARNING
+ **
+ ** This header file is *NOT* part of the public Bionic ABI/API and should not
+ ** be used/included by user-serviceable parts of the system (e.g.
+ ** applications).
+ **
+ ** It is only provided here for the benefit of Android components that need a
+ ** pre-allocated slot for performance reasons (including ART, the OpenGL
+ ** subsystem, and sanitizers).
+ **/
+
+// Bionic TCB / TLS slots:
+//
+// - TLS_SLOT_SELF: On x86-{32,64}, the kernel makes TLS memory available via
+// the gs/fs segments. To get the address of a TLS variable, the first slot
+// of TLS memory (accessed using %gs:0 / %fs:0) holds the address of the
+// gs/fs segment. This slot is used by:
+// - OpenGL and compiler-rt
+// - Accesses of x86 ELF TLS variables
+//
+// - TLS_SLOT_OPENGL and TLS_SLOT_OPENGL_API: These two aren't used by bionic
+// itself, but allow the graphics code to access TLS directly rather than
+// using the pthread API.
+//
+// - TLS_SLOT_STACK_GUARD: Used for -fstack-protector by:
+// - Clang targeting Android/arm64
+// - gcc targeting Linux/x86-{32,64}
+//
+// - TLS_SLOT_SANITIZER: Lets sanitizers avoid using pthread_getspecific for
+// finding the current thread state.
+//
+// - TLS_SLOT_DTV: Pointer to ELF TLS dynamic thread vector.
+//
+// - TLS_SLOT_ART_THREAD_SELF: Fast storage for Thread::Current() in ART.
+//
+// - TLS_SLOT_BIONIC_TLS: Optimizes accesses to bionic_tls by one load versus
+// finding it using __get_thread().
+
+#if defined(__arm__) || defined(__aarch64__)
+
+// The ARM ELF TLS ABI specifies[1] that the thread pointer points at a 2-word
+// TCB followed by the executable's TLS segment. Both the TCB and the
+// executable's segment are aligned according to the segment, so Bionic requires
+// a minimum segment alignment, which effectively reserves an 8-word TCB. The
+// ARM spec allocates the first TCB word to the DTV.
+//
+// [1] "Addenda to, and Errata in, the ABI for the ARM Architecture". Section 3.
+// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0045e/IHI0045E_ABI_addenda.pdf
+
+#define MIN_TLS_SLOT -1 // update this value when reserving a slot
+#define TLS_SLOT_BIONIC_TLS -1
+#define TLS_SLOT_DTV 0
+#define TLS_SLOT_THREAD_ID 1
+// Slot 2 is free (was historically used for TLS_SLOT_ERRNO)
+#define TLS_SLOT_OPENGL 3
+#define TLS_SLOT_OPENGL_API 4
+#define TLS_SLOT_STACK_GUARD 5
+#define TLS_SLOT_SANITIZER 6 // was historically used for dlerror
+#define TLS_SLOT_ART_THREAD_SELF 7
+#define TLS_SLOT_TSAN 8 // should be replaced with TLS_SLOT_SANITIZER
+
+// The maximum slot is fixed by the minimum TLS alignment in Bionic executables.
+// It should be changed to 7 once TLS_SLOT_TSAN is removed.
+#define MAX_TLS_SLOT 8
+
+#elif defined(__i386__) || defined(__x86_64__)
+
+// x86 uses variant 2 ELF TLS layout, which places the executable's TLS segment
+// immediately before the thread pointer. New slots are allocated at positive
+// offsets from the thread pointer.
+
+#define MIN_TLS_SLOT 0
+
+#define TLS_SLOT_SELF 0
+#define TLS_SLOT_THREAD_ID 1
+// Slot 2 is free (was historically used for TLS_SLOT_ERRNO)
+#define TLS_SLOT_OPENGL 3
+#define TLS_SLOT_OPENGL_API 4
+#define TLS_SLOT_STACK_GUARD 5
+#define TLS_SLOT_SANITIZER 6 // was historically used for dlerror
+#define TLS_SLOT_ART_THREAD_SELF 7
+#define TLS_SLOT_TSAN 8 // should be replaced with TLS_SLOT_SANITIZER
+#define TLS_SLOT_DTV 9
+#define TLS_SLOT_BIONIC_TLS 10
+#define MAX_TLS_SLOT 10 // update this value when reserving a slot
+
+#endif
+
+#define BIONIC_TLS_SLOTS (MAX_TLS_SLOT - MIN_TLS_SLOT + 1)
diff --git a/libc/private/bionic_elf_tls.h b/libc/private/bionic_elf_tls.h
new file mode 100644
index 0000000..e847669
--- /dev/null
+++ b/libc/private/bionic_elf_tls.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+struct StaticTlsLayout {
+ constexpr StaticTlsLayout() {}
+
+private:
+ size_t offset_ = 0;
+ size_t alignment_ = 1;
+ bool overflowed_ = false;
+
+ // Offsets to various Bionic TLS structs from the beginning of static TLS.
+ size_t offset_bionic_tcb_ = SIZE_MAX;
+ size_t offset_bionic_tls_ = SIZE_MAX;
+
+public:
+ size_t offset_bionic_tcb() const { return offset_bionic_tcb_; }
+ size_t offset_bionic_tls() const { return offset_bionic_tls_; }
+
+ size_t size() const { return offset_; }
+ size_t alignment() const { return alignment_; }
+ bool overflowed() const { return overflowed_; }
+
+ void reserve_tcb();
+ void reserve_bionic_tls();
+ void finish_layout();
+
+private:
+ size_t reserve(size_t size, size_t alignment);
+
+ template <typename T> size_t reserve_type() {
+ return reserve(sizeof(T), alignof(T));
+ }
+
+ size_t round_up_with_overflow_check(size_t value, size_t alignment);
+};
diff --git a/libc/private/bionic_globals.h b/libc/private/bionic_globals.h
index ceda38a..b5e677e 100644
--- a/libc/private/bionic_globals.h
+++ b/libc/private/bionic_globals.h
@@ -33,6 +33,7 @@
#include <link.h>
#include <pthread.h>
+#include "private/bionic_elf_tls.h"
#include "private/bionic_fdsan.h"
#include "private/bionic_malloc_dispatch.h"
#include "private/bionic_vdso.h"
@@ -67,6 +68,8 @@
pthread_mutex_t abort_msg_lock = PTHREAD_MUTEX_INITIALIZER;
abort_msg_t* abort_msg = nullptr;
+ StaticTlsLayout static_tls_layout;
+
// Values passed from the linker to libc.so.
const char* init_progname = nullptr;
char** init_environ = nullptr;
diff --git a/libc/private/bionic_tls.h b/libc/private/bionic_tls.h
index 4749cee..90914c3 100644
--- a/libc/private/bionic_tls.h
+++ b/libc/private/bionic_tls.h
@@ -26,8 +26,7 @@
* SUCH DAMAGE.
*/
-#ifndef __BIONIC_PRIVATE_BIONIC_TLS_H_
-#define __BIONIC_PRIVATE_BIONIC_TLS_H_
+#pragma once
#include <locale.h>
#include <mntent.h>
@@ -35,73 +34,48 @@
#include <sys/cdefs.h>
#include <sys/param.h>
+#include "bionic_asm_tls.h"
#include "bionic_macros.h"
#include "__get_tls.h"
#include "grp_pwd.h"
-__BEGIN_DECLS
-
/** WARNING WARNING WARNING
**
- ** This header file is *NOT* part of the public Bionic ABI/API
- ** and should not be used/included by user-serviceable parts of
- ** the system (e.g. applications).
- **
- ** It is only provided here for the benefit of the system dynamic
- ** linker and the OpenGL sub-system (which needs to access the
- ** pre-allocated slot directly for performance reason).
+ ** This header file is *NOT* part of the public Bionic ABI/API and should not
+ ** be used/included by user-serviceable parts of the system (e.g.
+ ** applications).
**/
-// Well-known TLS slots. What data goes in which slot is arbitrary unless otherwise noted.
-enum {
- TLS_SLOT_SELF = 0, // The kernel requires this specific slot for x86.
- TLS_SLOT_THREAD_ID,
+class pthread_internal_t;
- // TLS slot 2 was used for errno but is now free.
+// This struct is small, so the linker can allocate a temporary copy on its
+// stack. It can't be combined with pthread_internal_t because:
+// - native bridge requires pthread_internal_t to have the same layout across
+// architectures, and
+// - On x86, this struct would have to be placed at the front of
+// pthread_internal_t, moving fields like `tid`.
+// - We'd like to avoid having a temporary pthread_internal_t object that
+// needs to be transferred once the final size of static TLS is known.
+struct bionic_tcb {
+ void* raw_slots_storage[BIONIC_TLS_SLOTS];
- // These two aren't used by bionic itself, but allow the graphics code to
- // access TLS directly rather than using the pthread API.
- TLS_SLOT_OPENGL_API = 3,
- TLS_SLOT_OPENGL = 4,
+ // Return a reference to a slot given its TP-relative TLS_SLOT_xxx index.
+ // The thread pointer (i.e. __get_tls()) points at &tls_slot(0).
+ void*& tls_slot(size_t tpindex) {
+ return raw_slots_storage[tpindex - MIN_TLS_SLOT];
+ }
- TLS_SLOT_STACK_GUARD = 5, // GCC requires this specific slot for x86.
+ // Initialize the main thread's final object using its bootstrap object.
+ void copy_from_bootstrap(const bionic_tcb* boot) {
+ // Copy everything. Problematic slots will be reinitialized.
+ *this = *boot;
+ }
- // Lets sanitizers avoid using pthread_getspecific for finding the current
- // thread state. (Slot 6 was historically used for dlerror instead.)
- TLS_SLOT_SANITIZER = 6,
-
- // Fast storage for Thread::Current() in ART.
- TLS_SLOT_ART_THREAD_SELF = 7,
-
- // Lets TSAN avoid using pthread_getspecific for finding the current thread
- // state.
- TLS_SLOT_TSAN = 8,
-
- BIONIC_TLS_SLOTS // Must come last!
+ pthread_internal_t* thread() {
+ return static_cast<pthread_internal_t*>(tls_slot(TLS_SLOT_THREAD_ID));
+ }
};
-// ~3 pages.
-struct bionic_tls {
- locale_t locale;
-
- char basename_buf[MAXPATHLEN];
- char dirname_buf[MAXPATHLEN];
-
- mntent mntent_buf;
- char mntent_strings[BUFSIZ];
-
- char ptsname_buf[32];
- char ttyname_buf[64];
-
- char strerror_buf[NL_TEXTMAX];
- char strsignal_buf[NL_TEXTMAX];
-
- group_state_t group;
- passwd_state_t passwd;
-};
-
-#define BIONIC_TLS_SIZE (__BIONIC_ALIGN(sizeof(bionic_tls), PAGE_SIZE))
-
/*
* Bionic uses some pthread keys internally. All pthread keys used internally
* should be created in constructors, except for keys that may be used in or
@@ -126,12 +100,42 @@
*/
#define BIONIC_PTHREAD_KEY_COUNT (BIONIC_PTHREAD_KEY_RESERVED_COUNT + PTHREAD_KEYS_MAX)
-__END_DECLS
+class pthread_key_data_t {
+ public:
+ uintptr_t seq; // Use uintptr_t just for alignment, as we use pointer below.
+ void* data;
+};
-#if defined(__cplusplus)
+// ~3 pages. This struct is allocated as static TLS memory (i.e. at a fixed
+// offset from the thread pointer).
+struct bionic_tls {
+ pthread_key_data_t key_data[BIONIC_PTHREAD_KEY_COUNT];
+
+ locale_t locale;
+
+ char basename_buf[MAXPATHLEN];
+ char dirname_buf[MAXPATHLEN];
+
+ mntent mntent_buf;
+ char mntent_strings[BUFSIZ];
+
+ char ptsname_buf[32];
+ char ttyname_buf[64];
+
+ char strerror_buf[NL_TEXTMAX];
+ char strsignal_buf[NL_TEXTMAX];
+
+ group_state_t group;
+ passwd_state_t passwd;
+
+ // Initialize the main thread's final object using its bootstrap object.
+ void copy_from_bootstrap(const bionic_tls* boot __attribute__((unused))) {
+ // Nothing in bionic_tls needs to be preserved in the transition to the
+ // final TLS objects, so don't copy anything.
+ }
+};
+
class KernelArgumentBlock;
-extern void __libc_init_main_thread_early(KernelArgumentBlock& args);
-extern void __libc_init_main_thread_late();
-#endif
-
-#endif /* __BIONIC_PRIVATE_BIONIC_TLS_H_ */
+extern "C" void __libc_init_main_thread_early(const KernelArgumentBlock& args, bionic_tcb* temp_tcb);
+extern "C" void __libc_init_main_thread_late();
+extern "C" void __libc_init_main_thread_final();
diff --git a/libc/private/linker_native_bridge.h b/libc/private/linker_native_bridge.h
new file mode 100644
index 0000000..bfd0153
--- /dev/null
+++ b/libc/private/linker_native_bridge.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#pragma once
+
+extern "C" void __linker_reserve_bionic_tls_in_static_tls();