Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | /* * Copyright (c) 2024 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <stdint.h> #include "Defines.h" #include "Header.h" #include "Error.h" #include "LibSystemHelpers.h" #include "ThreadLocalVariables.h" #include "DyldSharedCache.h" using dyld4::LibSystemHelpers; using mach_o::Error; extern "C" void* _tlv_get_addr(dyld::ThreadLocalVariables::Thunk*); namespace dyld { // call by dyld via libSystemHelpers->setUpThreadLocals() at launch and during dlopen() Error ThreadLocalVariables::setUpImage(const DyldSharedCache* cache, const Header* hdr) { // driverkit and main OS use same dyld, but driverkit process do not support thread locals #if __has_feature(tls) if ( hdr->inDyldCache() ) { if ( Error err = this->initializeThunksInDyldCache(cache, hdr) ) return err; } else { if ( Error err = this->initializeThunksFromDisk(hdr) ) return err; } return Error::none(); #else return Error::none(); #endif // __has_feature(tls) } #if __has_feature(tls) void ThreadLocalVariables::findInitialContent(const Header* hdr, std::span<const uint8_t>& initialContent, bool& allZeroFill) { allZeroFill = true; #if BUILDING_UNIT_TESTS allZeroFill = _allZeroFillContent; initialContent = _initialContent; #else // find initial content for all TLVs in image intptr_t slide = (intptr_t)hdr->getSlide(); hdr->forEachSection(^(const Header::SectionInfo& sectInfo, bool& stop) { switch (sectInfo.flags & SECTION_TYPE) { case S_THREAD_LOCAL_REGULAR: allZeroFill = false; [[clang::fallthrough]]; case S_THREAD_LOCAL_ZEROFILL: if ( initialContent.empty() ) { // first of N contiguous TLV template sections, record as if this was only section initialContent = std::span<const uint8_t>((const uint8_t*)(sectInfo.address + slide), (size_t)sectInfo.size); } else { // non-first of N contiguous TLV template sections, accumlate values size_t newSize = (uintptr_t)sectInfo.address + (uintptr_t)sectInfo.size + slide - (uintptr_t)initialContent.data(); initialContent = std::span<const uint8_t>(initialContent.data(), newSize); } break; } }); #endif } // most images have just one __thread_vars section, but some have one in __DATA and one in __DATA_DIRTY Error ThreadLocalVariables::forEachThunkSpan(const Header* hdr, Error (^visit)(std::span<Thunk>)) { #if BUILDING_UNIT_TESTS return visit(_thunks); #else __block Error setUpErr; // find section with array of TLV thunks // and also initial content for all TLVs in image intptr_t slide = (intptr_t)hdr->getSlide(); hdr->forEachSection(^(const Header::SectionInfo& sectInfo, bool& stop) { if ( (sectInfo.flags & SECTION_TYPE) == S_THREAD_LOCAL_VARIABLES ) { if ( sectInfo.size % sizeof(Thunk) != 0) { setUpErr = Error("size (%llu) of thread-locals section %.*s is not a multiple of %lu", sectInfo.size, (int)sectInfo.sectionName.size(), sectInfo.sectionName.data(), sizeof(Thunk)); stop = true; return; } if ( sectInfo.size >= sizeof(Thunk) ) { std::span<Thunk> thunks = std::span<Thunk>((Thunk*)(sectInfo.address + slide), (size_t)(sectInfo.size/sizeof(Thunk))); setUpErr = visit(thunks); } } }); return std::move(setUpErr); #endif } static void finalizeListTLV(void* list) { #if BUILDING_LIBDYLD // Called by libc/pthreads when the current thread is going away sThreadLocalVariables.finalizeList(list); #endif // BUILDING_LIBDYLD } // This is called during libSystem initialization, which passes libSystemHelpers from libdyld down to dyld. // _libSystem_initialize() -> _dyld_initialize() -> APIs::_libdyld_initialize() -> ThreadLocalVariables::initialize() void ThreadLocalVariables::initialize() { // assign pthread_key for per-thread terminators // Note: if a thread is terminated, the value for this key is cleaned up by calling finalizeList() dyld_thread_key_create(&_terminatorsKey, &finalizeListTLV); } Error ThreadLocalVariables::initializeThunksFromDisk(const Header* hdr) { // each dylib gets a new key used for all thread-locals in that dylib dyld_thread_key_t key; #if BUILDING_UNIT_TESTS key = _key; #else if ( dyld_thread_key_create(&key, &::free) ) return Error("pthread_key_create() failed"); #endif // find initial content for all TLVs in image std::span<const uint8_t> initialContent; bool allZeroFill; findInitialContent(hdr, initialContent, allZeroFill); // set the thunk function pointer and key for every thread local variable Error err = forEachThunkSpan(hdr, ^(std::span<Thunk> thunks) { for ( Thunk& thunk : thunks ) { uintptr_t offset = thunk.offset; if ( offset > initialContent.size() ) return Error("malformed thread-local, offset=0x%lX is larger than total size=0x%lX", thunk.offset, initialContent.size() ); #if __LP64__ if ( initialContent.size() > 0xFFFFFFFFUL ) return Error("unsupported thread-local, larger than 4GB"); if ( key > 0xFFFFFFFFUL ) return Error("thread_key_t %lu, larger than uint32_t", key); TLV_Thunkv2* thunkv2 = (TLV_Thunkv2*)&thunk; thunkv2->func = (void*)&_tlv_get_addr; thunkv2->key = (uint32_t)key; thunkv2->offset = (uint32_t)offset; thunkv2->initialContentDelta = (uint32_t)(initialContent.data() - (uint8_t*)(&thunkv2->initialContentDelta)); thunkv2->initialContentSize = (uint32_t)initialContent.size(); // if initial content is all zeros, no need to store delta to initialContent if ( allZeroFill ) thunkv2->initialContentDelta = 0; if (verbose) fprintf(stderr, "initializeThunksFromDisk(%p): thunk=%p, key=%d, offset=0x%08X, delta=0x%08X, size=%d\n", hdr, thunkv2, thunkv2->key, thunkv2->offset, thunkv2->initialContentDelta, thunkv2->initialContentSize); #else if ( key > 0xFFFF ) return Error("thread_key_t %lu, larger than uint16_t", key); TLV_Thunkv2_32* thunkv2 = (TLV_Thunkv2_32*)&thunk; thunkv2->func = (void*)&_tlv_get_addr; thunkv2->key = (uint16_t)key; thunkv2->offset = (uint16_t)offset; // if initial content is all zeros, store size, otherwise store delta to mach_header so runtime can find __thread_ sections if ( allZeroFill ) { if ( initialContent.size() > 0x7FFFFFFF ) return Error("unsupported thread-local, larger than 2GB of zero-fill"); thunkv2->machHeaderDelta = (uint32_t)initialContent.size(); } else { thunkv2->machHeaderDelta = (int32_t)((uint8_t*)hdr - (uint8_t*)&thunkv2->machHeaderDelta); } if (verbose) fprintf(stderr, "initializeThunksFromDisk(%p): thunk=%p, key=%d, offset=0x%04X, machHeaderDelta=0x%08X\n", hdr, thunkv2, thunkv2->key, thunkv2->offset, thunkv2->machHeaderDelta); #endif } return Error::none(); }); return err; } Error ThreadLocalVariables::initializeThunksInDyldCache(const DyldSharedCache* cache, const Header* hdr) { // if cache builder runs out of static keys, it leaves the thunks looking like they do on disk (key == 0) __block bool notOptimized = false; Error err = forEachThunkSpan(hdr, ^(std::span<Thunk> thunks) { int staticKey = 0; // FIXME: simplify once new cache format is standard if ( cache->header.newFormatTLVs ) { #if __LP64__ TLV_Thunkv2* thunkv2 = (TLV_Thunkv2*)&thunks[0]; #else TLV_Thunkv2_32* thunkv2 = (TLV_Thunkv2_32*)&thunks[0]; #endif staticKey = thunkv2->key; } else { staticKey = (int)thunks[0].key; } if ( staticKey == 0 ) { notOptimized = true; if (verbose) fprintf(stderr, " initializeThunksInDyldCache(%p) thunks=%p not optimized in dyld cache\n", hdr, &thunks[0]); return Error::none(); } else { // dyld cache builder assigned a static key for these TLVs but we need to register // that free() should be called on the key's value if the thread goes away dyld_thread_key_init_np(staticKey, &::free); } // thunks in the dyld shared cache are normally correct, but we may need to be correct them if root of libdyld.dylib is in use void* getAddrFunc = (void*)&_tlv_get_addr; for ( Thunk& thunk : thunks ) { if ( thunk.func!= getAddrFunc ) thunk.func = getAddrFunc; } return Error::none(); }); if ( notOptimized ) return initializeThunksFromDisk(hdr); if ( err.hasError() ) return err; if ( !cache->header.newFormatTLVs ) return Error("dyld cache thread-local format too old"); return Error::none();; } void ThreadLocalVariables::addTermFunc(TermFunc func, void* objAddr) { // NOTE: this does not need locks because it only operates on current thread data TerminatorList* list = (TerminatorList*)::dyld_thread_getspecific(_terminatorsKey); if ( list == nullptr ) { // Note: use system malloc because it is thread safe and does not require dyld's allocator to be made r/w list = (TerminatorList*)::malloc(sizeof(TerminatorList)); bzero(list, sizeof(TerminatorList)); dyld_thread_setspecific(_terminatorsKey, list); } // go to end of chain while (list->next != nullptr) list = list->next; // make sure there is space to add another element if ( list->count == 7 ) { // if list is full, add a chain TerminatorList* nextList = (TerminatorList*)::malloc(sizeof(TerminatorList)); bzero(nextList, sizeof(TerminatorList)); list->next = nextList; list = nextList; } list->elements[list->count++] = { func, objAddr }; } // <rdar://problem/13741816> // called by exit() before it calls cxa_finalize() so that thread_local // objects are destroyed before global objects. // Note this is only called on macOS, and by libc. // iOS only destroys tlv's when each thread is destroyed and libpthread calls // tlv_finalize as that is the pointer we provided when we created the key void ThreadLocalVariables::exit() { if ( TerminatorList* list = (TerminatorList*)::dyld_thread_getspecific(_terminatorsKey) ) { // detach storage from thread while freeing it dyld_thread_setspecific(_terminatorsKey, nullptr); // Note, if new thread locals are added to our during this termination, // they will be on a new list, but the list we have here // is one we own and need to destroy it this->finalizeList(list); } } void ThreadLocalVariables::TerminatorList::reverseWalkChain(void (^visit)(TerminatorList*)) { if ( this->next != nullptr ) this->next->reverseWalkChain(visit); visit(this); } // on entry, libc has set the TSD slot to nullptr and passed us the previous value // this is done to handle destructors that re-animate the key value void ThreadLocalVariables::finalizeList(void* l) { TerminatorList* list = (TerminatorList*)l; // call term functions in reverse order of construction list->reverseWalkChain(^(TerminatorList* chain) { for ( uintptr_t i = chain->count; i > 0; --i ) { const Terminator& entry = chain->elements[i - 1]; if ( entry.termFunc != nullptr ) (*entry.termFunc)(entry.objAddr); // If a new tlv was added via tlv_atexit during the termination function just called, then we need to immediately destroy it TerminatorList* newlist = (TerminatorList*)(::dyld_thread_getspecific(_terminatorsKey)); if ( newlist != nullptr ) { // Set the list to NULL so that if yet another tlv is registered, we put it in a new list dyld_thread_setspecific(_terminatorsKey, nullptr); this->finalizeList(newlist); } } }); // free entire chain list->reverseWalkChain(^(TerminatorList* chain) { ::free(chain); }); } // called lazily when TLV is first accessed void* ThreadLocalVariables::instantiateVariable(const Thunk& thunk) { #if TARGET_OS_EXCLAVEKIT // On ExclaveKit, the assembly code for _tlv_get_addr cannot access thread specific data // instead we access it here from C. TLV_Thunkv2* ekThunk = (TLV_Thunkv2*)&thunk; if ( void* result = ::tss_get(ekThunk->key) ) return result; #endif // TARGET_OS_EXCLAVEKIT void* buffer = nullptr; dyld_thread_key_t key = 0; #if __LP64__ TLV_Thunkv2* thunkv2 = (TLV_Thunkv2*)&thunk; key = thunkv2->key; if ( thunkv2->initialContentDelta != 0 ) { // initial content of thread-locals is non-zero so copy initial bytes from template buffer = ::malloc(thunkv2->initialContentSize); const uint8_t* initialContent = (uint8_t*)(&thunkv2->initialContentDelta) + thunkv2->initialContentDelta; memcpy(buffer, initialContent, thunkv2->initialContentSize); if (verbose) fprintf(stderr, "instantiateVariable(%p) buffer=%p, init-content=%p size=%d\n", &thunk, buffer, initialContent, thunkv2->initialContentSize); } else { // initial content of thread-locals is all zeros buffer = ::calloc(thunkv2->initialContentSize, 1); if (verbose) fprintf(stderr, "instantiateVariable(%p) buffer=%p, zero-fill, size=%d\n", &thunk, buffer, thunkv2->initialContentSize); } #else TLV_Thunkv2_32* thunkv2 = (TLV_Thunkv2_32*)&thunk; if ( thunkv2->machHeaderDelta < 0 ) { // in non-zerofill case, machHeaderDelta is delta to mach_header key = thunkv2->key; std::span<const uint8_t> bytes((uint8_t*)&thunkv2->machHeaderDelta + thunkv2->machHeaderDelta, -thunkv2->machHeaderDelta); if ( const Header* hdr = Header::isMachO(bytes) ) { std::span<const uint8_t> initialContent; bool allZeroFill; findInitialContent(hdr, initialContent, allZeroFill); if ( initialContent.empty() ) { fprintf(stderr, "ThreadLocalVariables::getInitialContent(%p) failed\n", hdr); return nullptr; // abort? something has gone wrong } buffer = ::malloc(initialContent.size()); memcpy(buffer, initialContent.data(), initialContent.size()); if (verbose) fprintf(stderr, "instantiateVariable(%p) buffer=%p, init-content=%p size=%lu\n", thunkv2, buffer, initialContent.data(), initialContent.size()); } else { fprintf(stderr, "ThreadLocalVariables::instantiateVariable(%p) cannot find mach-o header\n", thunkv2); return nullptr; // abort? something has gone wrong } } else { // in zerofill case, machHeaderDelta is size to allocate buffer = ::calloc(thunkv2->machHeaderDelta, 1); key = thunkv2->key; if (verbose) fprintf(stderr, "instantiateVariable(%p) buffer=%p, zero-fill, size=%d\n", thunkv2, buffer, thunkv2->machHeaderDelta); } #endif // set this thread's value for key to be the new buffer. dyld_thread_setspecific(key, buffer); return buffer; } #endif // __has_feature(tls) #if BUILDING_LIBDYLD ThreadLocalVariables sThreadLocalVariables; #endif #if BUILDING_UNIT_TESTS void ThreadLocalVariables::setMock(int tlvKey, std::span<Thunk> thunks, std::span<const uint8_t> content) { _key = tlvKey; _thunks = thunks; _initialContent = content; _allZeroFillContent = true; for (uint8_t byte : content) { if ( byte != 0 ) { _allZeroFillContent = false; break; } } } #endif } // namespace |