2 * Copyright (c) 2007 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
24 /***********************************************************************
26 * OS portability layer.
27 **********************************************************************/
33 #include <TargetConditionals.h>
34 #include "objc-config.h"
35 #include "objc-private.h"
38 # define WORD_SHIFT 3UL
39 # define WORD_MASK 7UL
42 # define WORD_SHIFT 2UL
43 # define WORD_MASK 3UL
47 static inline uint32_t word_align(uint32_t x
) {
48 return (x
+ WORD_MASK
) & ~WORD_MASK
;
50 static inline size_t word_align(size_t x
) {
51 return (x
+ WORD_MASK
) & ~WORD_MASK
;
53 static inline size_t align16(size_t x
) {
54 return (x
+ size_t(15)) & ~size_t(15);
57 // Mix-in for classes that must not be copied.
60 nocopy_t(const nocopy_t
&) = delete;
61 const nocopy_t
& operator=(const nocopy_t
&) = delete;
63 constexpr nocopy_t() = default;
64 ~nocopy_t() = default;
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().
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;
75 T
load(std::memory_order order
) const noexcept {
76 return std::atomic
<T
>::load(order
);
78 void store(T desired
, std::memory_order order
) noexcept {
79 std::atomic
<T
>::store(desired
, order
);
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
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());
97 static inline uintptr_t mask16ShiftBits(uint16_t mask
)
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
);
108 # define OS_UNFAIR_LOCK_INLINE 1
110 # ifndef __STDC_LIMIT_MACROS
111 # define __STDC_LIMIT_MACROS
127 # include <pthread.h>
128 # include <crt_externs.h>
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.
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
;
158 #define ALWAYS_INLINE inline __attribute__((always_inline))
159 #define NEVER_INLINE __attribute__((noinline))
161 #define fastpath(x) (__builtin_expect(bool(x), 1))
162 #define slowpath(x) (__builtin_expect(bool(x), 0))
165 static ALWAYS_INLINE
uintptr_t
166 addc(uintptr_t lhs
, uintptr_t rhs
, uintptr_t carryin
, uintptr_t *carryout
)
168 return __builtin_addcl(lhs
, rhs
, carryin
, carryout
);
171 static ALWAYS_INLINE
uintptr_t
172 subc(uintptr_t lhs
, uintptr_t rhs
, uintptr_t carryin
, uintptr_t *carryout
)
174 return __builtin_subcl(lhs
, rhs
, carryin
, carryout
);
177 #if __arm64__ && !__arm64e__
181 LoadExclusive(uintptr_t *src
)
183 return __builtin_arm_ldrex(src
);
188 StoreExclusive(uintptr_t *dst
, uintptr_t *oldvalue
, uintptr_t value
)
190 if (slowpath(__builtin_arm_strex(value
, dst
))) {
191 *oldvalue
= LoadExclusive(dst
);
200 StoreReleaseExclusive(uintptr_t *dst
, uintptr_t *oldvalue
, uintptr_t value
)
202 if (slowpath(__builtin_arm_stlex(value
, dst
))) {
203 *oldvalue
= LoadExclusive(dst
);
211 ClearExclusive(uintptr_t *dst __unused
)
213 __builtin_arm_clrex();
220 LoadExclusive(uintptr_t *src
)
222 return __c11_atomic_load((_Atomic(uintptr_t) *)src
, __ATOMIC_RELAXED
);
227 StoreExclusive(uintptr_t *dst
, uintptr_t *oldvalue
, uintptr_t value
)
229 return __c11_atomic_compare_exchange_weak((_Atomic(uintptr_t) *)dst
, oldvalue
, value
, __ATOMIC_RELAXED
, __ATOMIC_RELAXED
);
235 StoreReleaseExclusive(uintptr_t *dst
, uintptr_t *oldvalue
, uintptr_t value
)
237 return __c11_atomic_compare_exchange_weak((_Atomic(uintptr_t) *)dst
, oldvalue
, value
, __ATOMIC_RELEASE
, __ATOMIC_RELAXED
);
242 ClearExclusive(uintptr_t *dst __unused
)
249 #if !TARGET_OS_IPHONE
250 # include <CrashReporterClient.h>
252 // CrashReporterClient not yet available on iOS
254 extern const char *CRSetCrashLogMessage(const char *msg
);
255 extern const char *CRGetCrashLogMessage(void);
261 # include <algorithm>
262 # include <functional>
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
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(""); }
279 #elif TARGET_OS_WIN32
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>
296 # include <Availability.h>
300 # include <algorithm>
301 # include <functional>
303 # define __BEGIN_DECLS extern "C" {
304 # define __END_DECLS }
306 # define __BEGIN_DECLS /*empty*/
307 # define __END_DECLS /*empty*/
310 # define PRIVATE_EXTERN
311 # define __attribute__(x)
312 # define inline __inline
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 { } }
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)
329 #include <objc/objc.h>
330 #include <objc/objc-api.h>
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)));
338 #define INIT_ONCE_PTR(var, create, delete) \
341 typeof(var) v = create; \
343 if (OSAtomicCompareAndSwapPtrBarrier(0, (void*)v, (void**)&var)){ \
351 #define INIT_ONCE_32(var, create, delete) \
354 typeof(var) v = create; \
356 if (OSAtomicCompareAndSwap32Barrier(0, v, (volatile int32_t *)&var)) { \
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)
376 # define SUPPORT_DIRECT_THREAD_KEYS 0
382 // Compiler compatibility
386 #define strdup _strdup
388 #define issetugid() 0
390 #define MIN(x, y) ((x) < (y) ? (x) : (y))
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
); }
395 int asprintf(char **dstp
, const char *format
, ...);
397 typedef void * malloc_zone_t
;
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? */ }
410 static __inline BOOL
OSAtomicCompareAndSwapLong(long oldl
, long newl
, long volatile *dst
)
412 // fixme barrier is overkill
413 long original
= InterlockedCompareExchange(dst
, newl
, oldl
);
414 return (original
== oldl
);
417 static __inline BOOL
OSAtomicCompareAndSwapPtrBarrier(void *oldp
, void *newp
, void * volatile *dst
)
419 void *original
= InterlockedCompareExchangePointer(dst
, newp
, oldp
);
420 return (original
== oldp
);
423 static __inline BOOL
OSAtomicCompareAndSwap32Barrier(int32_t oldl
, int32_t newl
, int32_t volatile *dst
)
425 long original
= InterlockedCompareExchange((volatile long *)dst
, newl
, oldl
);
426 return (original
== oldl
);
429 static __inline
int32_t OSAtomicDecrement32Barrier(volatile int32_t *dst
)
431 return InterlockedDecrement((volatile long *)dst
);
434 static __inline
int32_t OSAtomicIncrement32Barrier(volatile int32_t *dst
)
436 return InterlockedIncrement((volatile long *)dst
);
440 // Internal data types
442 typedef DWORD objc_thread_t
; // thread ID
443 static __inline
int thread_equal(objc_thread_t t1
, objc_thread_t t2
) {
446 static __inline objc_thread_t
objc_thread_self(void) {
447 return GetCurrentThreadId();
452 void (*dtor
)(void *);
454 static __inline tls_key_t
tls_create(void (*dtor
)(void*)) {
455 // fixme need dtor registry for DllMain to call on thread detach
461 static __inline
void *tls_get(tls_key_t k
) {
462 return TlsGetValue(k
.key
);
464 static __inline
void tls_set(tls_key_t k
, void *value
) {
465 TlsSetValue(k
.key
, value
);
469 CRITICAL_SECTION
*lock
;
471 #define MUTEX_INITIALIZER {0};
472 extern void mutex_init(mutex_t
*m
);
473 static __inline
int _mutex_lock_nodebug(mutex_t
*m
) {
478 EnterCriticalSection(m
->lock
);
481 static __inline
bool _mutex_try_lock_nodebug(mutex_t
*m
) {
486 return TryEnterCriticalSection(m
->lock
);
488 static __inline
int _mutex_unlock_nodebug(mutex_t
*m
) {
490 LeaveCriticalSection(m
->lock
);
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
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
) {
509 return WaitForSingleObject(m
->mutex
, INFINITE
);
511 static __inline
bool _recursive_mutex_try_lock_nodebug(recursive_mutex_t
*m
) {
513 return (WAIT_OBJECT_0
== WaitForSingleObject(m
->mutex
, 0));
515 static __inline
int _recursive_mutex_unlock_nodebug(recursive_mutex_t
*m
) {
517 return ReleaseMutex(m
->mutex
) ? 0 : RECURSIVE_MUTEX_NOT_LOCKED
;
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); }
529 // based on http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
530 // Vista-only CONDITION_VARIABLE would be better
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
;
539 #define MONITOR_INITIALIZER { 0 }
540 #define MONITOR_NOT_ENTERED 1
541 extern int monitor_init(monitor_t
*c
);
543 static inline int _monitor_enter_nodebug(monitor_t
*c
) {
545 int err
= monitor_init(c
);
548 return WaitForSingleObject(c
->mutex
, INFINITE
);
550 static inline int _monitor_leave_nodebug(monitor_t
*c
) {
551 if (!ReleaseMutex(c
->mutex
)) return MONITOR_NOT_ENTERED
;
554 static inline int _monitor_wait_nodebug(monitor_t
*c
) {
556 EnterCriticalSection(&c
->waitCountLock
);
558 LeaveCriticalSection(&c
->waitCountLock
);
560 SignalObjectAndWait(c
->mutex
, c
->waiters
, INFINITE
, FALSE
);
562 EnterCriticalSection(&c
->waitCountLock
);
564 last
= c
->didBroadcast
&& c
->waitCount
== 0;
565 LeaveCriticalSection(&c
->waitCountLock
);
568 // tell broadcaster that all waiters have awoken
569 SignalObjectAndWait(c
->waitersDone
, c
->mutex
, INFINITE
, FALSE
);
571 WaitForSingleObject(c
->mutex
, INFINITE
);
574 // fixme error checking
577 static inline int monitor_notify(monitor_t
*c
) {
580 EnterCriticalSection(&c
->waitCountLock
);
581 haveWaiters
= c
->waitCount
> 0;
582 LeaveCriticalSection(&c
->waitCountLock
);
585 ReleaseSemaphore(c
->waiters
, 1, 0);
588 // fixme error checking
591 static inline int monitor_notifyAll(monitor_t
*c
) {
592 EnterCriticalSection(&c
->waitCountLock
);
593 if (c
->waitCount
== 0) {
594 LeaveCriticalSection(&c
->waitCountLock
);
598 ReleaseSemaphore(c
->waiters
, c
->waitCount
, 0);
599 LeaveCriticalSection(&c
->waitCountLock
);
601 // fairness: wait for everyone to move from waiters to mutex
602 WaitForSingleObject(c
->waitersDone
, INFINITE
);
603 // not under waitCountLock, but still under mutex
606 // fixme error checking
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)
624 #include <mach-o/loader.h>
626 # define SEGMENT_CMD LC_SEGMENT
628 # define SEGMENT_CMD LC_SEGMENT_64
631 #ifndef VM_MEMORY_OBJC_DISPATCHERS
632 # define VM_MEMORY_OBJC_DISPATCHERS 0
636 // Compiler compatibility
640 static inline uint64_t nanoseconds() {
641 return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW
);
644 // Internal data types
646 typedef pthread_t objc_thread_t
;
648 static __inline
int thread_equal(objc_thread_t t1
, objc_thread_t t2
) {
649 return pthread_equal(t1
, t2
);
652 typedef pthread_key_t tls_key_t
;
654 static inline tls_key_t
tls_create(void (*dtor
)(void*)) {
656 pthread_key_create(&k
, dtor
);
659 static inline void *tls_get(tls_key_t k
) {
660 return pthread_getspecific(k
);
662 static inline void tls_set(tls_key_t k
, void *value
) {
663 pthread_setspecific(k
, value
);
666 #if SUPPORT_DIRECT_THREAD_KEYS
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
679 static inline void *tls_get_direct(tls_key_t k
)
681 ASSERT(is_valid_direct_key(k
));
683 if (_pthread_has_direct_tsd()) {
684 return _pthread_getspecific_direct(k
);
686 return pthread_getspecific(k
);
689 static inline void tls_set_direct(tls_key_t k
, void *value
)
691 ASSERT(is_valid_direct_key(k
));
693 if (_pthread_has_direct_tsd()) {
694 _pthread_setspecific_direct(k
, value
);
696 pthread_setspecific(k
, value
);
700 __attribute__((const))
701 static inline pthread_t
objc_thread_self()
703 return (pthread_t
)tls_get_direct(_PTHREAD_TSD_SLOT_PTHREAD_SELF
);
706 __attribute__((const))
707 static inline pthread_t
objc_thread_self()
709 return pthread_self();
711 #endif // SUPPORT_DIRECT_THREAD_KEYS
714 template <bool Debug
> class mutex_tt
;
715 template <bool Debug
> class monitor_tt
;
716 template <bool Debug
> class recursive_mutex_tt
;
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
>;
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;
735 extern const fork_unsafe_lock_t fork_unsafe_lock
;
737 #include "objc-lockdebug.h"
739 template <bool Debug
>
740 class mutex_tt
: nocopy_t
{
741 os_unfair_lock mLock
;
743 constexpr mutex_tt() : mLock(OS_UNFAIR_LOCK_INIT
) {
744 lockdebug_remember_mutex(this);
747 constexpr mutex_tt(__unused
const fork_unsafe_lock_t unsafe
) : mLock(OS_UNFAIR_LOCK_INIT
) { }
750 lockdebug_mutex_lock(this);
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
);
759 lockdebug_mutex_unlock(this);
761 os_unfair_lock_unlock_inline(&mLock
);
765 lockdebug_mutex_unlock(this);
767 bzero(&mLock
, sizeof(mLock
));
768 mLock
= os_unfair_lock OS_UNFAIR_LOCK_INIT
;
771 void assertLocked() {
772 lockdebug_mutex_assert_locked(this);
775 void assertUnlocked() {
776 lockdebug_mutex_assert_unlocked(this);
780 // Address-ordered lock discipline for a pair of locks.
782 static void lockTwo(mutex_tt
*lock1
, mutex_tt
*lock2
) {
783 if ((uintptr_t)lock1
< (uintptr_t)lock2
) {
788 if (lock2
!= lock1
) lock1
->lock();
792 static void unlockTwo(mutex_tt
*lock1
, mutex_tt
*lock2
) {
794 if (lock2
!= lock1
) lock2
->unlock();
797 // Scoped lock and unlock
798 class locker
: nocopy_t
{
801 locker(mutex_tt
& newLock
)
802 : lock(newLock
) { lock
.lock(); }
803 ~locker() { lock
.unlock(); }
806 // Either scoped lock and unlock, or NOP.
807 class conditional_locker
: nocopy_t
{
811 conditional_locker(mutex_tt
& newLock
, bool shouldLock
)
812 : lock(newLock
), didLock(shouldLock
)
814 if (shouldLock
) lock
.lock();
816 ~conditional_locker() { if (didLock
) lock
.unlock(); }
820 using mutex_locker_t
= mutex_tt
<LOCKDEBUG
>::locker
;
821 using conditional_mutex_locker_t
= mutex_tt
<LOCKDEBUG
>::conditional_locker
;
824 template <bool Debug
>
825 class recursive_mutex_tt
: nocopy_t
{
826 os_unfair_recursive_lock mLock
;
829 constexpr recursive_mutex_tt() : mLock(OS_UNFAIR_RECURSIVE_LOCK_INIT
) {
830 lockdebug_remember_recursive_mutex(this);
833 constexpr recursive_mutex_tt(__unused
const fork_unsafe_lock_t unsafe
)
834 : mLock(OS_UNFAIR_RECURSIVE_LOCK_INIT
)
839 lockdebug_recursive_mutex_lock(this);
840 os_unfair_recursive_lock_lock(&mLock
);
845 lockdebug_recursive_mutex_unlock(this);
847 os_unfair_recursive_lock_unlock(&mLock
);
852 lockdebug_recursive_mutex_unlock(this);
854 bzero(&mLock
, sizeof(mLock
));
855 mLock
= os_unfair_recursive_lock OS_UNFAIR_RECURSIVE_LOCK_INIT
;
860 if (os_unfair_recursive_lock_trylock(&mLock
)) {
861 lockdebug_recursive_mutex_lock(this);
869 if (os_unfair_recursive_lock_tryunlock4objc(&mLock
)) {
870 lockdebug_recursive_mutex_unlock(this);
876 void assertLocked() {
877 lockdebug_recursive_mutex_assert_locked(this);
880 void assertUnlocked() {
881 lockdebug_recursive_mutex_assert_unlocked(this);
886 template <bool Debug
>
888 pthread_mutex_t mutex
;
892 constexpr monitor_tt()
893 : mutex(PTHREAD_MUTEX_INITIALIZER
), cond(PTHREAD_COND_INITIALIZER
)
895 lockdebug_remember_monitor(this);
898 monitor_tt(__unused
const fork_unsafe_lock_t unsafe
)
899 : mutex(PTHREAD_MUTEX_INITIALIZER
), cond(PTHREAD_COND_INITIALIZER
)
904 lockdebug_monitor_enter(this);
906 int err
= pthread_mutex_lock(&mutex
);
907 if (err
) _objc_fatal("pthread_mutex_lock failed (%d)", err
);
912 lockdebug_monitor_leave(this);
914 int err
= pthread_mutex_unlock(&mutex
);
915 if (err
) _objc_fatal("pthread_mutex_unlock failed (%d)", err
);
920 lockdebug_monitor_wait(this);
922 int err
= pthread_cond_wait(&cond
, &mutex
);
923 if (err
) _objc_fatal("pthread_cond_wait failed (%d)", err
);
928 int err
= pthread_cond_signal(&cond
);
929 if (err
) _objc_fatal("pthread_cond_signal failed (%d)", err
);
934 int err
= pthread_cond_broadcast(&cond
);
935 if (err
) _objc_fatal("pthread_cond_broadcast failed (%d)", err
);
940 lockdebug_monitor_leave(this);
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
;
950 lockdebug_monitor_assert_locked(this);
953 void assertUnlocked()
955 lockdebug_monitor_assert_unlocked(this);
960 // semaphore_create formatted for INIT_ONCE use
961 static inline semaphore_t
create_semaphore(void)
965 k
= semaphore_create(mach_task_self(), &sem
, SYNC_POLICY_FIFO
, 0);
966 if (k
) _objc_fatal("semaphore_create failed (0x%x)", k
);
972 typedef struct mach_header headerType
;
973 typedef struct segment_command segmentType
;
974 typedef struct section sectionType
;
976 typedef struct mach_header_64 headerType
;
977 typedef struct segment_command_64 segmentType
;
978 typedef struct section_64 sectionType
;
980 #define headerIsBundle(hi) (hi->mhdr()->filetype == MH_BUNDLE)
981 #define libobjc_header ((headerType *)&_mh_dylib_header)
985 /* Secure /tmp usage */
986 extern int secure_open(const char *filename
, int flags
, uid_t euid
);
999 memdup(const void *mem
, size_t len
)
1001 void *dup
= malloc(len
);
1002 memcpy(dup
, mem
, len
);
1006 // strdup that doesn't copy read-only memory
1007 static inline char *
1008 strdupIfMutable(const char *str
)
1010 size_t size
= strlen(str
) + 1;
1011 if (_dyld_is_memory_immutable(str
, size
)) {
1014 return (char *)memdup(str
, size
);
1018 // free strdupIfMutable() result
1020 freeIfMutable(char *str
)
1022 size_t size
= strlen(str
) + 1;
1023 if (_dyld_is_memory_immutable(str
, size
)) {
1030 // nil-checking unsigned strdup
1031 static inline uint8_t *
1032 ustrdupMaybeNil(const uint8_t *str
)
1034 if (!str
) return nil
;
1035 return (uint8_t *)strdupIfMutable((char *)str
);
1038 // OS version checking:
1040 // sdkIsAtLeast(mac, ios, tv, watch, bridge)
1042 // This version order matches OBJC_AVAILABLE.
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))
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
;