]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-os.h
objc4-818.2.tar.gz
[apple/objc4.git] / runtime / objc-os.h
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.h
26 * OS portability layer.
27 **********************************************************************/
28
29 #ifndef _OBJC_OS_H
30 #define _OBJC_OS_H
31
32 #include <atomic>
33 #include <TargetConditionals.h>
34 #include "objc-config.h"
35 #include "objc-private.h"
36
37 #ifdef __LP64__
38 # define WORD_SHIFT 3UL
39 # define WORD_MASK 7UL
40 # define WORD_BITS 64
41 #else
42 # define WORD_SHIFT 2UL
43 # define WORD_MASK 3UL
44 # define WORD_BITS 32
45 #endif
46
47 static inline uint32_t word_align(uint32_t x) {
48 return (x + WORD_MASK) & ~WORD_MASK;
49 }
50 static inline size_t word_align(size_t x) {
51 return (x + WORD_MASK) & ~WORD_MASK;
52 }
53 static inline size_t align16(size_t x) {
54 return (x + size_t(15)) & ~size_t(15);
55 }
56
57 // Mix-in for classes that must not be copied.
58 class nocopy_t {
59 private:
60 nocopy_t(const nocopy_t&) = delete;
61 const nocopy_t& operator=(const nocopy_t&) = delete;
62 protected:
63 constexpr nocopy_t() = default;
64 ~nocopy_t() = default;
65 };
66
67 // Version of std::atomic that does not allow implicit conversions
68 // to/from the wrapped type, and requires an explicit memory order
69 // be passed to load() and store().
70 template <typename T>
71 struct explicit_atomic : public std::atomic<T> {
72 explicit explicit_atomic(T initial) noexcept : std::atomic<T>(std::move(initial)) {}
73 operator T() const = delete;
74
75 T load(std::memory_order order) const noexcept {
76 return std::atomic<T>::load(order);
77 }
78 void store(T desired, std::memory_order order) noexcept {
79 std::atomic<T>::store(desired, order);
80 }
81
82 // Convert a normal pointer to an atomic pointer. This is a
83 // somewhat dodgy thing to do, but if the atomic type is lock
84 // free and the same size as the non-atomic type, we know the
85 // representations are the same, and the compiler generates good
86 // code.
87 static explicit_atomic<T> *from_pointer(T *ptr) {
88 static_assert(sizeof(explicit_atomic<T> *) == sizeof(T *),
89 "Size of atomic must match size of original");
90 explicit_atomic<T> *atomic = (explicit_atomic<T> *)ptr;
91 ASSERT(atomic->is_lock_free());
92 return atomic;
93 }
94 };
95
96 namespace objc {
97 static inline uintptr_t mask16ShiftBits(uint16_t mask)
98 {
99 // returns by how much 0xffff must be shifted "right" to return mask
100 uintptr_t maskShift = __builtin_clz(mask) - 16;
101 ASSERT((0xffff >> maskShift) == mask);
102 return maskShift;
103 }
104 }
105
106 #if TARGET_OS_MAC
107
108 # define OS_UNFAIR_LOCK_INLINE 1
109
110 # ifndef __STDC_LIMIT_MACROS
111 # define __STDC_LIMIT_MACROS
112 # endif
113
114 # include <stdio.h>
115 # include <stdlib.h>
116 # include <stdint.h>
117 # include <stdarg.h>
118 # include <string.h>
119 # include <ctype.h>
120 # include <errno.h>
121 # include <dlfcn.h>
122 # include <fcntl.h>
123 # include <assert.h>
124 # include <limits.h>
125 # include <syslog.h>
126 # include <unistd.h>
127 # include <pthread.h>
128 # include <crt_externs.h>
129 # undef check
130 # include <Availability.h>
131 # include <TargetConditionals.h>
132 # include <sys/mman.h>
133 # include <sys/time.h>
134 # include <sys/stat.h>
135 # include <sys/param.h>
136 # include <sys/reason.h>
137 # include <mach/mach.h>
138 # include <mach/vm_param.h>
139 # include <mach/mach_time.h>
140 # include <mach-o/dyld.h>
141 # include <mach-o/ldsyms.h>
142 # include <mach-o/loader.h>
143 # include <mach-o/getsect.h>
144 # include <mach-o/dyld_priv.h>
145 # include <malloc/malloc.h>
146 # include <os/lock_private.h>
147 # include <libkern/OSAtomic.h>
148 # include <libkern/OSCacheControl.h>
149 # include <System/pthread_machdep.h>
150 # include "objc-probes.h" // generated dtrace probe definitions.
151
152 // Some libc functions call objc_msgSend()
153 // so we can't use them without deadlocks.
154 void syslog(int, const char *, ...) UNAVAILABLE_ATTRIBUTE;
155 void vsyslog(int, const char *, va_list) UNAVAILABLE_ATTRIBUTE;
156
157
158 #define ALWAYS_INLINE inline __attribute__((always_inline))
159 #define NEVER_INLINE __attribute__((noinline))
160
161 #define fastpath(x) (__builtin_expect(bool(x), 1))
162 #define slowpath(x) (__builtin_expect(bool(x), 0))
163
164
165 static ALWAYS_INLINE uintptr_t
166 addc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout)
167 {
168 return __builtin_addcl(lhs, rhs, carryin, carryout);
169 }
170
171 static ALWAYS_INLINE uintptr_t
172 subc(uintptr_t lhs, uintptr_t rhs, uintptr_t carryin, uintptr_t *carryout)
173 {
174 return __builtin_subcl(lhs, rhs, carryin, carryout);
175 }
176
177 #if __arm64__ && !__arm64e__
178
179 static ALWAYS_INLINE
180 uintptr_t
181 LoadExclusive(uintptr_t *src)
182 {
183 return __builtin_arm_ldrex(src);
184 }
185
186 static ALWAYS_INLINE
187 bool
188 StoreExclusive(uintptr_t *dst, uintptr_t *oldvalue, uintptr_t value)
189 {
190 if (slowpath(__builtin_arm_strex(value, dst))) {
191 *oldvalue = LoadExclusive(dst);
192 return false;
193 }
194 return true;
195 }
196
197
198 static ALWAYS_INLINE
199 bool
200 StoreReleaseExclusive(uintptr_t *dst, uintptr_t *oldvalue, uintptr_t value)
201 {
202 if (slowpath(__builtin_arm_stlex(value, dst))) {
203 *oldvalue = LoadExclusive(dst);
204 return false;
205 }
206 return true;
207 }
208
209 static ALWAYS_INLINE
210 void
211 ClearExclusive(uintptr_t *dst __unused)
212 {
213 __builtin_arm_clrex();
214 }
215
216 #else
217
218 static ALWAYS_INLINE
219 uintptr_t
220 LoadExclusive(uintptr_t *src)
221 {
222 return __c11_atomic_load((_Atomic(uintptr_t) *)src, __ATOMIC_RELAXED);
223 }
224
225 static ALWAYS_INLINE
226 bool
227 StoreExclusive(uintptr_t *dst, uintptr_t *oldvalue, uintptr_t value)
228 {
229 return __c11_atomic_compare_exchange_weak((_Atomic(uintptr_t) *)dst, oldvalue, value, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
230 }
231
232
233 static ALWAYS_INLINE
234 bool
235 StoreReleaseExclusive(uintptr_t *dst, uintptr_t *oldvalue, uintptr_t value)
236 {
237 return __c11_atomic_compare_exchange_weak((_Atomic(uintptr_t) *)dst, oldvalue, value, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
238 }
239
240 static ALWAYS_INLINE
241 void
242 ClearExclusive(uintptr_t *dst __unused)
243 {
244 }
245
246 #endif
247
248
249 #if !TARGET_OS_IPHONE
250 # include <CrashReporterClient.h>
251 #else
252 // CrashReporterClient not yet available on iOS
253 __BEGIN_DECLS
254 extern const char *CRSetCrashLogMessage(const char *msg);
255 extern const char *CRGetCrashLogMessage(void);
256 __END_DECLS
257 #endif
258
259 # if __cplusplus
260 # include <vector>
261 # include <algorithm>
262 # include <functional>
263 using namespace std;
264 # endif
265
266 # define PRIVATE_EXTERN __attribute__((visibility("hidden")))
267 # undef __private_extern__
268 # define __private_extern__ use_PRIVATE_EXTERN_instead
269 # undef private_extern
270 # define private_extern use_PRIVATE_EXTERN_instead
271
272 /* Use this for functions that are intended to be breakpoint hooks.
273 If you do not, the compiler may optimize them away.
274 BREAKPOINT_FUNCTION( void stop_on_error(void) ); */
275 # define BREAKPOINT_FUNCTION(prototype) \
276 OBJC_EXTERN __attribute__((noinline, used, visibility("hidden"))) \
277 prototype { asm(""); }
278
279 #elif TARGET_OS_WIN32
280
281 # define WINVER 0x0501 // target Windows XP and later
282 # define _WIN32_WINNT 0x0501 // target Windows XP and later
283 # define WIN32_LEAN_AND_MEAN
284 // hack: windef.h typedefs BOOL as int
285 # define BOOL WINBOOL
286 # include <windows.h>
287 # undef BOOL
288
289 # include <stdio.h>
290 # include <stdlib.h>
291 # include <stdint.h>
292 # include <stdarg.h>
293 # include <string.h>
294 # include <assert.h>
295 # include <malloc.h>
296 # include <Availability.h>
297
298 # if __cplusplus
299 # include <vector>
300 # include <algorithm>
301 # include <functional>
302 using namespace std;
303 # define __BEGIN_DECLS extern "C" {
304 # define __END_DECLS }
305 # else
306 # define __BEGIN_DECLS /*empty*/
307 # define __END_DECLS /*empty*/
308 # endif
309
310 # define PRIVATE_EXTERN
311 # define __attribute__(x)
312 # define inline __inline
313
314 /* Use this for functions that are intended to be breakpoint hooks.
315 If you do not, the compiler may optimize them away.
316 BREAKPOINT_FUNCTION( void MyBreakpointFunction(void) ); */
317 # define BREAKPOINT_FUNCTION(prototype) \
318 __declspec(noinline) prototype { __asm { } }
319
320 /* stub out dtrace probes */
321 # define OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW() do {} while(0)
322 # define OBJC_RUNTIME_OBJC_EXCEPTION_THROW(arg0) do {} while(0)
323
324 #else
325 # error unknown OS
326 #endif
327
328
329 #include <objc/objc.h>
330 #include <objc/objc-api.h>
331
332 extern void _objc_fatal(const char *fmt, ...)
333 __attribute__((noreturn, cold, format (printf, 1, 2)));
334 extern void _objc_fatal_with_reason(uint64_t reason, uint64_t flags,
335 const char *fmt, ...)
336 __attribute__((noreturn, cold, format (printf, 3, 4)));
337
338 #define INIT_ONCE_PTR(var, create, delete) \
339 do { \
340 if (var) break; \
341 typeof(var) v = create; \
342 while (!var) { \
343 if (OSAtomicCompareAndSwapPtrBarrier(0, (void*)v, (void**)&var)){ \
344 goto done; \
345 } \
346 } \
347 delete; \
348 done:; \
349 } while (0)
350
351 #define INIT_ONCE_32(var, create, delete) \
352 do { \
353 if (var) break; \
354 typeof(var) v = create; \
355 while (!var) { \
356 if (OSAtomicCompareAndSwap32Barrier(0, v, (volatile int32_t *)&var)) { \
357 goto done; \
358 } \
359 } \
360 delete; \
361 done:; \
362 } while (0)
363
364
365 // Thread keys reserved by libc for our use.
366 #if defined(__PTK_FRAMEWORK_OBJC_KEY0)
367 # define SUPPORT_DIRECT_THREAD_KEYS 1
368 # define TLS_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY0)
369 # define SYNC_DATA_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY1)
370 # define SYNC_COUNT_DIRECT_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY2)
371 # define AUTORELEASE_POOL_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY3)
372 # if SUPPORT_RETURN_AUTORELEASE
373 # define RETURN_DISPOSITION_KEY ((tls_key_t)__PTK_FRAMEWORK_OBJC_KEY4)
374 # endif
375 #else
376 # define SUPPORT_DIRECT_THREAD_KEYS 0
377 #endif
378
379
380 #if TARGET_OS_WIN32
381
382 // Compiler compatibility
383
384 // OS compatibility
385
386 #define strdup _strdup
387
388 #define issetugid() 0
389
390 #define MIN(x, y) ((x) < (y) ? (x) : (y))
391
392 static __inline void bcopy(const void *src, void *dst, size_t size) { memcpy(dst, src, size); }
393 static __inline void bzero(void *dst, size_t size) { memset(dst, 0, size); }
394
395 int asprintf(char **dstp, const char *format, ...);
396
397 typedef void * malloc_zone_t;
398
399 static __inline malloc_zone_t malloc_default_zone(void) { return (malloc_zone_t)-1; }
400 static __inline void *malloc_zone_malloc(malloc_zone_t z, size_t size) { return malloc(size); }
401 static __inline void *malloc_zone_calloc(malloc_zone_t z, size_t size, size_t count) { return calloc(size, count); }
402 static __inline void *malloc_zone_realloc(malloc_zone_t z, void *p, size_t size) { return realloc(p, size); }
403 static __inline void malloc_zone_free(malloc_zone_t z, void *p) { free(p); }
404 static __inline malloc_zone_t malloc_zone_from_ptr(const void *p) { return (malloc_zone_t)-1; }
405 static __inline size_t malloc_size(const void *p) { return _msize((void*)p); /* fixme invalid pointer check? */ }
406
407
408 // OSAtomic
409
410 static __inline BOOL OSAtomicCompareAndSwapLong(long oldl, long newl, long volatile *dst)
411 {
412 // fixme barrier is overkill
413 long original = InterlockedCompareExchange(dst, newl, oldl);
414 return (original == oldl);
415 }
416
417 static __inline BOOL OSAtomicCompareAndSwapPtrBarrier(void *oldp, void *newp, void * volatile *dst)
418 {
419 void *original = InterlockedCompareExchangePointer(dst, newp, oldp);
420 return (original == oldp);
421 }
422
423 static __inline BOOL OSAtomicCompareAndSwap32Barrier(int32_t oldl, int32_t newl, int32_t volatile *dst)
424 {
425 long original = InterlockedCompareExchange((volatile long *)dst, newl, oldl);
426 return (original == oldl);
427 }
428
429 static __inline int32_t OSAtomicDecrement32Barrier(volatile int32_t *dst)
430 {
431 return InterlockedDecrement((volatile long *)dst);
432 }
433
434 static __inline int32_t OSAtomicIncrement32Barrier(volatile int32_t *dst)
435 {
436 return InterlockedIncrement((volatile long *)dst);
437 }
438
439
440 // Internal data types
441
442 typedef DWORD objc_thread_t; // thread ID
443 static __inline int thread_equal(objc_thread_t t1, objc_thread_t t2) {
444 return t1 == t2;
445 }
446 static __inline objc_thread_t objc_thread_self(void) {
447 return GetCurrentThreadId();
448 }
449
450 typedef struct {
451 DWORD key;
452 void (*dtor)(void *);
453 } tls_key_t;
454 static __inline tls_key_t tls_create(void (*dtor)(void*)) {
455 // fixme need dtor registry for DllMain to call on thread detach
456 tls_key_t k;
457 k.key = TlsAlloc();
458 k.dtor = dtor;
459 return k;
460 }
461 static __inline void *tls_get(tls_key_t k) {
462 return TlsGetValue(k.key);
463 }
464 static __inline void tls_set(tls_key_t k, void *value) {
465 TlsSetValue(k.key, value);
466 }
467
468 typedef struct {
469 CRITICAL_SECTION *lock;
470 } mutex_t;
471 #define MUTEX_INITIALIZER {0};
472 extern void mutex_init(mutex_t *m);
473 static __inline int _mutex_lock_nodebug(mutex_t *m) {
474 // fixme error check
475 if (!m->lock) {
476 mutex_init(m);
477 }
478 EnterCriticalSection(m->lock);
479 return 0;
480 }
481 static __inline bool _mutex_try_lock_nodebug(mutex_t *m) {
482 // fixme error check
483 if (!m->lock) {
484 mutex_init(m);
485 }
486 return TryEnterCriticalSection(m->lock);
487 }
488 static __inline int _mutex_unlock_nodebug(mutex_t *m) {
489 // fixme error check
490 LeaveCriticalSection(m->lock);
491 return 0;
492 }
493
494
495 typedef mutex_t spinlock_t;
496 #define spinlock_lock(l) mutex_lock(l)
497 #define spinlock_unlock(l) mutex_unlock(l)
498 #define SPINLOCK_INITIALIZER MUTEX_INITIALIZER
499
500
501 typedef struct {
502 HANDLE mutex;
503 } recursive_mutex_t;
504 #define RECURSIVE_MUTEX_INITIALIZER {0};
505 #define RECURSIVE_MUTEX_NOT_LOCKED 1
506 extern void recursive_mutex_init(recursive_mutex_t *m);
507 static __inline int _recursive_mutex_lock_nodebug(recursive_mutex_t *m) {
508 ASSERT(m->mutex);
509 return WaitForSingleObject(m->mutex, INFINITE);
510 }
511 static __inline bool _recursive_mutex_try_lock_nodebug(recursive_mutex_t *m) {
512 ASSERT(m->mutex);
513 return (WAIT_OBJECT_0 == WaitForSingleObject(m->mutex, 0));
514 }
515 static __inline int _recursive_mutex_unlock_nodebug(recursive_mutex_t *m) {
516 ASSERT(m->mutex);
517 return ReleaseMutex(m->mutex) ? 0 : RECURSIVE_MUTEX_NOT_LOCKED;
518 }
519
520
521 /*
522 typedef HANDLE mutex_t;
523 static inline void mutex_init(HANDLE *m) { *m = CreateMutex(NULL, FALSE, NULL); }
524 static inline void _mutex_lock(mutex_t *m) { WaitForSingleObject(*m, INFINITE); }
525 static inline bool mutex_try_lock(mutex_t *m) { return WaitForSingleObject(*m, 0) == WAIT_OBJECT_0; }
526 static inline void _mutex_unlock(mutex_t *m) { ReleaseMutex(*m); }
527 */
528
529 // based on http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
530 // Vista-only CONDITION_VARIABLE would be better
531 typedef struct {
532 HANDLE mutex;
533 HANDLE waiters; // semaphore for those in cond_wait()
534 HANDLE waitersDone; // auto-reset event after everyone gets a broadcast
535 CRITICAL_SECTION waitCountLock; // guards waitCount and didBroadcast
536 unsigned int waitCount;
537 int didBroadcast;
538 } monitor_t;
539 #define MONITOR_INITIALIZER { 0 }
540 #define MONITOR_NOT_ENTERED 1
541 extern int monitor_init(monitor_t *c);
542
543 static inline int _monitor_enter_nodebug(monitor_t *c) {
544 if (!c->mutex) {
545 int err = monitor_init(c);
546 if (err) return err;
547 }
548 return WaitForSingleObject(c->mutex, INFINITE);
549 }
550 static inline int _monitor_leave_nodebug(monitor_t *c) {
551 if (!ReleaseMutex(c->mutex)) return MONITOR_NOT_ENTERED;
552 else return 0;
553 }
554 static inline int _monitor_wait_nodebug(monitor_t *c) {
555 int last;
556 EnterCriticalSection(&c->waitCountLock);
557 c->waitCount++;
558 LeaveCriticalSection(&c->waitCountLock);
559
560 SignalObjectAndWait(c->mutex, c->waiters, INFINITE, FALSE);
561
562 EnterCriticalSection(&c->waitCountLock);
563 c->waitCount--;
564 last = c->didBroadcast && c->waitCount == 0;
565 LeaveCriticalSection(&c->waitCountLock);
566
567 if (last) {
568 // tell broadcaster that all waiters have awoken
569 SignalObjectAndWait(c->waitersDone, c->mutex, INFINITE, FALSE);
570 } else {
571 WaitForSingleObject(c->mutex, INFINITE);
572 }
573
574 // fixme error checking
575 return 0;
576 }
577 static inline int monitor_notify(monitor_t *c) {
578 int haveWaiters;
579
580 EnterCriticalSection(&c->waitCountLock);
581 haveWaiters = c->waitCount > 0;
582 LeaveCriticalSection(&c->waitCountLock);
583
584 if (haveWaiters) {
585 ReleaseSemaphore(c->waiters, 1, 0);
586 }
587
588 // fixme error checking
589 return 0;
590 }
591 static inline int monitor_notifyAll(monitor_t *c) {
592 EnterCriticalSection(&c->waitCountLock);
593 if (c->waitCount == 0) {
594 LeaveCriticalSection(&c->waitCountLock);
595 return 0;
596 }
597 c->didBroadcast = 1;
598 ReleaseSemaphore(c->waiters, c->waitCount, 0);
599 LeaveCriticalSection(&c->waitCountLock);
600
601 // fairness: wait for everyone to move from waiters to mutex
602 WaitForSingleObject(c->waitersDone, INFINITE);
603 // not under waitCountLock, but still under mutex
604 c->didBroadcast = 0;
605
606 // fixme error checking
607 return 0;
608 }
609
610
611 typedef IMAGE_DOS_HEADER headerType;
612 // fixme YES bundle? NO bundle? sometimes?
613 #define headerIsBundle(hi) YES
614 OBJC_EXTERN IMAGE_DOS_HEADER __ImageBase;
615 #define libobjc_header ((headerType *)&__ImageBase)
616
617 // Prototypes
618
619
620 #elif TARGET_OS_MAC
621
622
623 // OS headers
624 #include <mach-o/loader.h>
625 #ifndef __LP64__
626 # define SEGMENT_CMD LC_SEGMENT
627 #else
628 # define SEGMENT_CMD LC_SEGMENT_64
629 #endif
630
631 #ifndef VM_MEMORY_OBJC_DISPATCHERS
632 # define VM_MEMORY_OBJC_DISPATCHERS 0
633 #endif
634
635
636 // Compiler compatibility
637
638 // OS compatibility
639
640 static inline uint64_t nanoseconds() {
641 return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
642 }
643
644 // Internal data types
645
646 typedef pthread_t objc_thread_t;
647
648 static __inline int thread_equal(objc_thread_t t1, objc_thread_t t2) {
649 return pthread_equal(t1, t2);
650 }
651
652 typedef pthread_key_t tls_key_t;
653
654 static inline tls_key_t tls_create(void (*dtor)(void*)) {
655 tls_key_t k;
656 pthread_key_create(&k, dtor);
657 return k;
658 }
659 static inline void *tls_get(tls_key_t k) {
660 return pthread_getspecific(k);
661 }
662 static inline void tls_set(tls_key_t k, void *value) {
663 pthread_setspecific(k, value);
664 }
665
666 #if SUPPORT_DIRECT_THREAD_KEYS
667
668 static inline bool is_valid_direct_key(tls_key_t k) {
669 return ( k == SYNC_DATA_DIRECT_KEY
670 || k == SYNC_COUNT_DIRECT_KEY
671 || k == AUTORELEASE_POOL_KEY
672 || k == _PTHREAD_TSD_SLOT_PTHREAD_SELF
673 # if SUPPORT_RETURN_AUTORELEASE
674 || k == RETURN_DISPOSITION_KEY
675 # endif
676 );
677 }
678
679 static inline void *tls_get_direct(tls_key_t k)
680 {
681 ASSERT(is_valid_direct_key(k));
682
683 if (_pthread_has_direct_tsd()) {
684 return _pthread_getspecific_direct(k);
685 } else {
686 return pthread_getspecific(k);
687 }
688 }
689 static inline void tls_set_direct(tls_key_t k, void *value)
690 {
691 ASSERT(is_valid_direct_key(k));
692
693 if (_pthread_has_direct_tsd()) {
694 _pthread_setspecific_direct(k, value);
695 } else {
696 pthread_setspecific(k, value);
697 }
698 }
699
700 __attribute__((const))
701 static inline pthread_t objc_thread_self()
702 {
703 return (pthread_t)tls_get_direct(_PTHREAD_TSD_SLOT_PTHREAD_SELF);
704 }
705 #else
706 __attribute__((const))
707 static inline pthread_t objc_thread_self()
708 {
709 return pthread_self();
710 }
711 #endif // SUPPORT_DIRECT_THREAD_KEYS
712
713
714 template <bool Debug> class mutex_tt;
715 template <bool Debug> class monitor_tt;
716 template <bool Debug> class recursive_mutex_tt;
717
718 #if DEBUG
719 # define LOCKDEBUG 1
720 #else
721 # define LOCKDEBUG 0
722 #endif
723
724 using spinlock_t = mutex_tt<LOCKDEBUG>;
725 using mutex_t = mutex_tt<LOCKDEBUG>;
726 using monitor_t = monitor_tt<LOCKDEBUG>;
727 using recursive_mutex_t = recursive_mutex_tt<LOCKDEBUG>;
728
729 // Use fork_unsafe_lock to get a lock that isn't
730 // acquired and released around fork().
731 // All fork-safe locks are checked in debug builds.
732 struct fork_unsafe_lock_t {
733 constexpr fork_unsafe_lock_t() = default;
734 };
735 extern const fork_unsafe_lock_t fork_unsafe_lock;
736
737 #include "objc-lockdebug.h"
738
739 template <bool Debug>
740 class mutex_tt : nocopy_t {
741 os_unfair_lock mLock;
742 public:
743 constexpr mutex_tt() : mLock(OS_UNFAIR_LOCK_INIT) {
744 lockdebug_remember_mutex(this);
745 }
746
747 constexpr mutex_tt(__unused const fork_unsafe_lock_t unsafe) : mLock(OS_UNFAIR_LOCK_INIT) { }
748
749 void lock() {
750 lockdebug_mutex_lock(this);
751
752 // <rdar://problem/50384154>
753 uint32_t opts = OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION | OS_UNFAIR_LOCK_ADAPTIVE_SPIN;
754 os_unfair_lock_lock_with_options_inline
755 (&mLock, (os_unfair_lock_options_t)opts);
756 }
757
758 void unlock() {
759 lockdebug_mutex_unlock(this);
760
761 os_unfair_lock_unlock_inline(&mLock);
762 }
763
764 void forceReset() {
765 lockdebug_mutex_unlock(this);
766
767 bzero(&mLock, sizeof(mLock));
768 mLock = os_unfair_lock OS_UNFAIR_LOCK_INIT;
769 }
770
771 void assertLocked() {
772 lockdebug_mutex_assert_locked(this);
773 }
774
775 void assertUnlocked() {
776 lockdebug_mutex_assert_unlocked(this);
777 }
778
779
780 // Address-ordered lock discipline for a pair of locks.
781
782 static void lockTwo(mutex_tt *lock1, mutex_tt *lock2) {
783 if ((uintptr_t)lock1 < (uintptr_t)lock2) {
784 lock1->lock();
785 lock2->lock();
786 } else {
787 lock2->lock();
788 if (lock2 != lock1) lock1->lock();
789 }
790 }
791
792 static void unlockTwo(mutex_tt *lock1, mutex_tt *lock2) {
793 lock1->unlock();
794 if (lock2 != lock1) lock2->unlock();
795 }
796
797 // Scoped lock and unlock
798 class locker : nocopy_t {
799 mutex_tt& lock;
800 public:
801 locker(mutex_tt& newLock)
802 : lock(newLock) { lock.lock(); }
803 ~locker() { lock.unlock(); }
804 };
805
806 // Either scoped lock and unlock, or NOP.
807 class conditional_locker : nocopy_t {
808 mutex_tt& lock;
809 bool didLock;
810 public:
811 conditional_locker(mutex_tt& newLock, bool shouldLock)
812 : lock(newLock), didLock(shouldLock)
813 {
814 if (shouldLock) lock.lock();
815 }
816 ~conditional_locker() { if (didLock) lock.unlock(); }
817 };
818 };
819
820 using mutex_locker_t = mutex_tt<LOCKDEBUG>::locker;
821 using conditional_mutex_locker_t = mutex_tt<LOCKDEBUG>::conditional_locker;
822
823
824 template <bool Debug>
825 class recursive_mutex_tt : nocopy_t {
826 os_unfair_recursive_lock mLock;
827
828 public:
829 constexpr recursive_mutex_tt() : mLock(OS_UNFAIR_RECURSIVE_LOCK_INIT) {
830 lockdebug_remember_recursive_mutex(this);
831 }
832
833 constexpr recursive_mutex_tt(__unused const fork_unsafe_lock_t unsafe)
834 : mLock(OS_UNFAIR_RECURSIVE_LOCK_INIT)
835 { }
836
837 void lock()
838 {
839 lockdebug_recursive_mutex_lock(this);
840 os_unfair_recursive_lock_lock(&mLock);
841 }
842
843 void unlock()
844 {
845 lockdebug_recursive_mutex_unlock(this);
846
847 os_unfair_recursive_lock_unlock(&mLock);
848 }
849
850 void forceReset()
851 {
852 lockdebug_recursive_mutex_unlock(this);
853
854 bzero(&mLock, sizeof(mLock));
855 mLock = os_unfair_recursive_lock OS_UNFAIR_RECURSIVE_LOCK_INIT;
856 }
857
858 bool tryLock()
859 {
860 if (os_unfair_recursive_lock_trylock(&mLock)) {
861 lockdebug_recursive_mutex_lock(this);
862 return true;
863 }
864 return false;
865 }
866
867 bool tryUnlock()
868 {
869 if (os_unfair_recursive_lock_tryunlock4objc(&mLock)) {
870 lockdebug_recursive_mutex_unlock(this);
871 return true;
872 }
873 return false;
874 }
875
876 void assertLocked() {
877 lockdebug_recursive_mutex_assert_locked(this);
878 }
879
880 void assertUnlocked() {
881 lockdebug_recursive_mutex_assert_unlocked(this);
882 }
883 };
884
885
886 template <bool Debug>
887 class monitor_tt {
888 pthread_mutex_t mutex;
889 pthread_cond_t cond;
890
891 public:
892 constexpr monitor_tt()
893 : mutex(PTHREAD_MUTEX_INITIALIZER), cond(PTHREAD_COND_INITIALIZER)
894 {
895 lockdebug_remember_monitor(this);
896 }
897
898 monitor_tt(__unused const fork_unsafe_lock_t unsafe)
899 : mutex(PTHREAD_MUTEX_INITIALIZER), cond(PTHREAD_COND_INITIALIZER)
900 { }
901
902 void enter()
903 {
904 lockdebug_monitor_enter(this);
905
906 int err = pthread_mutex_lock(&mutex);
907 if (err) _objc_fatal("pthread_mutex_lock failed (%d)", err);
908 }
909
910 void leave()
911 {
912 lockdebug_monitor_leave(this);
913
914 int err = pthread_mutex_unlock(&mutex);
915 if (err) _objc_fatal("pthread_mutex_unlock failed (%d)", err);
916 }
917
918 void wait()
919 {
920 lockdebug_monitor_wait(this);
921
922 int err = pthread_cond_wait(&cond, &mutex);
923 if (err) _objc_fatal("pthread_cond_wait failed (%d)", err);
924 }
925
926 void notify()
927 {
928 int err = pthread_cond_signal(&cond);
929 if (err) _objc_fatal("pthread_cond_signal failed (%d)", err);
930 }
931
932 void notifyAll()
933 {
934 int err = pthread_cond_broadcast(&cond);
935 if (err) _objc_fatal("pthread_cond_broadcast failed (%d)", err);
936 }
937
938 void forceReset()
939 {
940 lockdebug_monitor_leave(this);
941
942 bzero(&mutex, sizeof(mutex));
943 bzero(&cond, sizeof(cond));
944 mutex = pthread_mutex_t PTHREAD_MUTEX_INITIALIZER;
945 cond = pthread_cond_t PTHREAD_COND_INITIALIZER;
946 }
947
948 void assertLocked()
949 {
950 lockdebug_monitor_assert_locked(this);
951 }
952
953 void assertUnlocked()
954 {
955 lockdebug_monitor_assert_unlocked(this);
956 }
957 };
958
959
960 // semaphore_create formatted for INIT_ONCE use
961 static inline semaphore_t create_semaphore(void)
962 {
963 semaphore_t sem;
964 kern_return_t k;
965 k = semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, 0);
966 if (k) _objc_fatal("semaphore_create failed (0x%x)", k);
967 return sem;
968 }
969
970
971 #ifndef __LP64__
972 typedef struct mach_header headerType;
973 typedef struct segment_command segmentType;
974 typedef struct section sectionType;
975 #else
976 typedef struct mach_header_64 headerType;
977 typedef struct segment_command_64 segmentType;
978 typedef struct section_64 sectionType;
979 #endif
980 #define headerIsBundle(hi) (hi->mhdr()->filetype == MH_BUNDLE)
981 #define libobjc_header ((headerType *)&_mh_dylib_header)
982
983 // Prototypes
984
985 /* Secure /tmp usage */
986 extern int secure_open(const char *filename, int flags, uid_t euid);
987
988
989 #else
990
991
992 #error unknown OS
993
994
995 #endif
996
997
998 static inline void *
999 memdup(const void *mem, size_t len)
1000 {
1001 void *dup = malloc(len);
1002 memcpy(dup, mem, len);
1003 return dup;
1004 }
1005
1006 // strdup that doesn't copy read-only memory
1007 static inline char *
1008 strdupIfMutable(const char *str)
1009 {
1010 size_t size = strlen(str) + 1;
1011 if (_dyld_is_memory_immutable(str, size)) {
1012 return (char *)str;
1013 } else {
1014 return (char *)memdup(str, size);
1015 }
1016 }
1017
1018 // free strdupIfMutable() result
1019 static inline void
1020 freeIfMutable(char *str)
1021 {
1022 size_t size = strlen(str) + 1;
1023 if (_dyld_is_memory_immutable(str, size)) {
1024 // nothing
1025 } else {
1026 free(str);
1027 }
1028 }
1029
1030 // nil-checking unsigned strdup
1031 static inline uint8_t *
1032 ustrdupMaybeNil(const uint8_t *str)
1033 {
1034 if (!str) return nil;
1035 return (uint8_t *)strdupIfMutable((char *)str);
1036 }
1037
1038 // OS version checking:
1039 //
1040 // sdkIsAtLeast(mac, ios, tv, watch, bridge)
1041 //
1042 // This version order matches OBJC_AVAILABLE.
1043 //
1044 // NOTE: prefer dyld_program_sdk_at_least when possible
1045 #define sdkIsAtLeast(x, i, t, w, b) \
1046 (dyld_program_sdk_at_least(dyld_platform_version_macOS_ ## x) || \
1047 dyld_program_sdk_at_least(dyld_platform_version_iOS_ ## i) || \
1048 dyld_program_sdk_at_least(dyld_platform_version_tvOS_ ## t) || \
1049 dyld_program_sdk_at_least(dyld_platform_version_watchOS_ ## w) || \
1050 dyld_program_sdk_at_least(dyld_platform_version_bridgeOS_ ## b))
1051
1052
1053 #ifndef __BUILDING_OBJCDT__
1054 // fork() safety requires careful tracking of all locks.
1055 // Our custom lock types check this in debug builds.
1056 // Disallow direct use of all other lock types.
1057 typedef __darwin_pthread_mutex_t pthread_mutex_t UNAVAILABLE_ATTRIBUTE;
1058 typedef __darwin_pthread_rwlock_t pthread_rwlock_t UNAVAILABLE_ATTRIBUTE;
1059 typedef int32_t OSSpinLock UNAVAILABLE_ATTRIBUTE;
1060 typedef struct os_unfair_lock_s os_unfair_lock UNAVAILABLE_ATTRIBUTE;
1061 #endif
1062
1063 #endif