2 * Copyright (c) 1999-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@
23 /***********************************************************************
25 * Copyright 1988-1997, Apple Computer, Inc.
27 **********************************************************************/
30 /***********************************************************************
31 * Lazy method list arrays and method list locking (2004-10-19)
33 * cls->methodLists may be in one of three forms:
34 * 1. nil: The class has no methods.
35 * 2. non-nil, with CLS_NO_METHOD_ARRAY set: cls->methodLists points
36 * to a single method list, which is the class's only method list.
37 * 3. non-nil, with CLS_NO_METHOD_ARRAY clear: cls->methodLists points to
38 * an array of method list pointers. The end of the array's block
39 * is set to -1. If the actual number of method lists is smaller
40 * than that, the rest of the array is nil.
42 * Attaching categories and adding and removing classes may change
43 * the form of the class list. In addition, individual method lists
44 * may be reallocated when fixed up.
46 * Classes are initially read as #1 or #2. If a category is attached
47 * or other methods added, the class is changed to #3. Once in form #3,
48 * the class is never downgraded to #1 or #2, even if methods are removed.
49 * Classes added with objc_addClass are initially either #1 or #3.
51 * Accessing and manipulating a class's method lists are synchronized,
52 * to prevent races when one thread restructures the list. However,
53 * if the class is not yet in use (i.e. not in class_hash), then the
54 * thread loading the class may access its method lists without locking.
56 * The following functions acquire methodListLock:
57 * class_getInstanceMethod
58 * class_getClassMethod
59 * class_nextMethodList
62 * class_respondsToMethod
63 * _class_lookupMethodAndLoadCache
64 * lookupMethodInClassAndLoadCache
65 * _objc_add_category_flush_caches
67 * The following functions don't acquire methodListLock because they
68 * only access method lists during class load and unload:
69 * _objc_register_category
70 * _resolve_categories_for_class (calls _objc_add_category)
71 * add_class_to_loadable_list
73 * _objc_remove_classes_in_image
75 * The following functions use method lists without holding methodListLock.
76 * The caller must either hold methodListLock, or be loading the class.
77 * _getMethod (called by class_getInstanceMethod, class_getClassMethod,
78 * and class_respondsToMethod)
79 * _findMethodInClass (called by _class_lookupMethodAndLoadCache,
80 * lookupMethodInClassAndLoadCache, _getMethod)
81 * _findMethodInList (called by _findMethodInClass)
82 * nextMethodList (called by _findMethodInClass and class_nextMethodList
83 * fixupSelectorsInMethodList (called by nextMethodList)
84 * _objc_add_category (called by _objc_add_category_flush_caches,
85 * resolve_categories_for_class and _objc_register_category)
86 * _objc_insertMethods (called by class_addMethods and _objc_add_category)
87 * _objc_removeMethods (called by class_removeMethods)
88 * _objcTweakMethodListPointerForClass (called by _objc_insertMethods)
89 * get_base_method_list (called by add_class_to_loadable_list)
90 * lookupNamedMethodInMethodList (called by add_class_to_loadable_list)
91 ***********************************************************************/
93 /***********************************************************************
94 * Thread-safety of class info bits (2004-10-19)
96 * Some class info bits are used to store mutable runtime state.
97 * Modifications of the info bits at particular times need to be
98 * synchronized to prevent races.
100 * Three thread-safe modification functions are provided:
101 * cls->setInfo() // atomically sets some bits
102 * cls->clearInfo() // atomically clears some bits
103 * cls->changeInfo() // atomically sets some bits and clears others
104 * These replace CLS_SETINFO() for the multithreaded cases.
106 * Three modification windows are defined:
108 * - class construction or image load (before +load) in one thread
109 * - multi-threaded messaging and method caches
111 * Info bit modification at compile time and class construction do not
112 * need to be locked, because only one thread is manipulating the class.
113 * Info bit modification during messaging needs to be locked, because
114 * there may be other threads simultaneously messaging or otherwise
115 * manipulating the class.
117 * Modification windows for each flag:
119 * CLS_CLASS: compile-time and class load
120 * CLS_META: compile-time and class load
121 * CLS_INITIALIZED: +initialize
122 * CLS_POSING: messaging
123 * CLS_MAPPED: compile-time
124 * CLS_FLUSH_CACHE: class load and messaging
125 * CLS_GROW_CACHE: messaging
126 * CLS_NEED_BIND: unused
127 * CLS_METHOD_ARRAY: unused
128 * CLS_JAVA_HYBRID: JavaBridge only
129 * CLS_JAVA_CLASS: JavaBridge only
130 * CLS_INITIALIZING: messaging
131 * CLS_FROM_BUNDLE: class load
132 * CLS_HAS_CXX_STRUCTORS: compile-time and class load
133 * CLS_NO_METHOD_ARRAY: class load and messaging
134 * CLS_HAS_LOAD_METHOD: class load
136 * CLS_INITIALIZED and CLS_INITIALIZING have additional thread-safety
137 * constraints to support thread-safe +initialize. See "Thread safety
138 * during class initialization" for details.
140 * CLS_JAVA_HYBRID and CLS_JAVA_CLASS are set immediately after JavaBridge
141 * calls objc_addClass(). The JavaBridge does not use an atomic update,
142 * but the modification counts as "class construction" unless some other
143 * thread quickly finds the class via the class list. This race is
144 * small and unlikely in well-behaved code.
146 * Most info bits that may be modified during messaging are also never
147 * read without a lock. There is no general read lock for the info bits.
148 * CLS_INITIALIZED: classInitLock
149 * CLS_FLUSH_CACHE: cacheUpdateLock
150 * CLS_GROW_CACHE: cacheUpdateLock
151 * CLS_NO_METHOD_ARRAY: methodListLock
152 * CLS_INITIALIZING: classInitLock
153 ***********************************************************************/
155 /***********************************************************************
157 **********************************************************************/
159 #include "objc-private.h"
160 #include "objc-abi.h"
161 #include "objc-auto.h"
162 #include <objc/message.h>
165 /* overriding the default object allocation and error handling routines */
167 OBJC_EXPORT id (*_alloc)(Class, size_t);
168 OBJC_EXPORT id (*_copy)(id, size_t);
169 OBJC_EXPORT id (*_realloc)(id, size_t);
170 OBJC_EXPORT id (*_dealloc)(id);
171 OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *);
172 OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *);
173 OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *);
176 /***********************************************************************
177 * Information about multi-thread support:
179 * Since we do not lock many operations which walk the superclass, method
180 * and ivar chains, these chains must remain intact once a class is published
181 * by inserting it into the class hashtable. All modifications must be
182 * atomic so that someone walking these chains will always geta valid
184 ***********************************************************************/
188 /***********************************************************************
190 * Locking: None. If you add locking, tell gdb (rdar://7516456).
191 **********************************************************************/
192 Class object_getClass(id obj)
194 if (obj) return obj->getIsa();
199 /***********************************************************************
201 **********************************************************************/
202 Class object_setClass(id obj, Class cls)
204 if (!obj) return nil;
206 // Prevent a deadlock between the weak reference machinery
207 // and the +initialize machinery by ensuring that no
208 // weakly-referenced object has an un-+initialized isa.
209 // Unresolved future classes are not so protected.
210 if (!cls->isFuture() && !cls->isInitialized()) {
211 _class_initialize(_class_getNonMetaClass(cls, nil));
214 return obj->changeIsa(cls);
218 /***********************************************************************
220 **********************************************************************/
221 BOOL object_isClass(id obj)
224 return obj->isClass();
228 /***********************************************************************
229 * object_getClassName.
230 **********************************************************************/
231 const char *object_getClassName(id obj)
233 return class_getName(obj ? obj->getIsa() : nil);
237 /***********************************************************************
238 * object_getMethodImplementation.
239 **********************************************************************/
240 IMP object_getMethodImplementation(id obj, SEL name)
242 Class cls = (obj ? obj->getIsa() : nil);
243 return class_getMethodImplementation(cls, name);
247 /***********************************************************************
248 * object_getMethodImplementation_stret.
249 **********************************************************************/
251 IMP object_getMethodImplementation_stret(id obj, SEL name)
253 Class cls = (obj ? obj->getIsa() : nil);
254 return class_getMethodImplementation_stret(cls, name);
259 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
263 if (obj && name && !obj->isTaggedPointer()) {
264 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
265 object_setIvar(obj, ivar, (id)value);
271 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
273 if (obj && name && !obj->isTaggedPointer()) {
275 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
276 if (value) *value = (void *)object_getIvar(obj, ivar);
280 if (value) *value = nil;
284 static bool is_scanned_offset(ptrdiff_t ivar_offset, const uint8_t *layout) {
285 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
287 while ((byte = *layout++)) {
288 unsigned skips = (byte >> 4);
289 unsigned scans = (byte & 0x0F);
292 if (index == ivar_index) return YES;
293 if (index > ivar_index) return NO;
300 // FIXME: this could be optimized.
302 static Class _ivar_getClass(Class cls, Ivar ivar) {
303 Class ivar_class = nil;
304 const char *ivar_name = ivar_getName(ivar);
305 Ivar named_ivar = _class_getVariable(cls, ivar_name, &ivar_class);
307 // the same ivar name can appear multiple times along the superclass chain.
308 while (named_ivar != ivar && ivar_class != nil) {
309 ivar_class = ivar_class->superclass;
310 named_ivar = _class_getVariable(cls, ivar_getName(ivar), &ivar_class);
316 void object_setIvar(id obj, Ivar ivar, id value)
318 if (obj && ivar && !obj->isTaggedPointer()) {
319 Class cls = _ivar_getClass(obj->ISA(), ivar);
320 ptrdiff_t ivar_offset = ivar_getOffset(ivar);
321 id *location = (id *)((char *)obj + ivar_offset);
322 // if this ivar is a member of an ARR compiled class, then issue the correct barrier according to the layout.
323 if (_class_usesAutomaticRetainRelease(cls)) {
324 // for ARR, layout strings are relative to the instance start.
325 uint32_t instanceStart = _class_getInstanceStart(cls);
326 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
327 if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) {
328 // use the weak system to write to this variable.
329 objc_storeWeak(location, value);
332 const uint8_t *strong_layout = class_getIvarLayout(cls);
333 if (strong_layout && is_scanned_offset(ivar_offset - instanceStart, strong_layout)) {
334 objc_storeStrong(location, value);
340 // for GC, check for weak references.
341 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
342 if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) {
343 objc_assign_weak(value, location);
346 objc_assign_ivar(value, obj, ivar_offset);
354 id object_getIvar(id obj, Ivar ivar)
356 if (obj && ivar && !obj->isTaggedPointer()) {
357 Class cls = obj->ISA();
358 ptrdiff_t ivar_offset = ivar_getOffset(ivar);
359 if (_class_usesAutomaticRetainRelease(cls)) {
360 // for ARR, layout strings are relative to the instance start.
361 uint32_t instanceStart = _class_getInstanceStart(cls);
362 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
363 if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) {
364 // use the weak system to read this variable.
365 id *location = (id *)((char *)obj + ivar_offset);
366 return objc_loadWeak(location);
369 id *idx = (id *)((char *)obj + ivar_offset);
372 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
373 if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) {
374 return objc_read_weak(idx);
384 /***********************************************************************
385 * object_cxxDestructFromClass.
386 * Call C++ destructors on obj, starting with cls's
387 * dtor method (if any) followed by superclasses' dtors (if any),
388 * stopping at cls's dtor (if any).
389 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
390 **********************************************************************/
391 static void object_cxxDestructFromClass(id obj, Class cls)
395 // Call cls's dtor first, then superclasses's dtors.
397 for ( ; cls; cls = cls->superclass) {
398 if (!cls->hasCxxDtor()) return;
400 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
401 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
403 _objc_inform("CXX: calling C++ destructors for class %s",
404 cls->nameForLogging());
412 /***********************************************************************
413 * object_cxxDestruct.
414 * Call C++ destructors on obj, if any.
415 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
416 **********************************************************************/
417 void object_cxxDestruct(id obj)
420 if (obj->isTaggedPointer()) return;
421 object_cxxDestructFromClass(obj, obj->ISA());
425 /***********************************************************************
426 * object_cxxConstructFromClass.
427 * Recursively call C++ constructors on obj, starting with base class's
428 * ctor method (if any) followed by subclasses' ctors (if any), stopping
429 * at cls's ctor (if any).
430 * Does not check cls->hasCxxCtor(). The caller should preflight that.
431 * Returns self if construction succeeded.
432 * Returns nil if some constructor threw an exception. The exception is
433 * caught and discarded. Any partial construction is destructed.
434 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
436 * .cxx_construct returns id. This really means:
437 * return self: construction succeeded
438 * return nil: construction failed because a C++ constructor threw an exception
439 **********************************************************************/
441 object_cxxConstructFromClass(id obj, Class cls)
443 assert(cls->hasCxxCtor()); // required for performance, not correctness
448 supercls = cls->superclass;
450 // Call superclasses' ctors first, if any.
451 if (supercls && supercls->hasCxxCtor()) {
452 bool ok = object_cxxConstructFromClass(obj, supercls);
453 if (!ok) return nil; // some superclass's ctor failed - give up
456 // Find this class's ctor, if any.
457 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
458 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
460 // Call this class's ctor.
462 _objc_inform("CXX: calling C++ constructors for class %s",
463 cls->nameForLogging());
465 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
467 // This class's ctor was called and failed.
468 // Call superclasses's dtors to clean up.
469 if (supercls) object_cxxDestructFromClass(obj, supercls);
474 /***********************************************************************
475 * _class_resolveClassMethod
476 * Call +resolveClassMethod, looking for a method to be added to class cls.
477 * cls should be a metaclass.
478 * Does not check if the method already exists.
479 **********************************************************************/
480 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
482 assert(cls->isMetaClass());
484 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
485 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
487 // Resolver not implemented.
491 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
492 bool resolved = msg(_class_getNonMetaClass(cls, inst),
493 SEL_resolveClassMethod, sel);
495 // Cache the result (good or bad) so the resolver doesn't fire next time.
496 // +resolveClassMethod adds to self->ISA() a.k.a. cls
497 IMP imp = lookUpImpOrNil(cls, sel, inst,
498 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
500 if (resolved && PrintResolving) {
502 _objc_inform("RESOLVE: method %c[%s %s] "
503 "dynamically resolved to %p",
504 cls->isMetaClass() ? '+' : '-',
505 cls->nameForLogging(), sel_getName(sel), imp);
508 // Method resolver didn't add anything?
509 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
510 ", but no new implementation of %c[%s %s] was found",
511 cls->nameForLogging(), sel_getName(sel),
512 cls->isMetaClass() ? '+' : '-',
513 cls->nameForLogging(), sel_getName(sel));
519 /***********************************************************************
520 * _class_resolveInstanceMethod
521 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
522 * cls may be a metaclass or a non-meta class.
523 * Does not check if the method already exists.
524 **********************************************************************/
525 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
527 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
528 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
530 // Resolver not implemented.
534 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
535 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
537 // Cache the result (good or bad) so the resolver doesn't fire next time.
538 // +resolveInstanceMethod adds to self a.k.a. cls
539 IMP imp = lookUpImpOrNil(cls, sel, inst,
540 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
542 if (resolved && PrintResolving) {
544 _objc_inform("RESOLVE: method %c[%s %s] "
545 "dynamically resolved to %p",
546 cls->isMetaClass() ? '+' : '-',
547 cls->nameForLogging(), sel_getName(sel), imp);
550 // Method resolver didn't add anything?
551 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
552 ", but no new implementation of %c[%s %s] was found",
553 cls->nameForLogging(), sel_getName(sel),
554 cls->isMetaClass() ? '+' : '-',
555 cls->nameForLogging(), sel_getName(sel));
561 /***********************************************************************
562 * _class_resolveMethod
563 * Call +resolveClassMethod or +resolveInstanceMethod.
564 * Returns nothing; any result would be potentially out-of-date already.
565 * Does not check if the method already exists.
566 **********************************************************************/
567 void _class_resolveMethod(Class cls, SEL sel, id inst)
569 if (! cls->isMetaClass()) {
570 // try [cls resolveInstanceMethod:sel]
571 _class_resolveInstanceMethod(cls, sel, inst);
574 // try [nonMetaClass resolveClassMethod:sel]
575 // and [cls resolveInstanceMethod:sel]
576 _class_resolveClassMethod(cls, sel, inst);
577 if (!lookUpImpOrNil(cls, sel, inst,
578 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
580 _class_resolveInstanceMethod(cls, sel, inst);
586 /***********************************************************************
587 * class_getClassMethod. Return the class method for the specified
588 * class and selector.
589 **********************************************************************/
590 Method class_getClassMethod(Class cls, SEL sel)
592 if (!cls || !sel) return nil;
594 return class_getInstanceMethod(cls->getMeta(), sel);
598 /***********************************************************************
599 * class_getInstanceVariable. Return the named instance variable.
600 **********************************************************************/
601 Ivar class_getInstanceVariable(Class cls, const char *name)
603 if (!cls || !name) return nil;
605 return _class_getVariable(cls, name, nil);
609 /***********************************************************************
610 * class_getClassVariable. Return the named class variable.
611 **********************************************************************/
612 Ivar class_getClassVariable(Class cls, const char *name)
614 if (!cls) return nil;
616 return class_getInstanceVariable(cls->ISA(), name);
620 /***********************************************************************
621 * gdb_objc_class_changed
622 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
623 * Does nothing; gdb sets a breakpoint on it.
624 **********************************************************************/
626 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
630 /***********************************************************************
631 * class_respondsToSelector.
632 **********************************************************************/
633 BOOL class_respondsToMethod(Class cls, SEL sel)
635 OBJC_WARN_DEPRECATED;
637 return class_respondsToSelector(cls, sel);
641 BOOL class_respondsToSelector(Class cls, SEL sel)
643 return class_respondsToSelector_inst(cls, sel, nil);
647 // inst is an instance of cls or a subclass thereof, or nil if none is known.
648 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
649 bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
653 if (!sel || !cls) return NO;
655 // Avoids +initialize because it historically did so.
656 // We're not returning a callable IMP anyway.
657 imp = lookUpImpOrNil(cls, sel, inst,
658 NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
663 /***********************************************************************
664 * class_getMethodImplementation.
665 * Returns the IMP that would be invoked if [obj sel] were sent,
666 * where obj is an instance of class cls.
667 **********************************************************************/
668 IMP class_lookupMethod(Class cls, SEL sel)
670 OBJC_WARN_DEPRECATED;
672 // No one responds to zero!
674 __objc_error(cls, "invalid selector (null)");
677 return class_getMethodImplementation(cls, sel);
680 IMP class_getMethodImplementation(Class cls, SEL sel)
684 if (!cls || !sel) return nil;
686 imp = lookUpImpOrNil(cls, sel, nil,
687 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
689 // Translate forwarding function to C-callable external version
691 return _objc_msgForward;
698 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
700 IMP imp = class_getMethodImplementation(cls, sel);
702 // Translate forwarding function to struct-returning version
703 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
704 return (IMP)&_objc_msgForward_stret;
711 /***********************************************************************
712 * instrumentObjcMessageSends
713 **********************************************************************/
714 #if !SUPPORT_MESSAGE_LOGGING
716 void instrumentObjcMessageSends(BOOL flag)
722 bool objcMsgLogEnabled = false;
723 static int objcMsgLogFD = -1;
725 bool logMessageSend(bool isClassMethod,
726 const char *objectsClass,
727 const char *implementingClass,
732 // Create/open the log file
733 if (objcMsgLogFD == (-1))
735 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
736 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
737 if (objcMsgLogFD < 0) {
738 // no log file - disable logging
739 objcMsgLogEnabled = false;
745 // Make the log entry
746 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
747 isClassMethod ? '+' : '-',
750 sel_getName(selector));
752 static spinlock_t lock;
754 write (objcMsgLogFD, buf, strlen(buf));
757 // Tell caller to not cache the method
761 void instrumentObjcMessageSends(BOOL flag)
766 if (objcMsgLogEnabled == enable)
769 // If enabling, flush all method caches so we get some traces
771 _objc_flush_caches(Nil);
774 if (objcMsgLogFD != -1)
775 fsync (objcMsgLogFD);
777 objcMsgLogEnabled = enable;
780 // SUPPORT_MESSAGE_LOGGING
784 Class _calloc_class(size_t size)
787 if (UseGC) return (Class) malloc_zone_calloc(gc_zone, 1, size);
789 return (Class) calloc(1, size);
792 Class class_getSuperclass(Class cls)
794 if (!cls) return nil;
795 return cls->superclass;
798 BOOL class_isMetaClass(Class cls)
801 return cls->isMetaClass();
805 size_t class_getInstanceSize(Class cls)
808 return cls->alignedInstanceSize();
812 /***********************************************************************
813 * method_getNumberOfArguments.
814 **********************************************************************/
815 unsigned int method_getNumberOfArguments(Method m)
818 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
822 void method_getReturnType(Method m, char *dst, size_t dst_len)
824 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
828 char * method_copyReturnType(Method m)
830 return encoding_copyReturnType(method_getTypeEncoding(m));
834 void method_getArgumentType(Method m, unsigned int index,
835 char *dst, size_t dst_len)
837 encoding_getArgumentType(method_getTypeEncoding(m),
838 index, dst, dst_len);
842 char * method_copyArgumentType(Method m, unsigned int index)
844 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
848 /***********************************************************************
849 * _objc_constructOrFree
850 * Call C++ constructors, and free() if they fail.
851 * bytes->isa must already be set.
852 * cls must have cxx constructors.
853 * Returns the object, or nil.
854 **********************************************************************/
856 _objc_constructOrFree(id bytes, Class cls)
858 assert(cls->hasCxxCtor()); // for performance, not correctness
860 id obj = object_cxxConstructFromClass(bytes, cls);
864 auto_zone_retain(gc_zone, bytes); // gc free expects rc==1
874 /***********************************************************************
875 * _class_createInstancesFromZone
876 * Batch-allocating version of _class_createInstanceFromZone.
877 * Attempts to allocate num_requested objects, each with extraBytes.
878 * Returns the number of allocated objects (possibly zero), with
879 * the allocated pointers in *results.
880 **********************************************************************/
882 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
883 id *results, unsigned num_requested)
885 unsigned num_allocated;
888 size_t size = cls->instanceSize(extraBytes);
893 auto_zone_batch_allocate(gc_zone, size, AUTO_OBJECT_SCANNED, 0, 1,
894 (void**)results, num_requested);
900 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
901 size, (void**)results, num_requested);
902 for (i = 0; i < num_allocated; i++) {
903 bzero(results[i], size);
907 // Construct each object, and delete any that fail construction.
911 bool ctor = cls->hasCxxCtor();
912 for (i = 0; i < num_allocated; i++) {
914 obj->initIsa(cls); // fixme allow indexed
915 if (ctor) obj = _objc_constructOrFree(obj, cls);
918 results[i-shift] = obj;
924 return num_allocated - shift;
928 /***********************************************************************
929 * inform_duplicate. Complain about duplicate class implementations.
930 **********************************************************************/
932 inform_duplicate(const char *name, Class oldCls, Class cls)
935 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
936 ("Class %s is implemented in two different images.", name);
938 const header_info *oldHeader = _headerForClass(oldCls);
939 const header_info *newHeader = _headerForClass(cls);
940 const char *oldName = oldHeader ? oldHeader->fname : "??";
941 const char *newName = newHeader ? newHeader->fname : "??";
943 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
944 ("Class %s is implemented in both %s and %s. "
945 "One of the two will be used. Which one is undefined.",
946 name, oldName, newName);
952 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
957 if (count == 0) return strdup("");
960 // debug build: sanitize input
961 for (i = 0; i < count; i++) {
962 assert(attrs[i].name);
963 assert(strlen(attrs[i].name) > 0);
964 assert(! strchr(attrs[i].name, ','));
965 assert(! strchr(attrs[i].name, '"'));
966 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
971 for (i = 0; i < count; i++) {
972 if (attrs[i].value) {
973 size_t namelen = strlen(attrs[i].name);
974 if (namelen > 1) namelen += 2; // long names get quoted
975 len += namelen + strlen(attrs[i].value) + 1;
979 result = (char *)malloc(len + 1);
981 for (i = 0; i < count; i++) {
982 if (attrs[i].value) {
983 size_t namelen = strlen(attrs[i].name);
985 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
987 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
992 // remove trailing ',' if any
993 if (s > result) s[-1] = '\0';
999 Property attribute string format:
1001 - Comma-separated name-value pairs.
1002 - Name and value may not contain ,
1003 - Name may not contain "
1004 - Value may be empty
1005 - Name is single char, value follows
1006 - OR Name is double-quoted string of 2+ chars, value follows
1009 attribute-string: \0
1010 attribute-string: name-value-pair (',' name-value-pair)*
1011 name-value-pair: unquoted-name optional-value
1012 name-value-pair: quoted-name optional-value
1013 unquoted-name: [^",]
1014 quoted-name: '"' [^",]{2,} '"'
1015 optional-value: [^,]*
1019 iteratePropertyAttributes(const char *attrs,
1020 bool (*fn)(unsigned int index,
1021 void *ctx1, void *ctx2,
1022 const char *name, size_t nlen,
1023 const char *value, size_t vlen),
1024 void *ctx1, void *ctx2)
1026 if (!attrs) return 0;
1029 const char *attrsend = attrs + strlen(attrs);
1031 unsigned int attrcount = 0;
1034 // Find the next comma-separated attribute
1035 const char *start = attrs;
1036 const char *end = start + strcspn(attrs, ",");
1038 // Move attrs past this attribute and the comma (if any)
1039 attrs = *end ? end+1 : end;
1041 assert(attrs <= attrsend);
1042 assert(start <= attrsend);
1043 assert(end <= attrsend);
1045 // Skip empty attribute
1046 if (start == end) continue;
1048 // Process one non-empty comma-free attribute [start,end)
1049 const char *nameStart;
1050 const char *nameEnd;
1052 assert(start < end);
1054 if (*start != '\"') {
1055 // single-char short name
1061 // double-quoted long name
1062 nameStart = start+1;
1063 nameEnd = nameStart + strcspn(nameStart, "\",");
1064 start++; // leading quote
1065 start += nameEnd - nameStart; // name
1066 if (*start == '\"') start++; // trailing quote, if any
1069 // Process one possibly-empty comma-free attribute value [start,end)
1070 const char *valueStart;
1071 const char *valueEnd;
1073 assert(start <= end);
1078 bool more = (*fn)(attrcount, ctx1, ctx2,
1079 nameStart, nameEnd-nameStart,
1080 valueStart, valueEnd-valueStart);
1090 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1091 const char *name, size_t nlen, const char *value, size_t vlen)
1093 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1094 char **sp = (char **)ctxs;
1096 objc_property_attribute_t *a = *ap;
1100 memcpy(s, name, nlen);
1105 memcpy(s, value, vlen);
1118 objc_property_attribute_t *
1119 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1122 if (outCount) *outCount = 0;
1127 // number of commas plus 1 for the attributes (upper bound)
1128 // plus another attribute for the attribute array terminator
1129 // plus strlen(attrs) for name/value string data (upper bound)
1130 // plus count*2 for the name/value string terminators (upper bound)
1131 unsigned int attrcount = 1;
1133 for (s = attrs; s && *s; s++) {
1134 if (*s == ',') attrcount++;
1138 attrcount * sizeof(objc_property_attribute_t) +
1139 sizeof(objc_property_attribute_t) +
1142 objc_property_attribute_t *result = (objc_property_attribute_t *)
1145 objc_property_attribute_t *ra = result;
1146 char *rs = (char *)(ra+attrcount+1);
1148 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1150 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1151 assert((uint8_t *)rs <= (uint8_t *)result+size);
1153 if (attrcount == 0) {
1158 if (outCount) *outCount = attrcount;
1164 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1165 const char *name, size_t nlen, const char *value, size_t vlen)
1167 const char *query = (char *)ctxa;
1168 char **resultp = (char **)ctxs;
1170 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1171 char *result = (char *)calloc(vlen+1, 1);
1172 memcpy(result, value, vlen);
1173 result[vlen] = '\0';
1181 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1185 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);