objc-os.h 29 KB

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