]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-os.mm
objc4-709.1.tar.gz
[apple/objc4.git] / runtime / objc-os.mm
1 /*
2 * Copyright (c) 2007 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /***********************************************************************
25 * objc-os.m
26 * OS portability layer.
27 **********************************************************************/
28
29 #include "objc-private.h"
30 #include "objc-loadmethod.h"
31
32 #if TARGET_OS_WIN32
33
34 #include "objc-runtime-old.h"
35 #include "objcrt.h"
36
37 const fork_unsafe_lock_t fork_unsafe_lock;
38
39 int monitor_init(monitor_t *c)
40 {
41 // fixme error checking
42 HANDLE mutex = CreateMutex(NULL, TRUE, NULL);
43 while (!c->mutex) {
44 // fixme memory barrier here?
45 if (0 == InterlockedCompareExchangePointer(&c->mutex, mutex, 0)) {
46 // we win - finish construction
47 c->waiters = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
48 c->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
49 InitializeCriticalSection(&c->waitCountLock);
50 c->waitCount = 0;
51 c->didBroadcast = 0;
52 ReleaseMutex(c->mutex);
53 return 0;
54 }
55 }
56
57 // someone else allocated the mutex and constructed the monitor
58 ReleaseMutex(mutex);
59 CloseHandle(mutex);
60 return 0;
61 }
62
63 void mutex_init(mutex_t *m)
64 {
65 while (!m->lock) {
66 CRITICAL_SECTION *newlock = malloc(sizeof(CRITICAL_SECTION));
67 InitializeCriticalSection(newlock);
68 // fixme memory barrier here?
69 if (0 == InterlockedCompareExchangePointer(&m->lock, newlock, 0)) {
70 return;
71 }
72 // someone else installed their lock first
73 DeleteCriticalSection(newlock);
74 free(newlock);
75 }
76 }
77
78
79 void recursive_mutex_init(recursive_mutex_t *m)
80 {
81 // fixme error checking
82 HANDLE newmutex = CreateMutex(NULL, FALSE, NULL);
83 while (!m->mutex) {
84 // fixme memory barrier here?
85 if (0 == InterlockedCompareExchangePointer(&m->mutex, newmutex, 0)) {
86 // we win
87 return;
88 }
89 }
90
91 // someone else installed their lock first
92 CloseHandle(newmutex);
93 }
94
95
96 WINBOOL APIENTRY DllMain( HMODULE hModule,
97 DWORD ul_reason_for_call,
98 LPVOID lpReserved
99 )
100 {
101 switch (ul_reason_for_call) {
102 case DLL_PROCESS_ATTACH:
103 environ_init();
104 tls_init();
105 lock_init();
106 sel_init(3500); // old selector heuristic
107 exception_init();
108 break;
109
110 case DLL_THREAD_ATTACH:
111 break;
112
113 case DLL_THREAD_DETACH:
114 case DLL_PROCESS_DETACH:
115 break;
116 }
117 return TRUE;
118 }
119
120 OBJC_EXPORT void *_objc_init_image(HMODULE image, const objc_sections *sects)
121 {
122 header_info *hi = malloc(sizeof(header_info));
123 size_t count, i;
124
125 hi->mhdr = (const headerType *)image;
126 hi->info = sects->iiStart;
127 hi->allClassesRealized = NO;
128 hi->modules = sects->modStart ? (Module *)((void **)sects->modStart+1) : 0;
129 hi->moduleCount = (Module *)sects->modEnd - hi->modules;
130 hi->protocols = sects->protoStart ? (struct old_protocol **)((void **)sects->protoStart+1) : 0;
131 hi->protocolCount = (struct old_protocol **)sects->protoEnd - hi->protocols;
132 hi->imageinfo = NULL;
133 hi->imageinfoBytes = 0;
134 // hi->imageinfo = sects->iiStart ? (uint8_t *)((void **)sects->iiStart+1) : 0;;
135 // hi->imageinfoBytes = (uint8_t *)sects->iiEnd - hi->imageinfo;
136 hi->selrefs = sects->selrefsStart ? (SEL *)((void **)sects->selrefsStart+1) : 0;
137 hi->selrefCount = (SEL *)sects->selrefsEnd - hi->selrefs;
138 hi->clsrefs = sects->clsrefsStart ? (Class *)((void **)sects->clsrefsStart+1) : 0;
139 hi->clsrefCount = (Class *)sects->clsrefsEnd - hi->clsrefs;
140
141 count = 0;
142 for (i = 0; i < hi->moduleCount; i++) {
143 if (hi->modules[i]) count++;
144 }
145 hi->mod_count = 0;
146 hi->mod_ptr = 0;
147 if (count > 0) {
148 hi->mod_ptr = malloc(count * sizeof(struct objc_module));
149 for (i = 0; i < hi->moduleCount; i++) {
150 if (hi->modules[i]) memcpy(&hi->mod_ptr[hi->mod_count++], hi->modules[i], sizeof(struct objc_module));
151 }
152 }
153
154 hi->moduleName = malloc(MAX_PATH * sizeof(TCHAR));
155 GetModuleFileName((HMODULE)(hi->mhdr), hi->moduleName, MAX_PATH * sizeof(TCHAR));
156
157 appendHeader(hi);
158
159 if (PrintImages) {
160 _objc_inform("IMAGES: loading image for %s%s%s%s\n",
161 hi->fname,
162 headerIsBundle(hi) ? " (bundle)" : "",
163 hi->info->isReplacement() ? " (replacement)":"",
164 hi->info->hasCategoryClassProperties() ? " (has class properties)":"");
165 }
166
167 // Count classes. Size various table based on the total.
168 int total = 0;
169 int unoptimizedTotal = 0;
170 {
171 if (_getObjc2ClassList(hi, &count)) {
172 total += (int)count;
173 if (!hi->getInSharedCache()) unoptimizedTotal += count;
174 }
175 }
176
177 _read_images(&hi, 1, total, unoptimizedTotal);
178
179 return hi;
180 }
181
182 OBJC_EXPORT void _objc_load_image(HMODULE image, header_info *hinfo)
183 {
184 prepare_load_methods(hinfo);
185 call_load_methods();
186 }
187
188 OBJC_EXPORT void _objc_unload_image(HMODULE image, header_info *hinfo)
189 {
190 _objc_fatal("image unload not supported");
191 }
192
193
194 // TARGET_OS_WIN32
195 #elif TARGET_OS_MAC
196
197 #include "objc-file-old.h"
198 #include "objc-file.h"
199
200
201 /***********************************************************************
202 * libobjc must never run static destructors.
203 * Cover libc's __cxa_atexit with our own definition that runs nothing.
204 * rdar://21734598 ER: Compiler option to suppress C++ static destructors
205 **********************************************************************/
206 extern "C" int __cxa_atexit();
207 extern "C" int __cxa_atexit() { return 0; }
208
209
210 /***********************************************************************
211 * bad_magic.
212 * Return YES if the header has invalid Mach-o magic.
213 **********************************************************************/
214 bool bad_magic(const headerType *mhdr)
215 {
216 return (mhdr->magic != MH_MAGIC && mhdr->magic != MH_MAGIC_64 &&
217 mhdr->magic != MH_CIGAM && mhdr->magic != MH_CIGAM_64);
218 }
219
220
221 static header_info * addHeader(const headerType *mhdr, const char *path, int &totalClasses, int &unoptimizedTotalClasses)
222 {
223 header_info *hi;
224
225 if (bad_magic(mhdr)) return NULL;
226
227 bool inSharedCache = false;
228
229 // Look for hinfo from the dyld shared cache.
230 hi = preoptimizedHinfoForHeader(mhdr);
231 if (hi) {
232 // Found an hinfo in the dyld shared cache.
233
234 // Weed out duplicates.
235 if (hi->isLoaded()) {
236 return NULL;
237 }
238
239 inSharedCache = true;
240
241 // Initialize fields not set by the shared cache
242 // hi->next is set by appendHeader
243 hi->setLoaded(true);
244
245 if (PrintPreopt) {
246 _objc_inform("PREOPTIMIZATION: honoring preoptimized header info at %p for %s", hi, hi->fname());
247 }
248
249 #if !__OBJC2__
250 _objc_fatal("shouldn't be here");
251 #endif
252 #if DEBUG
253 // Verify image_info
254 size_t info_size = 0;
255 const objc_image_info *image_info = _getObjcImageInfo(mhdr,&info_size);
256 assert(image_info == hi->info());
257 #endif
258 }
259 else
260 {
261 // Didn't find an hinfo in the dyld shared cache.
262
263 // Weed out duplicates
264 for (hi = FirstHeader; hi; hi = hi->getNext()) {
265 if (mhdr == hi->mhdr()) return NULL;
266 }
267
268 // Locate the __OBJC segment
269 size_t info_size = 0;
270 unsigned long seg_size;
271 const objc_image_info *image_info = _getObjcImageInfo(mhdr,&info_size);
272 const uint8_t *objc_segment = getsegmentdata(mhdr,SEG_OBJC,&seg_size);
273 if (!objc_segment && !image_info) return NULL;
274
275 // Allocate a header_info entry.
276 // Note we also allocate space for a single header_info_rw in the
277 // rw_data[] inside header_info.
278 hi = (header_info *)calloc(sizeof(header_info) + sizeof(header_info_rw), 1);
279
280 // Set up the new header_info entry.
281 hi->setmhdr(mhdr);
282 #if !__OBJC2__
283 // mhdr must already be set
284 hi->mod_count = 0;
285 hi->mod_ptr = _getObjcModules(hi, &hi->mod_count);
286 #endif
287 // Install a placeholder image_info if absent to simplify code elsewhere
288 static const objc_image_info emptyInfo = {0, 0};
289 hi->setinfo(image_info ?: &emptyInfo);
290
291 hi->setLoaded(true);
292 hi->setAllClassesRealized(NO);
293 }
294
295 #if __OBJC2__
296 {
297 size_t count = 0;
298 if (_getObjc2ClassList(hi, &count)) {
299 totalClasses += (int)count;
300 if (!inSharedCache) unoptimizedTotalClasses += count;
301 }
302 }
303 #endif
304
305 appendHeader(hi);
306
307 return hi;
308 }
309
310
311 /***********************************************************************
312 * linksToLibrary
313 * Returns true if the image links directly to a dylib whose install name
314 * is exactly the given name.
315 **********************************************************************/
316 bool
317 linksToLibrary(const header_info *hi, const char *name)
318 {
319 const struct dylib_command *cmd;
320 unsigned long i;
321
322 cmd = (const struct dylib_command *) (hi->mhdr() + 1);
323 for (i = 0; i < hi->mhdr()->ncmds; i++) {
324 if (cmd->cmd == LC_LOAD_DYLIB || cmd->cmd == LC_LOAD_UPWARD_DYLIB ||
325 cmd->cmd == LC_LOAD_WEAK_DYLIB || cmd->cmd == LC_REEXPORT_DYLIB)
326 {
327 const char *dylib = cmd->dylib.name.offset + (const char *)cmd;
328 if (0 == strcmp(dylib, name)) return true;
329 }
330 cmd = (const struct dylib_command *)((char *)cmd + cmd->cmdsize);
331 }
332
333 return false;
334 }
335
336
337 #if SUPPORT_GC_COMPAT
338
339 /***********************************************************************
340 * shouldRejectGCApp
341 * Return YES if the executable requires GC.
342 **********************************************************************/
343 static bool shouldRejectGCApp(const header_info *hi)
344 {
345 assert(hi->mhdr()->filetype == MH_EXECUTE);
346
347 if (!hi->info()->supportsGC()) {
348 // App does not use GC. Don't reject it.
349 return NO;
350 }
351
352 // Exception: Trivial AppleScriptObjC apps can run without GC.
353 // 1. executable defines no classes
354 // 2. executable references NSBundle only
355 // 3. executable links to AppleScriptObjC.framework
356 // Note that objc_appRequiresGC() also knows about this.
357 size_t classcount = 0;
358 size_t refcount = 0;
359 #if __OBJC2__
360 _getObjc2ClassList(hi, &classcount);
361 _getObjc2ClassRefs(hi, &refcount);
362 #else
363 if (hi->mod_count == 0 || (hi->mod_count == 1 && !hi->mod_ptr[0].symtab)) classcount = 0;
364 else classcount = 1;
365 _getObjcClassRefs(hi, &refcount);
366 #endif
367 if (classcount == 0 && refcount == 1 &&
368 linksToLibrary(hi, "/System/Library/Frameworks"
369 "/AppleScriptObjC.framework/Versions/A"
370 "/AppleScriptObjC"))
371 {
372 // It's AppleScriptObjC. Don't reject it.
373 return NO;
374 }
375 else {
376 // GC and not trivial AppleScriptObjC. Reject it.
377 return YES;
378 }
379 }
380
381
382 /***********************************************************************
383 * rejectGCImage
384 * Halt if an image requires GC.
385 * Testing of the main executable should use rejectGCApp() instead.
386 **********************************************************************/
387 static bool shouldRejectGCImage(const headerType *mhdr)
388 {
389 assert(mhdr->filetype != MH_EXECUTE);
390
391 objc_image_info *image_info;
392 size_t size;
393
394 #if !__OBJC2__
395 unsigned long seg_size;
396 // 32-bit: __OBJC seg but no image_info means no GC support
397 if (!getsegmentdata(mhdr, "__OBJC", &seg_size)) {
398 // Not objc, therefore not GC. Don't reject it.
399 return NO;
400 }
401 image_info = _getObjcImageInfo(mhdr, &size);
402 if (!image_info) {
403 // No image_info, therefore not GC. Don't reject it.
404 return NO;
405 }
406 #else
407 // 64-bit: no image_info means no objc at all
408 image_info = _getObjcImageInfo(mhdr, &size);
409 if (!image_info) {
410 // Not objc, therefore not GC. Don't reject it.
411 return NO;
412 }
413 #endif
414
415 return image_info->requiresGC();
416 }
417
418 // SUPPORT_GC_COMPAT
419 #endif
420
421
422 /***********************************************************************
423 * map_images_nolock
424 * Process the given images which are being mapped in by dyld.
425 * All class registration and fixups are performed (or deferred pending
426 * discovery of missing superclasses etc), and +load methods are called.
427 *
428 * info[] is in bottom-up order i.e. libobjc will be earlier in the
429 * array than any library that links to libobjc.
430 *
431 * Locking: loadMethodLock(old) or runtimeLock(new) acquired by map_images.
432 **********************************************************************/
433 #if __OBJC2__
434 #include "objc-file.h"
435 #else
436 #include "objc-file-old.h"
437 #endif
438
439 void
440 map_images_nolock(unsigned mhCount, const char * const mhPaths[],
441 const struct mach_header * const mhdrs[])
442 {
443 static bool firstTime = YES;
444 header_info *hList[mhCount];
445 uint32_t hCount;
446 size_t selrefCount = 0;
447
448 // Perform first-time initialization if necessary.
449 // This function is called before ordinary library initializers.
450 // fixme defer initialization until an objc-using image is found?
451 if (firstTime) {
452 preopt_init();
453 }
454
455 if (PrintImages) {
456 _objc_inform("IMAGES: processing %u newly-mapped images...\n", mhCount);
457 }
458
459
460 // Find all images with Objective-C metadata.
461 hCount = 0;
462
463 // Count classes. Size various table based on the total.
464 int totalClasses = 0;
465 int unoptimizedTotalClasses = 0;
466 {
467 uint32_t i = mhCount;
468 while (i--) {
469 const headerType *mhdr = (const headerType *)mhdrs[i];
470
471 auto hi = addHeader(mhdr, mhPaths[i], totalClasses, unoptimizedTotalClasses);
472 if (!hi) {
473 // no objc data in this entry
474 continue;
475 }
476
477 if (mhdr->filetype == MH_EXECUTE) {
478 // Size some data structures based on main executable's size
479 #if __OBJC2__
480 size_t count;
481 _getObjc2SelectorRefs(hi, &count);
482 selrefCount += count;
483 _getObjc2MessageRefs(hi, &count);
484 selrefCount += count;
485 #else
486 _getObjcSelectorRefs(hi, &selrefCount);
487 #endif
488
489 #if SUPPORT_GC_COMPAT
490 // Halt if this is a GC app.
491 if (shouldRejectGCApp(hi)) {
492 _objc_fatal_with_reason
493 (OBJC_EXIT_REASON_GC_NOT_SUPPORTED,
494 OS_REASON_FLAG_CONSISTENT_FAILURE,
495 "Objective-C garbage collection "
496 "is no longer supported.");
497 }
498 #endif
499 }
500
501 hList[hCount++] = hi;
502
503 if (PrintImages) {
504 _objc_inform("IMAGES: loading image for %s%s%s%s%s\n",
505 hi->fname(),
506 mhdr->filetype == MH_BUNDLE ? " (bundle)" : "",
507 hi->info()->isReplacement() ? " (replacement)" : "",
508 hi->info()->hasCategoryClassProperties() ? " (has class properties)" : "",
509 hi->info()->optimizedByDyld()?" (preoptimized)":"");
510 }
511 }
512 }
513
514 // Perform one-time runtime initialization that must be deferred until
515 // the executable itself is found. This needs to be done before
516 // further initialization.
517 // (The executable may not be present in this infoList if the
518 // executable does not contain Objective-C code but Objective-C
519 // is dynamically loaded later.
520 if (firstTime) {
521 sel_init(selrefCount);
522 arr_init();
523
524 #if SUPPORT_GC_COMPAT
525 // Reject any GC images linked to the main executable.
526 // We already rejected the app itself above.
527 // Images loaded after launch will be rejected by dyld.
528
529 for (uint32_t i = 0; i < hCount; i++) {
530 auto hi = hList[i];
531 auto mh = hi->mhdr();
532 if (mh->filetype != MH_EXECUTE && shouldRejectGCImage(mh)) {
533 _objc_fatal_with_reason
534 (OBJC_EXIT_REASON_GC_NOT_SUPPORTED,
535 OS_REASON_FLAG_CONSISTENT_FAILURE,
536 "%s requires Objective-C garbage collection "
537 "which is no longer supported.", hi->fname());
538 }
539 }
540 #endif
541 }
542
543 if (hCount > 0) {
544 _read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
545 }
546
547 firstTime = NO;
548 }
549
550
551 /***********************************************************************
552 * unmap_image_nolock
553 * Process the given image which is about to be unmapped by dyld.
554 * mh is mach_header instead of headerType because that's what
555 * dyld_priv.h says even for 64-bit.
556 *
557 * Locking: loadMethodLock(both) and runtimeLock(new) acquired by unmap_image.
558 **********************************************************************/
559 void
560 unmap_image_nolock(const struct mach_header *mh)
561 {
562 if (PrintImages) {
563 _objc_inform("IMAGES: processing 1 newly-unmapped image...\n");
564 }
565
566 header_info *hi;
567
568 // Find the runtime's header_info struct for the image
569 for (hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
570 if (hi->mhdr() == (const headerType *)mh) {
571 break;
572 }
573 }
574
575 if (!hi) return;
576
577 if (PrintImages) {
578 _objc_inform("IMAGES: unloading image for %s%s%s\n",
579 hi->fname(),
580 hi->mhdr()->filetype == MH_BUNDLE ? " (bundle)" : "",
581 hi->info()->isReplacement() ? " (replacement)" : "");
582 }
583
584 _unload_image(hi);
585
586 // Remove header_info from header list
587 removeHeader(hi);
588 free(hi);
589 }
590
591
592 /***********************************************************************
593 * static_init
594 * Run C++ static constructor functions.
595 * libc calls _objc_init() before dyld would call our static constructors,
596 * so we have to do it ourselves.
597 **********************************************************************/
598 static void static_init()
599 {
600 size_t count;
601 Initializer *inits = getLibobjcInitializers(&_mh_dylib_header, &count);
602 for (size_t i = 0; i < count; i++) {
603 inits[i]();
604 }
605 }
606
607
608 /***********************************************************************
609 * _objc_atfork_prepare
610 * _objc_atfork_parent
611 * _objc_atfork_child
612 * Allow ObjC to be used between fork() and exec().
613 * libc requires this because it has fork-safe functions that use os_objects.
614 *
615 * _objc_atfork_prepare() acquires all locks.
616 * _objc_atfork_parent() releases the locks again.
617 * _objc_atfork_child() forcibly resets the locks.
618 **********************************************************************/
619
620 // Declare lock ordering.
621 #if DEBUG
622 __attribute__((constructor))
623 static void defineLockOrder()
624 {
625 // Every lock precedes crashlog_lock
626 // on the assumption that fatal errors could be anywhere.
627 lockdebug_lock_precedes_lock(&loadMethodLock, &crashlog_lock);
628 lockdebug_lock_precedes_lock(&classInitLock, &crashlog_lock);
629 #if __OBJC2__
630 lockdebug_lock_precedes_lock(&runtimeLock, &crashlog_lock);
631 lockdebug_lock_precedes_lock(&DemangleCacheLock, &crashlog_lock);
632 #else
633 lockdebug_lock_precedes_lock(&classLock, &crashlog_lock);
634 lockdebug_lock_precedes_lock(&methodListLock, &crashlog_lock);
635 lockdebug_lock_precedes_lock(&NXUniqueStringLock, &crashlog_lock);
636 lockdebug_lock_precedes_lock(&impLock, &crashlog_lock);
637 #endif
638 lockdebug_lock_precedes_lock(&selLock, &crashlog_lock);
639 lockdebug_lock_precedes_lock(&cacheUpdateLock, &crashlog_lock);
640 lockdebug_lock_precedes_lock(&objcMsgLogLock, &crashlog_lock);
641 lockdebug_lock_precedes_lock(&AltHandlerDebugLock, &crashlog_lock);
642 lockdebug_lock_precedes_lock(&AssociationsManagerLock, &crashlog_lock);
643 SideTableLocksPrecedeLock(&crashlog_lock);
644 PropertyLocks.precedeLock(&crashlog_lock);
645 StructLocks.precedeLock(&crashlog_lock);
646 CppObjectLocks.precedeLock(&crashlog_lock);
647
648 // loadMethodLock precedes everything
649 // because it is held while +load methods run
650 lockdebug_lock_precedes_lock(&loadMethodLock, &classInitLock);
651 #if __OBJC2__
652 lockdebug_lock_precedes_lock(&loadMethodLock, &runtimeLock);
653 lockdebug_lock_precedes_lock(&loadMethodLock, &DemangleCacheLock);
654 #else
655 lockdebug_lock_precedes_lock(&loadMethodLock, &methodListLock);
656 lockdebug_lock_precedes_lock(&loadMethodLock, &classLock);
657 lockdebug_lock_precedes_lock(&loadMethodLock, &NXUniqueStringLock);
658 lockdebug_lock_precedes_lock(&loadMethodLock, &impLock);
659 #endif
660 lockdebug_lock_precedes_lock(&loadMethodLock, &selLock);
661 lockdebug_lock_precedes_lock(&loadMethodLock, &cacheUpdateLock);
662 lockdebug_lock_precedes_lock(&loadMethodLock, &objcMsgLogLock);
663 lockdebug_lock_precedes_lock(&loadMethodLock, &AltHandlerDebugLock);
664 lockdebug_lock_precedes_lock(&loadMethodLock, &AssociationsManagerLock);
665 SideTableLocksSucceedLock(&loadMethodLock);
666 PropertyLocks.succeedLock(&loadMethodLock);
667 StructLocks.succeedLock(&loadMethodLock);
668 CppObjectLocks.succeedLock(&loadMethodLock);
669
670 // PropertyLocks and CppObjectLocks precede everything
671 // because they are held while objc_retain() or C++ copy are called.
672 // (StructLocks do not precede everything because it calls memmove only.)
673 PropertyLocks.precedeLock(&classInitLock);
674 CppObjectLocks.precedeLock(&classInitLock);
675 #if __OBJC2__
676 PropertyLocks.precedeLock(&runtimeLock);
677 CppObjectLocks.precedeLock(&runtimeLock);
678 PropertyLocks.precedeLock(&DemangleCacheLock);
679 CppObjectLocks.precedeLock(&DemangleCacheLock);
680 #else
681 PropertyLocks.precedeLock(&methodListLock);
682 CppObjectLocks.precedeLock(&methodListLock);
683 PropertyLocks.precedeLock(&classLock);
684 CppObjectLocks.precedeLock(&classLock);
685 PropertyLocks.precedeLock(&NXUniqueStringLock);
686 CppObjectLocks.precedeLock(&NXUniqueStringLock);
687 PropertyLocks.precedeLock(&impLock);
688 CppObjectLocks.precedeLock(&impLock);
689 #endif
690 PropertyLocks.precedeLock(&selLock);
691 CppObjectLocks.precedeLock(&selLock);
692 PropertyLocks.precedeLock(&cacheUpdateLock);
693 CppObjectLocks.precedeLock(&cacheUpdateLock);
694 PropertyLocks.precedeLock(&objcMsgLogLock);
695 CppObjectLocks.precedeLock(&objcMsgLogLock);
696 PropertyLocks.precedeLock(&AltHandlerDebugLock);
697 CppObjectLocks.precedeLock(&AltHandlerDebugLock);
698 PropertyLocks.precedeLock(&AssociationsManagerLock);
699 CppObjectLocks.precedeLock(&AssociationsManagerLock);
700 // fixme side table
701
702 #if __OBJC2__
703 lockdebug_lock_precedes_lock(&classInitLock, &runtimeLock);
704 #endif
705
706 #if __OBJC2__
707 // Runtime operations may occur inside SideTable locks
708 // (such as storeWeak calling getMethodImplementation)
709 SideTableLocksPrecedeLock(&runtimeLock);
710 // Some operations may occur inside runtimeLock.
711 lockdebug_lock_precedes_lock(&runtimeLock, &selLock);
712 lockdebug_lock_precedes_lock(&runtimeLock, &cacheUpdateLock);
713 lockdebug_lock_precedes_lock(&runtimeLock, &DemangleCacheLock);
714 #else
715 // Runtime operations may occur inside SideTable locks
716 // (such as storeWeak calling getMethodImplementation)
717 SideTableLocksPrecedeLock(&methodListLock);
718 // Method lookup and fixup.
719 lockdebug_lock_precedes_lock(&methodListLock, &classLock);
720 lockdebug_lock_precedes_lock(&methodListLock, &selLock);
721 lockdebug_lock_precedes_lock(&methodListLock, &cacheUpdateLock);
722 lockdebug_lock_precedes_lock(&methodListLock, &impLock);
723 lockdebug_lock_precedes_lock(&classLock, &selLock);
724 lockdebug_lock_precedes_lock(&classLock, &cacheUpdateLock);
725 #endif
726
727 // Striped locks use address order internally.
728 SideTableDefineLockOrder();
729 PropertyLocks.defineLockOrder();
730 StructLocks.defineLockOrder();
731 CppObjectLocks.defineLockOrder();
732 }
733 // DEBUG
734 #endif
735
736 void _objc_atfork_prepare()
737 {
738 lockdebug_assert_no_locks_locked();
739 lockdebug_setInForkPrepare(true);
740
741 loadMethodLock.lock();
742 PropertyLocks.lockAll();
743 CppObjectLocks.lockAll();
744 AssociationsManagerLock.lock();
745 SideTableLockAll();
746 classInitLock.enter();
747 #if __OBJC2__
748 runtimeLock.write();
749 DemangleCacheLock.lock();
750 #else
751 methodListLock.lock();
752 classLock.lock();
753 NXUniqueStringLock.lock();
754 impLock.lock();
755 #endif
756 selLock.write();
757 cacheUpdateLock.lock();
758 objcMsgLogLock.lock();
759 AltHandlerDebugLock.lock();
760 StructLocks.lockAll();
761 crashlog_lock.lock();
762
763 lockdebug_assert_all_locks_locked();
764 lockdebug_setInForkPrepare(false);
765 }
766
767 void _objc_atfork_parent()
768 {
769 lockdebug_assert_all_locks_locked();
770
771 CppObjectLocks.unlockAll();
772 StructLocks.unlockAll();
773 PropertyLocks.unlockAll();
774 AssociationsManagerLock.unlock();
775 AltHandlerDebugLock.unlock();
776 objcMsgLogLock.unlock();
777 crashlog_lock.unlock();
778 loadMethodLock.unlock();
779 cacheUpdateLock.unlock();
780 selLock.unlockWrite();
781 SideTableUnlockAll();
782 #if __OBJC2__
783 DemangleCacheLock.unlock();
784 runtimeLock.unlockWrite();
785 #else
786 impLock.unlock();
787 NXUniqueStringLock.unlock();
788 methodListLock.unlock();
789 classLock.unlock();
790 #endif
791 classInitLock.leave();
792
793 lockdebug_assert_no_locks_locked();
794 }
795
796 void _objc_atfork_child()
797 {
798 lockdebug_assert_all_locks_locked();
799
800 CppObjectLocks.forceResetAll();
801 StructLocks.forceResetAll();
802 PropertyLocks.forceResetAll();
803 AssociationsManagerLock.forceReset();
804 AltHandlerDebugLock.forceReset();
805 objcMsgLogLock.forceReset();
806 crashlog_lock.forceReset();
807 loadMethodLock.forceReset();
808 cacheUpdateLock.forceReset();
809 selLock.forceReset();
810 SideTableForceResetAll();
811 #if __OBJC2__
812 DemangleCacheLock.forceReset();
813 runtimeLock.forceReset();
814 #else
815 impLock.forceReset();
816 NXUniqueStringLock.forceReset();
817 methodListLock.forceReset();
818 classLock.forceReset();
819 #endif
820 classInitLock.forceReset();
821
822 lockdebug_assert_no_locks_locked();
823 }
824
825
826 /***********************************************************************
827 * _objc_init
828 * Bootstrap initialization. Registers our image notifier with dyld.
829 * Called by libSystem BEFORE library initialization time
830 **********************************************************************/
831
832 void _objc_init(void)
833 {
834 static bool initialized = false;
835 if (initialized) return;
836 initialized = true;
837
838 // fixme defer initialization until an objc-using image is found?
839 environ_init();
840 tls_init();
841 static_init();
842 lock_init();
843 exception_init();
844
845 _dyld_objc_notify_register(&map_images, load_images, unmap_image);
846 }
847
848
849 /***********************************************************************
850 * _headerForAddress.
851 * addr can be a class or a category
852 **********************************************************************/
853 static const header_info *_headerForAddress(void *addr)
854 {
855 #if __OBJC2__
856 const char *segnames[] = { "__DATA", "__DATA_CONST", "__DATA_DIRTY" };
857 #else
858 const char *segnames[] = { "__OBJC" };
859 #endif
860 header_info *hi;
861
862 for (hi = FirstHeader; hi != NULL; hi = hi->getNext()) {
863 for (size_t i = 0; i < sizeof(segnames)/sizeof(segnames[0]); i++) {
864 unsigned long seg_size;
865 uint8_t *seg = getsegmentdata(hi->mhdr(), segnames[i], &seg_size);
866 if (!seg) continue;
867
868 // Is the class in this header?
869 if ((uint8_t *)addr >= seg && (uint8_t *)addr < seg + seg_size) {
870 return hi;
871 }
872 }
873 }
874
875 // Not found
876 return 0;
877 }
878
879
880 /***********************************************************************
881 * _headerForClass
882 * Return the image header containing this class, or NULL.
883 * Returns NULL on runtime-constructed classes, and the NSCF classes.
884 **********************************************************************/
885 const header_info *_headerForClass(Class cls)
886 {
887 return _headerForAddress(cls);
888 }
889
890
891 /**********************************************************************
892 * secure_open
893 * Securely open a file from a world-writable directory (like /tmp)
894 * If the file does not exist, it will be atomically created with mode 0600
895 * If the file exists, it must be, and remain after opening:
896 * 1. a regular file (in particular, not a symlink)
897 * 2. owned by euid
898 * 3. permissions 0600
899 * 4. link count == 1
900 * Returns a file descriptor or -1. Errno may or may not be set on error.
901 **********************************************************************/
902 int secure_open(const char *filename, int flags, uid_t euid)
903 {
904 struct stat fs, ls;
905 int fd = -1;
906 bool truncate = NO;
907 bool create = NO;
908
909 if (flags & O_TRUNC) {
910 // Don't truncate the file until after it is open and verified.
911 truncate = YES;
912 flags &= ~O_TRUNC;
913 }
914 if (flags & O_CREAT) {
915 // Don't create except when we're ready for it
916 create = YES;
917 flags &= ~O_CREAT;
918 flags &= ~O_EXCL;
919 }
920
921 if (lstat(filename, &ls) < 0) {
922 if (errno == ENOENT && create) {
923 // No such file - create it
924 fd = open(filename, flags | O_CREAT | O_EXCL, 0600);
925 if (fd >= 0) {
926 // File was created successfully.
927 // New file does not need to be truncated.
928 return fd;
929 } else {
930 // File creation failed.
931 return -1;
932 }
933 } else {
934 // lstat failed, or user doesn't want to create the file
935 return -1;
936 }
937 } else {
938 // lstat succeeded - verify attributes and open
939 if (S_ISREG(ls.st_mode) && // regular file?
940 ls.st_nlink == 1 && // link count == 1?
941 ls.st_uid == euid && // owned by euid?
942 (ls.st_mode & ALLPERMS) == (S_IRUSR | S_IWUSR)) // mode 0600?
943 {
944 // Attributes look ok - open it and check attributes again
945 fd = open(filename, flags, 0000);
946 if (fd >= 0) {
947 // File is open - double-check attributes
948 if (0 == fstat(fd, &fs) &&
949 fs.st_nlink == ls.st_nlink && // link count == 1?
950 fs.st_uid == ls.st_uid && // owned by euid?
951 fs.st_mode == ls.st_mode && // regular file, 0600?
952 fs.st_ino == ls.st_ino && // same inode as before?
953 fs.st_dev == ls.st_dev) // same device as before?
954 {
955 // File is open and OK
956 if (truncate) ftruncate(fd, 0);
957 return fd;
958 } else {
959 // Opened file looks funny - close it
960 close(fd);
961 return -1;
962 }
963 } else {
964 // File didn't open
965 return -1;
966 }
967 } else {
968 // Unopened file looks funny - don't open it
969 return -1;
970 }
971 }
972 }
973
974
975 #if TARGET_OS_IPHONE
976
977 const char *__crashreporter_info__ = NULL;
978
979 const char *CRSetCrashLogMessage(const char *msg)
980 {
981 __crashreporter_info__ = msg;
982 return msg;
983 }
984 const char *CRGetCrashLogMessage(void)
985 {
986 return __crashreporter_info__;
987 }
988
989 #endif
990
991 // TARGET_OS_MAC
992 #else
993
994
995 #error unknown OS
996
997
998 #endif