]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-private.h
fbeaeb5ae67a055fcf8e07dc3a3d8fdee8063197
[apple/objc4.git] / runtime / objc-private.h
1 /*
2 * Copyright (c) 1999-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-private.h
25 * Copyright 1988-1996, NeXT Software, Inc.
26 */
27
28 #ifndef _OBJC_PRIVATE_H_
29 #define _OBJC_PRIVATE_H_
30
31 #include "objc-config.h"
32
33 /* Isolate ourselves from the definitions of id and Class in the compiler
34 * and public headers.
35 */
36
37 #ifdef _OBJC_OBJC_H_
38 #error include objc-private.h before other headers
39 #endif
40
41 #define OBJC_TYPES_DEFINED 1
42 #undef OBJC_OLD_DISPATCH_PROTOTYPES
43 #define OBJC_OLD_DISPATCH_PROTOTYPES 0
44
45 #include <cstddef> // for nullptr_t
46 #include <stdint.h>
47 #include <assert.h>
48
49 // An assert that's disabled for release builds but still ensures the expression compiles.
50 #ifdef NDEBUG
51 #define ASSERT(x) (void)sizeof(!(x))
52 #else
53 #define ASSERT(x) assert(x)
54 #endif
55
56 struct objc_class;
57 struct objc_object;
58
59 typedef struct objc_class *Class;
60 typedef struct objc_object *id;
61
62 namespace {
63 struct SideTable;
64 };
65
66 #include "isa.h"
67
68 union isa_t {
69 isa_t() { }
70 isa_t(uintptr_t value) : bits(value) { }
71
72 Class cls;
73 uintptr_t bits;
74 #if defined(ISA_BITFIELD)
75 struct {
76 ISA_BITFIELD; // defined in isa.h
77 };
78 #endif
79 };
80
81
82 struct objc_object {
83 private:
84 isa_t isa;
85
86 public:
87
88 // ISA() assumes this is NOT a tagged pointer object
89 Class ISA();
90
91 // rawISA() assumes this is NOT a tagged pointer object or a non pointer ISA
92 Class rawISA();
93
94 // getIsa() allows this to be a tagged pointer object
95 Class getIsa();
96
97 uintptr_t isaBits() const;
98
99 // initIsa() should be used to init the isa of new objects only.
100 // If this object already has an isa, use changeIsa() for correctness.
101 // initInstanceIsa(): objects with no custom RR/AWZ
102 // initClassIsa(): class objects
103 // initProtocolIsa(): protocol objects
104 // initIsa(): other objects
105 void initIsa(Class cls /*nonpointer=false*/);
106 void initClassIsa(Class cls /*nonpointer=maybe*/);
107 void initProtocolIsa(Class cls /*nonpointer=maybe*/);
108 void initInstanceIsa(Class cls, bool hasCxxDtor);
109
110 // changeIsa() should be used to change the isa of existing objects.
111 // If this is a new object, use initIsa() for performance.
112 Class changeIsa(Class newCls);
113
114 bool hasNonpointerIsa();
115 bool isTaggedPointer();
116 bool isBasicTaggedPointer();
117 bool isExtTaggedPointer();
118 bool isClass();
119
120 // object may have associated objects?
121 bool hasAssociatedObjects();
122 void setHasAssociatedObjects();
123
124 // object may be weakly referenced?
125 bool isWeaklyReferenced();
126 void setWeaklyReferenced_nolock();
127
128 // object may have -.cxx_destruct implementation?
129 bool hasCxxDtor();
130
131 // Optimized calls to retain/release methods
132 id retain();
133 void release();
134 id autorelease();
135
136 // Implementations of retain/release methods
137 id rootRetain();
138 bool rootRelease();
139 id rootAutorelease();
140 bool rootTryRetain();
141 bool rootReleaseShouldDealloc();
142 uintptr_t rootRetainCount();
143
144 // Implementation of dealloc methods
145 bool rootIsDeallocating();
146 void clearDeallocating();
147 void rootDealloc();
148
149 private:
150 void initIsa(Class newCls, bool nonpointer, bool hasCxxDtor);
151
152 // Slow paths for inline control
153 id rootAutorelease2();
154 uintptr_t overrelease_error();
155
156 #if SUPPORT_NONPOINTER_ISA
157 // Unified retain count manipulation for nonpointer isa
158 id rootRetain(bool tryRetain, bool handleOverflow);
159 bool rootRelease(bool performDealloc, bool handleUnderflow);
160 id rootRetain_overflow(bool tryRetain);
161 uintptr_t rootRelease_underflow(bool performDealloc);
162
163 void clearDeallocating_slow();
164
165 // Side table retain count overflow for nonpointer isa
166 void sidetable_lock();
167 void sidetable_unlock();
168
169 void sidetable_moveExtraRC_nolock(size_t extra_rc, bool isDeallocating, bool weaklyReferenced);
170 bool sidetable_addExtraRC_nolock(size_t delta_rc);
171 size_t sidetable_subExtraRC_nolock(size_t delta_rc);
172 size_t sidetable_getExtraRC_nolock();
173 #endif
174
175 // Side-table-only retain count
176 bool sidetable_isDeallocating();
177 void sidetable_clearDeallocating();
178
179 bool sidetable_isWeaklyReferenced();
180 void sidetable_setWeaklyReferenced_nolock();
181
182 id sidetable_retain();
183 id sidetable_retain_slow(SideTable& table);
184
185 uintptr_t sidetable_release(bool performDealloc = true);
186 uintptr_t sidetable_release_slow(SideTable& table, bool performDealloc = true);
187
188 bool sidetable_tryRetain();
189
190 uintptr_t sidetable_retainCount();
191 #if DEBUG
192 bool sidetable_present();
193 #endif
194 };
195
196
197 #if __OBJC2__
198 typedef struct method_t *Method;
199 typedef struct ivar_t *Ivar;
200 typedef struct category_t *Category;
201 typedef struct property_t *objc_property_t;
202 #else
203 typedef struct old_method *Method;
204 typedef struct old_ivar *Ivar;
205 typedef struct old_category *Category;
206 typedef struct old_property *objc_property_t;
207 #endif
208
209 // Public headers
210
211 #include "objc.h"
212 #include "runtime.h"
213 #include "objc-os.h"
214 #include "objc-abi.h"
215 #include "objc-api.h"
216 #include "objc-config.h"
217 #include "objc-internal.h"
218 #include "maptable.h"
219 #include "hashtable2.h"
220
221 /* Do not include message.h here. */
222 /* #include "message.h" */
223
224 #define __APPLE_API_PRIVATE
225 #include "objc-gdb.h"
226 #undef __APPLE_API_PRIVATE
227
228
229 // Private headers
230
231 #include "objc-ptrauth.h"
232
233 #if __OBJC2__
234 #include "objc-runtime-new.h"
235 #else
236 #include "objc-runtime-old.h"
237 #endif
238
239 #include "objc-references.h"
240 #include "objc-initialize.h"
241 #include "objc-loadmethod.h"
242
243
244 #if SUPPORT_PREOPT && __cplusplus
245 #include <objc-shared-cache.h>
246 using objc_selopt_t = const objc_opt::objc_selopt_t;
247 #else
248 struct objc_selopt_t;
249 #endif
250
251
252 #define STRINGIFY(x) #x
253 #define STRINGIFY2(x) STRINGIFY(x)
254
255 __BEGIN_DECLS
256
257 namespace objc {
258
259 struct SafeRanges {
260 private:
261 struct Range {
262 uintptr_t start;
263 uintptr_t end;
264
265 inline bool contains(uintptr_t ptr) const {
266 uintptr_t m_start, m_end;
267 #if __arm64__
268 // <rdar://problem/48304934> Force the compiler to use ldp
269 // we really don't want 2 loads and 2 jumps.
270 __asm__(
271 # if __LP64__
272 "ldp %x[one], %x[two], [%x[src]]"
273 # else
274 "ldp %w[one], %w[two], [%x[src]]"
275 # endif
276 : [one] "=r" (m_start), [two] "=r" (m_end)
277 : [src] "r" (this)
278 );
279 #else
280 m_start = start;
281 m_end = end;
282 #endif
283 return m_start <= ptr && ptr < m_end;
284 }
285 };
286
287 struct Range *ranges;
288 uint32_t count;
289 uint32_t size : 31;
290 uint32_t sorted : 1;
291
292 public:
293 inline bool contains(uint16_t witness, uintptr_t ptr) const {
294 return witness < count && ranges[witness].contains(ptr);
295 }
296
297 bool find(uintptr_t ptr, uint32_t &pos);
298 void add(uintptr_t start, uintptr_t end);
299 void remove(uintptr_t start, uintptr_t end);
300 };
301
302 extern struct SafeRanges dataSegmentsRanges;
303
304 } // objc
305
306 struct header_info;
307
308 // Split out the rw data from header info. For now put it in a huge array
309 // that more than exceeds the space needed. In future we'll just allocate
310 // this in the shared cache builder.
311 typedef struct header_info_rw {
312
313 bool getLoaded() const {
314 return isLoaded;
315 }
316
317 void setLoaded(bool v) {
318 isLoaded = v ? 1: 0;
319 }
320
321 bool getAllClassesRealized() const {
322 return allClassesRealized;
323 }
324
325 void setAllClassesRealized(bool v) {
326 allClassesRealized = v ? 1: 0;
327 }
328
329 header_info *getNext() const {
330 return (header_info *)(next << 2);
331 }
332
333 void setNext(header_info *v) {
334 next = ((uintptr_t)v) >> 2;
335 }
336
337 private:
338 #ifdef __LP64__
339 uintptr_t isLoaded : 1;
340 uintptr_t allClassesRealized : 1;
341 uintptr_t next : 62;
342 #else
343 uintptr_t isLoaded : 1;
344 uintptr_t allClassesRealized : 1;
345 uintptr_t next : 30;
346 #endif
347 } header_info_rw;
348
349 struct header_info_rw* getPreoptimizedHeaderRW(const struct header_info *const hdr);
350
351 typedef struct header_info {
352 private:
353 // Note, this is no longer a pointer, but instead an offset to a pointer
354 // from this location.
355 intptr_t mhdr_offset;
356
357 // Note, this is no longer a pointer, but instead an offset to a pointer
358 // from this location.
359 intptr_t info_offset;
360
361 // Do not add fields without editing ObjCModernAbstraction.hpp
362 public:
363
364 header_info_rw *getHeaderInfoRW() {
365 header_info_rw *preopt =
366 isPreoptimized() ? getPreoptimizedHeaderRW(this) : nil;
367 if (preopt) return preopt;
368 else return &rw_data[0];
369 }
370
371 const headerType *mhdr() const {
372 return (const headerType *)(((intptr_t)&mhdr_offset) + mhdr_offset);
373 }
374
375 void setmhdr(const headerType *mhdr) {
376 mhdr_offset = (intptr_t)mhdr - (intptr_t)&mhdr_offset;
377 }
378
379 const objc_image_info *info() const {
380 return (const objc_image_info *)(((intptr_t)&info_offset) + info_offset);
381 }
382
383 void setinfo(const objc_image_info *info) {
384 info_offset = (intptr_t)info - (intptr_t)&info_offset;
385 }
386
387 bool isLoaded() {
388 return getHeaderInfoRW()->getLoaded();
389 }
390
391 void setLoaded(bool v) {
392 getHeaderInfoRW()->setLoaded(v);
393 }
394
395 bool areAllClassesRealized() {
396 return getHeaderInfoRW()->getAllClassesRealized();
397 }
398
399 void setAllClassesRealized(bool v) {
400 getHeaderInfoRW()->setAllClassesRealized(v);
401 }
402
403 header_info *getNext() {
404 return getHeaderInfoRW()->getNext();
405 }
406
407 void setNext(header_info *v) {
408 getHeaderInfoRW()->setNext(v);
409 }
410
411 bool isBundle() {
412 return mhdr()->filetype == MH_BUNDLE;
413 }
414
415 const char *fname() const {
416 return dyld_image_path_containing_address(mhdr());
417 }
418
419 bool isPreoptimized() const;
420
421 bool hasPreoptimizedSelectors() const;
422
423 bool hasPreoptimizedClasses() const;
424
425 bool hasPreoptimizedProtocols() const;
426
427 #if !__OBJC2__
428 struct old_protocol **proto_refs;
429 struct objc_module *mod_ptr;
430 size_t mod_count;
431 # if TARGET_OS_WIN32
432 struct objc_module **modules;
433 size_t moduleCount;
434 struct old_protocol **protocols;
435 size_t protocolCount;
436 void *imageinfo;
437 size_t imageinfoBytes;
438 SEL *selrefs;
439 size_t selrefCount;
440 struct objc_class **clsrefs;
441 size_t clsrefCount;
442 TCHAR *moduleName;
443 # endif
444 #endif
445
446 private:
447 // Images in the shared cache will have an empty array here while those
448 // allocated at run time will allocate a single entry.
449 header_info_rw rw_data[];
450 } header_info;
451
452 extern header_info *FirstHeader;
453 extern header_info *LastHeader;
454
455 extern void appendHeader(header_info *hi);
456 extern void removeHeader(header_info *hi);
457
458 extern objc_image_info *_getObjcImageInfo(const headerType *head, size_t *size);
459 extern bool _hasObjcContents(const header_info *hi);
460
461
462 // Mach-O segment and section names are 16 bytes and may be un-terminated.
463
464 static inline bool segnameEquals(const char *lhs, const char *rhs) {
465 return 0 == strncmp(lhs, rhs, 16);
466 }
467
468 static inline bool segnameStartsWith(const char *segname, const char *prefix) {
469 return 0 == strncmp(segname, prefix, strlen(prefix));
470 }
471
472 static inline bool sectnameEquals(const char *lhs, const char *rhs) {
473 return segnameEquals(lhs, rhs);
474 }
475
476 static inline bool sectnameStartsWith(const char *sectname, const char *prefix){
477 return segnameStartsWith(sectname, prefix);
478 }
479
480
481 /* selectors */
482 extern void sel_init(size_t selrefCount);
483 extern SEL sel_registerNameNoLock(const char *str, bool copy);
484
485 extern SEL SEL_cxx_construct;
486 extern SEL SEL_cxx_destruct;
487
488 /* preoptimization */
489 extern void preopt_init(void);
490 extern void disableSharedCacheOptimizations(void);
491 extern bool isPreoptimized(void);
492 extern bool noMissingWeakSuperclasses(void);
493 extern header_info *preoptimizedHinfoForHeader(const headerType *mhdr);
494
495 extern objc_selopt_t *preoptimizedSelectors(void);
496
497 extern bool sharedCacheSupportsProtocolRoots(void);
498 extern Protocol *getPreoptimizedProtocol(const char *name);
499 extern Protocol *getSharedCachePreoptimizedProtocol(const char *name);
500
501 extern unsigned getPreoptimizedClassUnreasonableCount();
502 extern Class getPreoptimizedClass(const char *name);
503 extern Class* copyPreoptimizedClasses(const char *name, int *outCount);
504
505 extern Class _calloc_class(size_t size);
506
507 /* method lookup */
508 enum {
509 LOOKUP_INITIALIZE = 1,
510 LOOKUP_RESOLVER = 2,
511 LOOKUP_CACHE = 4,
512 LOOKUP_NIL = 8,
513 };
514 extern IMP lookUpImpOrForward(id obj, SEL, Class cls, int behavior);
515
516 static inline IMP
517 lookUpImpOrNil(id obj, SEL sel, Class cls, int behavior = 0)
518 {
519 return lookUpImpOrForward(obj, sel, cls, behavior | LOOKUP_CACHE | LOOKUP_NIL);
520 }
521
522 extern IMP lookupMethodInClassAndLoadCache(Class cls, SEL sel);
523 extern BOOL class_respondsToSelector_inst(id inst, SEL sel, Class cls);
524 extern Class class_initialize(Class cls, id inst);
525
526 extern bool objcMsgLogEnabled;
527 extern bool logMessageSend(bool isClassMethod,
528 const char *objectsClass,
529 const char *implementingClass,
530 SEL selector);
531
532 /* message dispatcher */
533
534 #if !OBJC_OLD_DISPATCH_PROTOTYPES
535 extern void _objc_msgForward_impcache(void);
536 #else
537 extern id _objc_msgForward_impcache(id, SEL, ...);
538 #endif
539
540 /* errors */
541 extern id(*badAllocHandler)(Class);
542 extern id _objc_callBadAllocHandler(Class cls) __attribute__((cold, noinline));
543 extern void __objc_error(id, const char *, ...) __attribute__((cold, format (printf, 2, 3), noreturn));
544 extern void _objc_inform(const char *fmt, ...) __attribute__((cold, format(printf, 1, 2)));
545 extern void _objc_inform_on_crash(const char *fmt, ...) __attribute__((cold, format (printf, 1, 2)));
546 extern void _objc_inform_now_and_on_crash(const char *fmt, ...) __attribute__((cold, format (printf, 1, 2)));
547 extern void _objc_inform_deprecated(const char *oldname, const char *newname) __attribute__((cold, noinline));
548 extern void inform_duplicate(const char *name, Class oldCls, Class cls);
549
550 /* magic */
551 extern Class _objc_getFreedObjectClass (void);
552
553 /* map table additions */
554 extern void *NXMapKeyCopyingInsert(NXMapTable *table, const void *key, const void *value);
555 extern void *NXMapKeyFreeingRemove(NXMapTable *table, const void *key);
556
557 /* hash table additions */
558 extern unsigned _NXHashCapacity(NXHashTable *table);
559 extern void _NXHashRehashToCapacity(NXHashTable *table, unsigned newCapacity);
560
561 /* property attribute parsing */
562 extern const char *copyPropertyAttributeString(const objc_property_attribute_t *attrs, unsigned int count);
563 extern objc_property_attribute_t *copyPropertyAttributeList(const char *attrs, unsigned int *outCount);
564 extern char *copyPropertyAttributeValue(const char *attrs, const char *name);
565
566 /* locking */
567
568 class monitor_locker_t : nocopy_t {
569 monitor_t& lock;
570 public:
571 monitor_locker_t(monitor_t& newLock) : lock(newLock) { lock.enter(); }
572 ~monitor_locker_t() { lock.leave(); }
573 };
574
575 class recursive_mutex_locker_t : nocopy_t {
576 recursive_mutex_t& lock;
577 public:
578 recursive_mutex_locker_t(recursive_mutex_t& newLock)
579 : lock(newLock) { lock.lock(); }
580 ~recursive_mutex_locker_t() { lock.unlock(); }
581 };
582
583
584 /* Exceptions */
585 struct alt_handler_list;
586 extern void exception_init(void);
587 extern void _destroyAltHandlerList(struct alt_handler_list *list);
588
589 /* Class change notifications (gdb only for now) */
590 #define OBJC_CLASS_ADDED (1<<0)
591 #define OBJC_CLASS_REMOVED (1<<1)
592 #define OBJC_CLASS_IVARS_CHANGED (1<<2)
593 #define OBJC_CLASS_METHODS_CHANGED (1<<3)
594 extern void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
595 __attribute__((noinline));
596
597
598 // Settings from environment variables
599 #define OPTION(var, env, help) extern bool var;
600 #include "objc-env.h"
601 #undef OPTION
602
603 extern void environ_init(void);
604 extern void runtime_init(void);
605
606 extern void logReplacedMethod(const char *className, SEL s, bool isMeta, const char *catName, IMP oldImp, IMP newImp);
607
608
609 // objc per-thread storage
610 typedef struct {
611 struct _objc_initializing_classes *initializingClasses; // for +initialize
612 struct SyncCache *syncCache; // for @synchronize
613 struct alt_handler_list *handlerList; // for exception alt handlers
614 char *printableNames[4]; // temporary demangled names for logging
615 const char **classNameLookups; // for objc_getClass() hooks
616 unsigned classNameLookupsAllocated;
617 unsigned classNameLookupsUsed;
618
619 // If you add new fields here, don't forget to update
620 // _objc_pthread_destroyspecific()
621
622 } _objc_pthread_data;
623
624 extern _objc_pthread_data *_objc_fetch_pthread_data(bool create);
625 extern void tls_init(void);
626
627 // encoding.h
628 extern unsigned int encoding_getNumberOfArguments(const char *typedesc);
629 extern unsigned int encoding_getSizeOfArguments(const char *typedesc);
630 extern unsigned int encoding_getArgumentInfo(const char *typedesc, unsigned int arg, const char **type, int *offset);
631 extern void encoding_getReturnType(const char *t, char *dst, size_t dst_len);
632 extern char * encoding_copyReturnType(const char *t);
633 extern void encoding_getArgumentType(const char *t, unsigned int index, char *dst, size_t dst_len);
634 extern char *encoding_copyArgumentType(const char *t, unsigned int index);
635
636 // sync.h
637 extern void _destroySyncCache(struct SyncCache *cache);
638
639 // arr
640 extern void arr_init(void);
641 extern id objc_autoreleaseReturnValue(id obj);
642
643 // block trampolines
644 extern void _imp_implementationWithBlock_init(void);
645 extern IMP _imp_implementationWithBlockNoCopy(id block);
646
647 // layout.h
648 typedef struct {
649 uint8_t *bits;
650 size_t bitCount;
651 size_t bitsAllocated;
652 bool weak;
653 } layout_bitmap;
654 extern layout_bitmap layout_bitmap_create(const unsigned char *layout_string, size_t layoutStringInstanceSize, size_t instanceSize, bool weak);
655 extern layout_bitmap layout_bitmap_create_empty(size_t instanceSize, bool weak);
656 extern void layout_bitmap_free(layout_bitmap bits);
657 extern const unsigned char *layout_string_create(layout_bitmap bits);
658 extern void layout_bitmap_set_ivar(layout_bitmap bits, const char *type, size_t offset);
659 extern void layout_bitmap_grow(layout_bitmap *bits, size_t newCount);
660 extern void layout_bitmap_slide(layout_bitmap *bits, size_t oldPos, size_t newPos);
661 extern void layout_bitmap_slide_anywhere(layout_bitmap *bits, size_t oldPos, size_t newPos);
662 extern bool layout_bitmap_splat(layout_bitmap dst, layout_bitmap src,
663 size_t oldSrcInstanceSize);
664 extern bool layout_bitmap_or(layout_bitmap dst, layout_bitmap src, const char *msg);
665 extern bool layout_bitmap_clear(layout_bitmap dst, layout_bitmap src, const char *msg);
666 extern void layout_bitmap_print(layout_bitmap bits);
667
668
669 // fixme runtime
670 extern bool MultithreadedForkChild;
671 extern id objc_noop_imp(id self, SEL _cmd);
672 extern Class look_up_class(const char *aClassName, bool includeUnconnected, bool includeClassHandler);
673 extern "C" void map_images(unsigned count, const char * const paths[],
674 const struct mach_header * const mhdrs[]);
675 extern void map_images_nolock(unsigned count, const char * const paths[],
676 const struct mach_header * const mhdrs[]);
677 extern void load_images(const char *path, const struct mach_header *mh);
678 extern void unmap_image(const char *path, const struct mach_header *mh);
679 extern void unmap_image_nolock(const struct mach_header *mh);
680 extern void _read_images(header_info **hList, uint32_t hCount, int totalClasses, int unoptimizedTotalClass);
681 extern void _unload_image(header_info *hi);
682
683 extern const header_info *_headerForClass(Class cls);
684
685 extern Class _class_remap(Class cls);
686 extern Ivar _class_getVariable(Class cls, const char *name);
687
688 extern unsigned _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone, id *results, unsigned num_requested);
689
690 extern const char *_category_getName(Category cat);
691 extern const char *_category_getClassName(Category cat);
692 extern Class _category_getClass(Category cat);
693 extern IMP _category_getLoadMethod(Category cat);
694
695 enum {
696 OBJECT_CONSTRUCT_NONE = 0,
697 OBJECT_CONSTRUCT_FREE_ONFAILURE = 1,
698 OBJECT_CONSTRUCT_CALL_BADALLOC = 2,
699 };
700 extern id object_cxxConstructFromClass(id obj, Class cls, int flags);
701 extern void object_cxxDestruct(id obj);
702
703 extern void fixupCopiedIvars(id newObject, id oldObject);
704 extern Class _class_getClassForIvar(Class cls, Ivar ivar);
705
706
707 #define OBJC_WARN_DEPRECATED \
708 do { \
709 static int warned = 0; \
710 if (!warned) { \
711 warned = 1; \
712 _objc_inform_deprecated(__FUNCTION__, NULL); \
713 } \
714 } while (0) \
715
716 __END_DECLS
717
718
719 #ifndef STATIC_ASSERT
720 # define STATIC_ASSERT(x) _STATIC_ASSERT2(x, __LINE__)
721 # define _STATIC_ASSERT2(x, line) _STATIC_ASSERT3(x, line)
722 # define _STATIC_ASSERT3(x, line) \
723 typedef struct { \
724 int _static_assert[(x) ? 0 : -1]; \
725 } _static_assert_ ## line __attribute__((unavailable))
726 #endif
727
728 #define countof(arr) (sizeof(arr) / sizeof((arr)[0]))
729
730
731 static __inline uint32_t _objc_strhash(const char *s) {
732 uint32_t hash = 0;
733 for (;;) {
734 int a = *s++;
735 if (0 == a) break;
736 hash += (hash << 8) + a;
737 }
738 return hash;
739 }
740
741 #if __cplusplus
742
743 template <typename T>
744 static inline T log2u(T x) {
745 return (x<2) ? 0 : log2u(x>>1)+1;
746 }
747
748 template <typename T>
749 static inline T exp2u(T x) {
750 return (1 << x);
751 }
752
753 template <typename T>
754 static T exp2m1u(T x) {
755 return (1 << x) - 1;
756 }
757
758 #endif
759
760 // Misalignment-safe integer types
761 __attribute__((aligned(1))) typedef uintptr_t unaligned_uintptr_t;
762 __attribute__((aligned(1))) typedef intptr_t unaligned_intptr_t;
763 __attribute__((aligned(1))) typedef uint64_t unaligned_uint64_t;
764 __attribute__((aligned(1))) typedef int64_t unaligned_int64_t;
765 __attribute__((aligned(1))) typedef uint32_t unaligned_uint32_t;
766 __attribute__((aligned(1))) typedef int32_t unaligned_int32_t;
767 __attribute__((aligned(1))) typedef uint16_t unaligned_uint16_t;
768 __attribute__((aligned(1))) typedef int16_t unaligned_int16_t;
769
770
771 // Global operator new and delete. We must not use any app overrides.
772 // This ALSO REQUIRES each of these be in libobjc's unexported symbol list.
773 #if __cplusplus
774 #pragma clang diagnostic push
775 #pragma clang diagnostic ignored "-Winline-new-delete"
776 #include <new>
777 inline void* operator new(std::size_t size) throw (std::bad_alloc) { return malloc(size); }
778 inline void* operator new[](std::size_t size) throw (std::bad_alloc) { return malloc(size); }
779 inline void* operator new(std::size_t size, const std::nothrow_t&) throw() { return malloc(size); }
780 inline void* operator new[](std::size_t size, const std::nothrow_t&) throw() { return malloc(size); }
781 inline void operator delete(void* p) throw() { free(p); }
782 inline void operator delete[](void* p) throw() { free(p); }
783 inline void operator delete(void* p, const std::nothrow_t&) throw() { free(p); }
784 inline void operator delete[](void* p, const std::nothrow_t&) throw() { free(p); }
785 #pragma clang diagnostic pop
786 #endif
787
788
789 class TimeLogger {
790 uint64_t mStart;
791 bool mRecord;
792 public:
793 TimeLogger(bool record = true)
794 : mStart(nanoseconds())
795 , mRecord(record)
796 { }
797
798 void log(const char *msg) {
799 if (mRecord) {
800 uint64_t end = nanoseconds();
801 _objc_inform("%.2f ms: %s", (end - mStart) / 1000000.0, msg);
802 mStart = nanoseconds();
803 }
804 }
805 };
806
807 enum { CacheLineSize = 64 };
808
809 // StripedMap<T> is a map of void* -> T, sized appropriately
810 // for cache-friendly lock striping.
811 // For example, this may be used as StripedMap<spinlock_t>
812 // or as StripedMap<SomeStruct> where SomeStruct stores a spin lock.
813 template<typename T>
814 class StripedMap {
815 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
816 enum { StripeCount = 8 };
817 #else
818 enum { StripeCount = 64 };
819 #endif
820
821 struct PaddedT {
822 T value alignas(CacheLineSize);
823 };
824
825 PaddedT array[StripeCount];
826
827 static unsigned int indexForPointer(const void *p) {
828 uintptr_t addr = reinterpret_cast<uintptr_t>(p);
829 return ((addr >> 4) ^ (addr >> 9)) % StripeCount;
830 }
831
832 public:
833 T& operator[] (const void *p) {
834 return array[indexForPointer(p)].value;
835 }
836 const T& operator[] (const void *p) const {
837 return const_cast<StripedMap<T>>(this)[p];
838 }
839
840 // Shortcuts for StripedMaps of locks.
841 void lockAll() {
842 for (unsigned int i = 0; i < StripeCount; i++) {
843 array[i].value.lock();
844 }
845 }
846
847 void unlockAll() {
848 for (unsigned int i = 0; i < StripeCount; i++) {
849 array[i].value.unlock();
850 }
851 }
852
853 void forceResetAll() {
854 for (unsigned int i = 0; i < StripeCount; i++) {
855 array[i].value.forceReset();
856 }
857 }
858
859 void defineLockOrder() {
860 for (unsigned int i = 1; i < StripeCount; i++) {
861 lockdebug_lock_precedes_lock(&array[i-1].value, &array[i].value);
862 }
863 }
864
865 void precedeLock(const void *newlock) {
866 // assumes defineLockOrder is also called
867 lockdebug_lock_precedes_lock(&array[StripeCount-1].value, newlock);
868 }
869
870 void succeedLock(const void *oldlock) {
871 // assumes defineLockOrder is also called
872 lockdebug_lock_precedes_lock(oldlock, &array[0].value);
873 }
874
875 const void *getLock(int i) {
876 if (i < StripeCount) return &array[i].value;
877 else return nil;
878 }
879
880 #if DEBUG
881 StripedMap() {
882 // Verify alignment expectations.
883 uintptr_t base = (uintptr_t)&array[0].value;
884 uintptr_t delta = (uintptr_t)&array[1].value - base;
885 ASSERT(delta % CacheLineSize == 0);
886 ASSERT(base % CacheLineSize == 0);
887 }
888 #else
889 constexpr StripedMap() {}
890 #endif
891 };
892
893
894 // DisguisedPtr<T> acts like pointer type T*, except the
895 // stored value is disguised to hide it from tools like `leaks`.
896 // nil is disguised as itself so zero-filled memory works as expected,
897 // which means 0x80..00 is also disguised as itself but we don't care.
898 // Note that weak_entry_t knows about this encoding.
899 template <typename T>
900 class DisguisedPtr {
901 uintptr_t value;
902
903 static uintptr_t disguise(T* ptr) {
904 return -(uintptr_t)ptr;
905 }
906
907 static T* undisguise(uintptr_t val) {
908 return (T*)-val;
909 }
910
911 public:
912 DisguisedPtr() { }
913 DisguisedPtr(T* ptr)
914 : value(disguise(ptr)) { }
915 DisguisedPtr(const DisguisedPtr<T>& ptr)
916 : value(ptr.value) { }
917
918 DisguisedPtr<T>& operator = (T* rhs) {
919 value = disguise(rhs);
920 return *this;
921 }
922 DisguisedPtr<T>& operator = (const DisguisedPtr<T>& rhs) {
923 value = rhs.value;
924 return *this;
925 }
926
927 operator T* () const {
928 return undisguise(value);
929 }
930 T* operator -> () const {
931 return undisguise(value);
932 }
933 T& operator * () const {
934 return *undisguise(value);
935 }
936 T& operator [] (size_t i) const {
937 return undisguise(value)[i];
938 }
939
940 // pointer arithmetic operators omitted
941 // because we don't currently use them anywhere
942 };
943
944 // fixme type id is weird and not identical to objc_object*
945 static inline bool operator == (DisguisedPtr<objc_object> lhs, id rhs) {
946 return lhs == (objc_object *)rhs;
947 }
948 static inline bool operator != (DisguisedPtr<objc_object> lhs, id rhs) {
949 return lhs != (objc_object *)rhs;
950 }
951
952
953 // Storage for a thread-safe chained hook function.
954 // get() returns the value for calling.
955 // set() installs a new function and returns the old one for chaining.
956 // More precisely, set() writes the old value to a variable supplied by
957 // the caller. get() and set() use appropriate barriers so that the
958 // old value is safely written to the variable before the new value is
959 // called to use it.
960 //
961 // T1: store to old variable; store-release to hook variable
962 // T2: load-acquire from hook variable; call it; called hook loads old variable
963
964 template <typename Fn>
965 class ChainedHookFunction {
966 std::atomic<Fn> hook{nil};
967
968 public:
969 ChainedHookFunction(Fn f) : hook{f} { };
970
971 Fn get() {
972 return hook.load(std::memory_order_acquire);
973 }
974
975 void set(Fn newValue, Fn *oldVariable)
976 {
977 Fn oldValue = hook.load(std::memory_order_relaxed);
978 do {
979 *oldVariable = oldValue;
980 } while (!hook.compare_exchange_weak(oldValue, newValue,
981 std::memory_order_release,
982 std::memory_order_relaxed));
983 }
984 };
985
986
987 // A small vector for use as a global variable. Only supports appending and
988 // iteration. Stores a single element inline, and multiple elements in a heap
989 // allocation. There is no attempt to amortize reallocation cost; this is
990 // intended to be used in situation where zero or one element is common, two
991 // might happen, and three or more is very rare.
992 //
993 // This does not clean up its allocation, and thus cannot be used as a local
994 // variable or member of something with limited lifetime.
995
996 template <typename T, unsigned InlineCount>
997 class GlobalSmallVector {
998 static_assert(std::is_pod<T>::value, "SmallVector requires POD types");
999
1000 protected:
1001 unsigned count{0};
1002 union {
1003 T inlineElements[InlineCount];
1004 T *elements;
1005 };
1006
1007 public:
1008 void append(const T &val) {
1009 if (count < InlineCount) {
1010 // We have space. Store the new value inline.
1011 inlineElements[count] = val;
1012 } else if (count == InlineCount) {
1013 // Inline storage is full. Switch to a heap allocation.
1014 T *newElements = (T *)malloc((count + 1) * sizeof(T));
1015 memcpy(newElements, inlineElements, count * sizeof(T));
1016 newElements[count] = val;
1017 elements = newElements;
1018 } else {
1019 // Resize the heap allocation and append.
1020 elements = (T *)realloc(elements, (count + 1) * sizeof(T));
1021 elements[count] = val;
1022 }
1023 count++;
1024 }
1025
1026 const T *begin() const {
1027 return count <= InlineCount ? inlineElements : elements;
1028 }
1029
1030 const T *end() const {
1031 return begin() + count;
1032 }
1033 };
1034
1035 // A small vector that cleans up its internal memory allocation when destroyed.
1036 template <typename T, unsigned InlineCount>
1037 class SmallVector: public GlobalSmallVector<T, InlineCount> {
1038 public:
1039 ~SmallVector() {
1040 if (this->count > InlineCount)
1041 free(this->elements);
1042 }
1043
1044 template <unsigned OtherCount>
1045 void initFrom(const GlobalSmallVector<T, OtherCount> &other) {
1046 ASSERT(this->count == 0);
1047 this->count = (unsigned)(other.end() - other.begin());
1048 if (this->count > InlineCount) {
1049 this->elements = (T *)memdup(other.begin(), this->count * sizeof(T));
1050 } else {
1051 memcpy(this->inlineElements, other.begin(), this->count * sizeof(T));
1052 }
1053 }
1054 };
1055
1056 // Pointer hash function.
1057 // This is not a terrific hash, but it is fast
1058 // and not outrageously flawed for our purposes.
1059
1060 // Based on principles from http://locklessinc.com/articles/fast_hash/
1061 // and evaluation ideas from http://floodyberry.com/noncryptohashzoo/
1062 #if __LP64__
1063 static inline uint32_t ptr_hash(uint64_t key)
1064 {
1065 key ^= key >> 4;
1066 key *= 0x8a970be7488fda55;
1067 key ^= __builtin_bswap64(key);
1068 return (uint32_t)key;
1069 }
1070 #else
1071 static inline uint32_t ptr_hash(uint32_t key)
1072 {
1073 key ^= key >> 4;
1074 key *= 0x5052acdb;
1075 key ^= __builtin_bswap32(key);
1076 return key;
1077 }
1078 #endif
1079
1080 /*
1081 Higher-quality hash function. This is measurably slower in some workloads.
1082 #if __LP64__
1083 uint32_t ptr_hash(uint64_t key)
1084 {
1085 key -= __builtin_bswap64(key);
1086 key *= 0x8a970be7488fda55;
1087 key ^= __builtin_bswap64(key);
1088 key *= 0x8a970be7488fda55;
1089 key ^= __builtin_bswap64(key);
1090 return (uint32_t)key;
1091 }
1092 #else
1093 static uint32_t ptr_hash(uint32_t key)
1094 {
1095 key -= __builtin_bswap32(key);
1096 key *= 0x5052acdb;
1097 key ^= __builtin_bswap32(key);
1098 key *= 0x5052acdb;
1099 key ^= __builtin_bswap32(key);
1100 return key;
1101 }
1102 #endif
1103 */
1104
1105
1106
1107 // Lock declarations
1108 #include "objc-locks.h"
1109
1110 // Inlined parts of objc_object's implementation
1111 #include "objc-object.h"
1112
1113 #endif /* _OBJC_PRIVATE_H_ */
1114