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/message.h>
163 /***********************************************************************
164 * Information about multi-thread support:
166 * Since we do not lock many operations which walk the superclass, method
167 * and ivar chains, these chains must remain intact once a class is published
168 * by inserting it into the class hashtable. All modifications must be
169 * atomic so that someone walking these chains will always geta valid
171 ***********************************************************************/
175 /***********************************************************************
177 * Locking: None. If you add locking, tell gdb (rdar://7516456).
178 **********************************************************************/
179 Class object_getClass(id obj)
181 if (obj) return obj->getIsa();
186 /***********************************************************************
188 **********************************************************************/
189 Class object_setClass(id obj, Class cls)
191 if (!obj) return nil;
193 // Prevent a deadlock between the weak reference machinery
194 // and the +initialize machinery by ensuring that no
195 // weakly-referenced object has an un-+initialized isa.
196 // Unresolved future classes are not so protected.
197 if (!cls->isFuture() && !cls->isInitialized()) {
198 // use lookUpImpOrNil to indirectly provoke +initialize
199 // to avoid duplicating the code to actually send +initialize
200 lookUpImpOrNil(nil, @selector(initialize), cls, LOOKUP_INITIALIZE);
203 return obj->changeIsa(cls);
207 /***********************************************************************
209 **********************************************************************/
210 BOOL object_isClass(id obj)
213 return obj->isClass();
217 /***********************************************************************
218 * object_getClassName.
219 **********************************************************************/
220 const char *object_getClassName(id obj)
222 return class_getName(obj ? obj->getIsa() : nil);
226 /***********************************************************************
227 * object_getMethodImplementation.
228 **********************************************************************/
229 IMP object_getMethodImplementation(id obj, SEL name)
231 Class cls = (obj ? obj->getIsa() : nil);
232 return class_getMethodImplementation(cls, name);
236 /***********************************************************************
237 * object_getMethodImplementation_stret.
238 **********************************************************************/
240 IMP object_getMethodImplementation_stret(id obj, SEL name)
242 Class cls = (obj ? obj->getIsa() : nil);
243 return class_getMethodImplementation_stret(cls, name);
248 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
250 if (!layout) return NO;
252 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
254 while ((byte = *layout++)) {
255 unsigned skips = (byte >> 4);
256 unsigned scans = (byte & 0x0F);
258 if (index > ivar_index) return NO;
260 if (index > ivar_index) return YES;
266 /***********************************************************************
268 * Given an object and an ivar in it, look up some data about that ivar:
270 * - its memory management behavior
271 * The ivar is assumed to be word-aligned and of of object type.
272 **********************************************************************/
274 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
275 objc_ivar_memory_management_t& memoryManagement)
277 ivarOffset = ivar_getOffset(ivar);
279 // Look for ARC variables and ARC-style weak.
281 // Preflight the hasAutomaticIvars check
282 // because _class_getClassForIvar() may need to take locks.
283 bool hasAutomaticIvars = NO;
284 for (Class c = cls; c; c = c->superclass) {
285 if (c->hasAutomaticIvars()) {
286 hasAutomaticIvars = YES;
291 if (hasAutomaticIvars) {
292 Class ivarCls = _class_getClassForIvar(cls, ivar);
293 if (ivarCls->hasAutomaticIvars()) {
294 // ARC layout bitmaps encode the class's own ivars only.
295 // Use alignedInstanceStart() because unaligned bytes at the start
296 // of this class's ivars are not represented in the layout bitmap.
297 ptrdiff_t localOffset =
298 ivarOffset - ivarCls->alignedInstanceStart();
300 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
301 memoryManagement = objc_ivar_memoryStrong;
305 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
306 memoryManagement = objc_ivar_memoryWeak;
310 // Unretained is only for true ARC classes.
311 if (ivarCls->isARC()) {
312 memoryManagement = objc_ivar_memoryUnretained;
318 memoryManagement = objc_ivar_memoryUnknown;
322 /***********************************************************************
323 * _class_getIvarMemoryManagement
324 * SPI for KVO and others to decide what memory management to use
325 * when setting instance variables directly.
326 **********************************************************************/
327 objc_ivar_memory_management_t
328 _class_getIvarMemoryManagement(Class cls, Ivar ivar)
331 objc_ivar_memory_management_t memoryManagement;
332 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
333 return memoryManagement;
338 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
340 if (!obj || !ivar || obj->isTaggedPointer()) return;
343 objc_ivar_memory_management_t memoryManagement;
344 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
346 if (memoryManagement == objc_ivar_memoryUnknown) {
347 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
348 else memoryManagement = objc_ivar_memoryUnretained;
351 id *location = (id *)((char *)obj + offset);
353 switch (memoryManagement) {
354 case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
355 case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
356 case objc_ivar_memoryUnretained: *location = value; break;
357 case objc_ivar_memoryUnknown: _objc_fatal("impossible");
361 void object_setIvar(id obj, Ivar ivar, id value)
363 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
366 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
368 return _object_setIvar(obj, ivar, value, true /*strong default*/);
372 id object_getIvar(id obj, Ivar ivar)
374 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
377 objc_ivar_memory_management_t memoryManagement;
378 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
380 id *location = (id *)((char *)obj + offset);
382 if (memoryManagement == objc_ivar_memoryWeak) {
383 return objc_loadWeak(location);
391 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
396 if (obj && name && !obj->isTaggedPointer()) {
397 if ((ivar = _class_getVariable(obj->ISA(), name))) {
398 _object_setIvar(obj, ivar, (id)value, assumeStrong);
404 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
406 return _object_setInstanceVariable(obj, name, value, false);
409 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
412 return _object_setInstanceVariable(obj, name, value, true);
416 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
418 if (obj && name && !obj->isTaggedPointer()) {
420 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
421 if (value) *value = (void *)object_getIvar(obj, ivar);
425 if (value) *value = nil;
430 /***********************************************************************
431 * object_cxxDestructFromClass.
432 * Call C++ destructors on obj, starting with cls's
433 * dtor method (if any) followed by superclasses' dtors (if any),
434 * stopping at cls's dtor (if any).
435 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
436 **********************************************************************/
437 static void object_cxxDestructFromClass(id obj, Class cls)
441 // Call cls's dtor first, then superclasses's dtors.
443 for ( ; cls; cls = cls->superclass) {
444 if (!cls->hasCxxDtor()) return;
446 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
447 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
449 _objc_inform("CXX: calling C++ destructors for class %s",
450 cls->nameForLogging());
458 /***********************************************************************
459 * object_cxxDestruct.
460 * Call C++ destructors on obj, if any.
461 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
462 **********************************************************************/
463 void object_cxxDestruct(id obj)
466 if (obj->isTaggedPointer()) return;
467 object_cxxDestructFromClass(obj, obj->ISA());
471 /***********************************************************************
472 * object_cxxConstructFromClass.
473 * Recursively call C++ constructors on obj, starting with base class's
474 * ctor method (if any) followed by subclasses' ctors (if any), stopping
475 * at cls's ctor (if any).
476 * Does not check cls->hasCxxCtor(). The caller should preflight that.
477 * Returns self if construction succeeded.
478 * Returns nil if some constructor threw an exception. The exception is
479 * caught and discarded. Any partial construction is destructed.
480 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
482 * .cxx_construct returns id. This really means:
483 * return self: construction succeeded
484 * return nil: construction failed because a C++ constructor threw an exception
485 **********************************************************************/
487 object_cxxConstructFromClass(id obj, Class cls, int flags)
489 ASSERT(cls->hasCxxCtor()); // required for performance, not correctness
494 supercls = cls->superclass;
496 // Call superclasses' ctors first, if any.
497 if (supercls && supercls->hasCxxCtor()) {
498 bool ok = object_cxxConstructFromClass(obj, supercls, flags);
499 if (slowpath(!ok)) return nil; // some superclass's ctor failed - give up
502 // Find this class's ctor, if any.
503 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
504 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
506 // Call this class's ctor.
508 _objc_inform("CXX: calling C++ constructors for class %s",
509 cls->nameForLogging());
511 if (fastpath((*ctor)(obj))) return obj; // ctor called and succeeded - ok
513 supercls = cls->superclass; // this reload avoids a spill on the stack
515 // This class's ctor was called and failed.
516 // Call superclasses's dtors to clean up.
517 if (supercls) object_cxxDestructFromClass(obj, supercls);
518 if (flags & OBJECT_CONSTRUCT_FREE_ONFAILURE) free(obj);
519 if (flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
520 return _objc_callBadAllocHandler(cls);
526 /***********************************************************************
528 * Fix up ARC strong and ARC-style weak variables
529 * after oldObject was memcpy'd to newObject.
530 **********************************************************************/
531 void fixupCopiedIvars(id newObject, id oldObject)
533 for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
534 if (cls->hasAutomaticIvars()) {
535 // Use alignedInstanceStart() because unaligned bytes at the start
536 // of this class's ivars are not represented in the layout bitmap.
537 size_t instanceStart = cls->alignedInstanceStart();
539 const uint8_t *strongLayout = class_getIvarLayout(cls);
541 id *newPtr = (id *)((char*)newObject + instanceStart);
543 while ((byte = *strongLayout++)) {
544 unsigned skips = (byte >> 4);
545 unsigned scans = (byte & 0x0F);
548 // ensure strong references are properly retained.
549 id value = *newPtr++;
550 if (value) objc_retain(value);
555 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
556 // fix up weak references if any.
558 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
560 while ((byte = *weakLayout++)) {
561 unsigned skips = (byte >> 4);
562 unsigned weaks = (byte & 0x0F);
563 newPtr += skips, oldPtr += skips;
565 objc_copyWeak(newPtr, oldPtr);
576 /***********************************************************************
577 * class_getClassMethod. Return the class method for the specified
578 * class and selector.
579 **********************************************************************/
580 Method class_getClassMethod(Class cls, SEL sel)
582 if (!cls || !sel) return nil;
584 return class_getInstanceMethod(cls->getMeta(), sel);
588 /***********************************************************************
589 * class_getInstanceVariable. Return the named instance variable.
590 **********************************************************************/
591 Ivar class_getInstanceVariable(Class cls, const char *name)
593 if (!cls || !name) return nil;
595 return _class_getVariable(cls, name);
599 /***********************************************************************
600 * class_getClassVariable. Return the named class variable.
601 **********************************************************************/
602 Ivar class_getClassVariable(Class cls, const char *name)
604 if (!cls) return nil;
606 return class_getInstanceVariable(cls->ISA(), name);
610 /***********************************************************************
611 * gdb_objc_class_changed
612 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
613 * Does nothing; gdb sets a breakpoint on it.
614 **********************************************************************/
616 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
620 /***********************************************************************
621 * class_respondsToSelector.
622 **********************************************************************/
623 BOOL class_respondsToMethod(Class cls, SEL sel)
625 OBJC_WARN_DEPRECATED;
627 return class_respondsToSelector(cls, sel);
631 BOOL class_respondsToSelector(Class cls, SEL sel)
633 return class_respondsToSelector_inst(nil, sel, cls);
637 // inst is an instance of cls or a subclass thereof, or nil if none is known.
638 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
640 class_respondsToSelector_inst(id inst, SEL sel, Class cls)
642 // Avoids +initialize because it historically did so.
643 // We're not returning a callable IMP anyway.
644 return sel && cls && lookUpImpOrNil(inst, sel, cls, LOOKUP_RESOLVER);
648 /***********************************************************************
649 * class_getMethodImplementation.
650 * Returns the IMP that would be invoked if [obj sel] were sent,
651 * where obj is an instance of class cls.
652 **********************************************************************/
653 IMP class_lookupMethod(Class cls, SEL sel)
655 OBJC_WARN_DEPRECATED;
657 // No one responds to zero!
659 __objc_error(cls, "invalid selector (null)");
662 return class_getMethodImplementation(cls, sel);
665 IMP class_getMethodImplementation(Class cls, SEL sel)
669 if (!cls || !sel) return nil;
671 imp = lookUpImpOrNil(nil, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER);
673 // Translate forwarding function to C-callable external version
675 return _objc_msgForward;
682 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
684 IMP imp = class_getMethodImplementation(cls, sel);
686 // Translate forwarding function to struct-returning version
687 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
688 return (IMP)&_objc_msgForward_stret;
695 /***********************************************************************
696 * instrumentObjcMessageSends
697 **********************************************************************/
698 // Define this everywhere even if it isn't used to simplify fork() safety code.
699 spinlock_t objcMsgLogLock;
701 #if !SUPPORT_MESSAGE_LOGGING
703 void instrumentObjcMessageSends(BOOL flag)
709 bool objcMsgLogEnabled = false;
710 static int objcMsgLogFD = -1;
712 bool logMessageSend(bool isClassMethod,
713 const char *objectsClass,
714 const char *implementingClass,
719 // Create/open the log file
720 if (objcMsgLogFD == (-1))
722 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
723 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
724 if (objcMsgLogFD < 0) {
725 // no log file - disable logging
726 objcMsgLogEnabled = false;
732 // Make the log entry
733 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
734 isClassMethod ? '+' : '-',
737 sel_getName(selector));
739 objcMsgLogLock.lock();
740 write (objcMsgLogFD, buf, strlen(buf));
741 objcMsgLogLock.unlock();
743 // Tell caller to not cache the method
747 void instrumentObjcMessageSends(BOOL flag)
752 if (objcMsgLogEnabled == enable)
755 // If enabling, flush all method caches so we get some traces
757 _objc_flush_caches(Nil);
760 if (objcMsgLogFD != -1)
761 fsync (objcMsgLogFD);
763 objcMsgLogEnabled = enable;
766 // SUPPORT_MESSAGE_LOGGING
770 Class _calloc_class(size_t size)
772 return (Class) calloc(1, size);
775 Class class_getSuperclass(Class cls)
777 if (!cls) return nil;
778 return cls->superclass;
781 BOOL class_isMetaClass(Class cls)
784 return cls->isMetaClass();
788 size_t class_getInstanceSize(Class cls)
791 return cls->alignedInstanceSize();
795 /***********************************************************************
796 * method_getNumberOfArguments.
797 **********************************************************************/
798 unsigned int method_getNumberOfArguments(Method m)
801 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
805 void method_getReturnType(Method m, char *dst, size_t dst_len)
807 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
811 char * method_copyReturnType(Method m)
813 return encoding_copyReturnType(method_getTypeEncoding(m));
817 void method_getArgumentType(Method m, unsigned int index,
818 char *dst, size_t dst_len)
820 encoding_getArgumentType(method_getTypeEncoding(m),
821 index, dst, dst_len);
825 char * method_copyArgumentType(Method m, unsigned int index)
827 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
830 /***********************************************************************
831 * _class_createInstancesFromZone
832 * Batch-allocating version of _class_createInstanceFromZone.
833 * Attempts to allocate num_requested objects, each with extraBytes.
834 * Returns the number of allocated objects (possibly zero), with
835 * the allocated pointers in *results.
836 **********************************************************************/
838 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
839 id *results, unsigned num_requested)
841 unsigned num_allocated;
844 size_t size = cls->instanceSize(extraBytes);
847 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
848 size, (void**)results, num_requested);
849 for (unsigned i = 0; i < num_allocated; i++) {
850 bzero(results[i], size);
853 // Construct each object, and delete any that fail construction.
856 bool ctor = cls->hasCxxCtor();
857 for (unsigned i = 0; i < num_allocated; i++) {
859 obj->initIsa(cls); // fixme allow nonpointer
861 obj = object_cxxConstructFromClass(obj, cls,
862 OBJECT_CONSTRUCT_FREE_ONFAILURE);
865 results[i-shift] = obj;
871 return num_allocated - shift;
875 /***********************************************************************
876 * inform_duplicate. Complain about duplicate class implementations.
877 **********************************************************************/
879 inform_duplicate(const char *name, Class oldCls, Class newCls)
882 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
883 ("Class %s is implemented in two different images.", name);
885 const header_info *oldHeader = _headerForClass(oldCls);
886 const header_info *newHeader = _headerForClass(newCls);
887 const char *oldName = oldHeader ? oldHeader->fname() : "??";
888 const char *newName = newHeader ? newHeader->fname() : "??";
890 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
891 ("Class %s is implemented in both %s (%p) and %s (%p). "
892 "One of the two will be used. Which one is undefined.",
893 name, oldName, oldCls, newName, newCls);
899 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
904 if (count == 0) return strdup("");
907 // debug build: sanitize input
908 for (i = 0; i < count; i++) {
909 ASSERT(attrs[i].name);
910 ASSERT(strlen(attrs[i].name) > 0);
911 ASSERT(! strchr(attrs[i].name, ','));
912 ASSERT(! strchr(attrs[i].name, '"'));
913 if (attrs[i].value) ASSERT(! strchr(attrs[i].value, ','));
918 for (i = 0; i < count; i++) {
919 if (attrs[i].value) {
920 size_t namelen = strlen(attrs[i].name);
921 if (namelen > 1) namelen += 2; // long names get quoted
922 len += namelen + strlen(attrs[i].value) + 1;
926 result = (char *)malloc(len + 1);
928 for (i = 0; i < count; i++) {
929 if (attrs[i].value) {
930 size_t namelen = strlen(attrs[i].name);
932 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
934 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
939 // remove trailing ',' if any
940 if (s > result) s[-1] = '\0';
946 Property attribute string format:
948 - Comma-separated name-value pairs.
949 - Name and value may not contain ,
950 - Name may not contain "
952 - Name is single char, value follows
953 - OR Name is double-quoted string of 2+ chars, value follows
957 attribute-string: name-value-pair (',' name-value-pair)*
958 name-value-pair: unquoted-name optional-value
959 name-value-pair: quoted-name optional-value
961 quoted-name: '"' [^",]{2,} '"'
962 optional-value: [^,]*
966 iteratePropertyAttributes(const char *attrs,
967 bool (*fn)(unsigned int index,
968 void *ctx1, void *ctx2,
969 const char *name, size_t nlen,
970 const char *value, size_t vlen),
971 void *ctx1, void *ctx2)
973 if (!attrs) return 0;
976 const char *attrsend = attrs + strlen(attrs);
978 unsigned int attrcount = 0;
981 // Find the next comma-separated attribute
982 const char *start = attrs;
983 const char *end = start + strcspn(attrs, ",");
985 // Move attrs past this attribute and the comma (if any)
986 attrs = *end ? end+1 : end;
988 assert(attrs <= attrsend);
989 assert(start <= attrsend);
990 assert(end <= attrsend);
992 // Skip empty attribute
993 if (start == end) continue;
995 // Process one non-empty comma-free attribute [start,end)
996 const char *nameStart;
1001 if (*start != '\"') {
1002 // single-char short name
1008 // double-quoted long name
1009 nameStart = start+1;
1010 nameEnd = nameStart + strcspn(nameStart, "\",");
1011 start++; // leading quote
1012 start += nameEnd - nameStart; // name
1013 if (*start == '\"') start++; // trailing quote, if any
1016 // Process one possibly-empty comma-free attribute value [start,end)
1017 const char *valueStart;
1018 const char *valueEnd;
1020 ASSERT(start <= end);
1025 bool more = (*fn)(attrcount, ctx1, ctx2,
1026 nameStart, nameEnd-nameStart,
1027 valueStart, valueEnd-valueStart);
1037 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1038 const char *name, size_t nlen, const char *value, size_t vlen)
1040 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1041 char **sp = (char **)ctxs;
1043 objc_property_attribute_t *a = *ap;
1047 memcpy(s, name, nlen);
1052 memcpy(s, value, vlen);
1065 objc_property_attribute_t *
1066 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1069 if (outCount) *outCount = 0;
1074 // number of commas plus 1 for the attributes (upper bound)
1075 // plus another attribute for the attribute array terminator
1076 // plus strlen(attrs) for name/value string data (upper bound)
1077 // plus count*2 for the name/value string terminators (upper bound)
1078 unsigned int attrcount = 1;
1080 for (s = attrs; s && *s; s++) {
1081 if (*s == ',') attrcount++;
1085 attrcount * sizeof(objc_property_attribute_t) +
1086 sizeof(objc_property_attribute_t) +
1089 objc_property_attribute_t *result = (objc_property_attribute_t *)
1092 objc_property_attribute_t *ra = result;
1093 char *rs = (char *)(ra+attrcount+1);
1095 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1097 ASSERT((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1098 ASSERT((uint8_t *)rs <= (uint8_t *)result+size);
1100 if (attrcount == 0) {
1105 if (outCount) *outCount = attrcount;
1111 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1112 const char *name, size_t nlen, const char *value, size_t vlen)
1114 const char *query = (char *)ctxa;
1115 char **resultp = (char **)ctxs;
1117 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1118 char *result = (char *)calloc(vlen+1, 1);
1119 memcpy(result, value, vlen);
1120 result[vlen] = '\0';
1128 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1132 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);