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 lookUpImpOrForward to indirectly provoke +initialize
199 // to avoid duplicating the code to actually send +initialize
200 lookUpImpOrForward(cls, SEL_initialize, nil,
201 YES/*initialize*/, YES/*cache*/, NO/*resolver*/);
204 return obj->changeIsa(cls);
208 /***********************************************************************
210 **********************************************************************/
211 BOOL object_isClass(id obj)
214 return obj->isClass();
218 /***********************************************************************
219 * object_getClassName.
220 **********************************************************************/
221 const char *object_getClassName(id obj)
223 return class_getName(obj ? obj->getIsa() : nil);
227 /***********************************************************************
228 * object_getMethodImplementation.
229 **********************************************************************/
230 IMP object_getMethodImplementation(id obj, SEL name)
232 Class cls = (obj ? obj->getIsa() : nil);
233 return class_getMethodImplementation(cls, name);
237 /***********************************************************************
238 * object_getMethodImplementation_stret.
239 **********************************************************************/
241 IMP object_getMethodImplementation_stret(id obj, SEL name)
243 Class cls = (obj ? obj->getIsa() : nil);
244 return class_getMethodImplementation_stret(cls, name);
249 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
251 if (!layout) return NO;
253 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
255 while ((byte = *layout++)) {
256 unsigned skips = (byte >> 4);
257 unsigned scans = (byte & 0x0F);
259 if (index > ivar_index) return NO;
261 if (index > ivar_index) return YES;
267 /***********************************************************************
269 * Given an object and an ivar in it, look up some data about that ivar:
271 * - its memory management behavior
272 * The ivar is assumed to be word-aligned and of of object type.
273 **********************************************************************/
275 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
276 objc_ivar_memory_management_t& memoryManagement)
278 ivarOffset = ivar_getOffset(ivar);
280 // Look for ARC variables and ARC-style weak.
282 // Preflight the hasAutomaticIvars check
283 // because _class_getClassForIvar() may need to take locks.
284 bool hasAutomaticIvars = NO;
285 for (Class c = cls; c; c = c->superclass) {
286 if (c->hasAutomaticIvars()) {
287 hasAutomaticIvars = YES;
292 if (hasAutomaticIvars) {
293 Class ivarCls = _class_getClassForIvar(cls, ivar);
294 if (ivarCls->hasAutomaticIvars()) {
295 // ARC layout bitmaps encode the class's own ivars only.
296 // Use alignedInstanceStart() because unaligned bytes at the start
297 // of this class's ivars are not represented in the layout bitmap.
298 ptrdiff_t localOffset =
299 ivarOffset - ivarCls->alignedInstanceStart();
301 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
302 memoryManagement = objc_ivar_memoryStrong;
306 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
307 memoryManagement = objc_ivar_memoryWeak;
311 // Unretained is only for true ARC classes.
312 if (ivarCls->isARC()) {
313 memoryManagement = objc_ivar_memoryUnretained;
319 memoryManagement = objc_ivar_memoryUnknown;
323 /***********************************************************************
324 * _class_getIvarMemoryManagement
325 * SPI for KVO and others to decide what memory management to use
326 * when setting instance variables directly.
327 **********************************************************************/
328 objc_ivar_memory_management_t
329 _class_getIvarMemoryManagement(Class cls, Ivar ivar)
332 objc_ivar_memory_management_t memoryManagement;
333 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
334 return memoryManagement;
339 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
341 if (!obj || !ivar || obj->isTaggedPointer()) return;
344 objc_ivar_memory_management_t memoryManagement;
345 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
347 if (memoryManagement == objc_ivar_memoryUnknown) {
348 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
349 else memoryManagement = objc_ivar_memoryUnretained;
352 id *location = (id *)((char *)obj + offset);
354 switch (memoryManagement) {
355 case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
356 case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
357 case objc_ivar_memoryUnretained: *location = value; break;
358 case objc_ivar_memoryUnknown: _objc_fatal("impossible");
362 void object_setIvar(id obj, Ivar ivar, id value)
364 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
367 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
369 return _object_setIvar(obj, ivar, value, true /*strong default*/);
373 id object_getIvar(id obj, Ivar ivar)
375 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
378 objc_ivar_memory_management_t memoryManagement;
379 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
381 id *location = (id *)((char *)obj + offset);
383 if (memoryManagement == objc_ivar_memoryWeak) {
384 return objc_loadWeak(location);
392 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
397 if (obj && name && !obj->isTaggedPointer()) {
398 if ((ivar = _class_getVariable(obj->ISA(), name))) {
399 _object_setIvar(obj, ivar, (id)value, assumeStrong);
405 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
407 return _object_setInstanceVariable(obj, name, value, false);
410 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
413 return _object_setInstanceVariable(obj, name, value, true);
417 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
419 if (obj && name && !obj->isTaggedPointer()) {
421 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
422 if (value) *value = (void *)object_getIvar(obj, ivar);
426 if (value) *value = nil;
431 /***********************************************************************
432 * object_cxxDestructFromClass.
433 * Call C++ destructors on obj, starting with cls's
434 * dtor method (if any) followed by superclasses' dtors (if any),
435 * stopping at cls's dtor (if any).
436 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
437 **********************************************************************/
438 static void object_cxxDestructFromClass(id obj, Class cls)
442 // Call cls's dtor first, then superclasses's dtors.
444 for ( ; cls; cls = cls->superclass) {
445 if (!cls->hasCxxDtor()) return;
447 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
448 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
450 _objc_inform("CXX: calling C++ destructors for class %s",
451 cls->nameForLogging());
459 /***********************************************************************
460 * object_cxxDestruct.
461 * Call C++ destructors on obj, if any.
462 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
463 **********************************************************************/
464 void object_cxxDestruct(id obj)
467 if (obj->isTaggedPointer()) return;
468 object_cxxDestructFromClass(obj, obj->ISA());
472 /***********************************************************************
473 * object_cxxConstructFromClass.
474 * Recursively call C++ constructors on obj, starting with base class's
475 * ctor method (if any) followed by subclasses' ctors (if any), stopping
476 * at cls's ctor (if any).
477 * Does not check cls->hasCxxCtor(). The caller should preflight that.
478 * Returns self if construction succeeded.
479 * Returns nil if some constructor threw an exception. The exception is
480 * caught and discarded. Any partial construction is destructed.
481 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
483 * .cxx_construct returns id. This really means:
484 * return self: construction succeeded
485 * return nil: construction failed because a C++ constructor threw an exception
486 **********************************************************************/
488 object_cxxConstructFromClass(id obj, Class cls)
490 assert(cls->hasCxxCtor()); // required for performance, not correctness
495 supercls = cls->superclass;
497 // Call superclasses' ctors first, if any.
498 if (supercls && supercls->hasCxxCtor()) {
499 bool ok = object_cxxConstructFromClass(obj, supercls);
500 if (!ok) return nil; // some superclass's ctor failed - give up
503 // Find this class's ctor, if any.
504 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
505 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
507 // Call this class's ctor.
509 _objc_inform("CXX: calling C++ constructors for class %s",
510 cls->nameForLogging());
512 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
514 // This class's ctor was called and failed.
515 // Call superclasses's dtors to clean up.
516 if (supercls) object_cxxDestructFromClass(obj, supercls);
521 /***********************************************************************
523 * Fix up ARC strong and ARC-style weak variables
524 * after oldObject was memcpy'd to newObject.
525 **********************************************************************/
526 void fixupCopiedIvars(id newObject, id oldObject)
528 for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
529 if (cls->hasAutomaticIvars()) {
530 // Use alignedInstanceStart() because unaligned bytes at the start
531 // of this class's ivars are not represented in the layout bitmap.
532 size_t instanceStart = cls->alignedInstanceStart();
534 const uint8_t *strongLayout = class_getIvarLayout(cls);
536 id *newPtr = (id *)((char*)newObject + instanceStart);
538 while ((byte = *strongLayout++)) {
539 unsigned skips = (byte >> 4);
540 unsigned scans = (byte & 0x0F);
543 // ensure strong references are properly retained.
544 id value = *newPtr++;
545 if (value) objc_retain(value);
550 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
551 // fix up weak references if any.
553 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
555 while ((byte = *weakLayout++)) {
556 unsigned skips = (byte >> 4);
557 unsigned weaks = (byte & 0x0F);
558 newPtr += skips, oldPtr += skips;
560 objc_copyWeak(newPtr, oldPtr);
571 /***********************************************************************
572 * class_getClassMethod. Return the class method for the specified
573 * class and selector.
574 **********************************************************************/
575 Method class_getClassMethod(Class cls, SEL sel)
577 if (!cls || !sel) return nil;
579 return class_getInstanceMethod(cls->getMeta(), sel);
583 /***********************************************************************
584 * class_getInstanceVariable. Return the named instance variable.
585 **********************************************************************/
586 Ivar class_getInstanceVariable(Class cls, const char *name)
588 if (!cls || !name) return nil;
590 return _class_getVariable(cls, name);
594 /***********************************************************************
595 * class_getClassVariable. Return the named class variable.
596 **********************************************************************/
597 Ivar class_getClassVariable(Class cls, const char *name)
599 if (!cls) return nil;
601 return class_getInstanceVariable(cls->ISA(), name);
605 /***********************************************************************
606 * gdb_objc_class_changed
607 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
608 * Does nothing; gdb sets a breakpoint on it.
609 **********************************************************************/
611 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
615 /***********************************************************************
616 * class_respondsToSelector.
617 **********************************************************************/
618 BOOL class_respondsToMethod(Class cls, SEL sel)
620 OBJC_WARN_DEPRECATED;
622 return class_respondsToSelector(cls, sel);
626 BOOL class_respondsToSelector(Class cls, SEL sel)
628 return class_respondsToSelector_inst(cls, sel, nil);
632 // inst is an instance of cls or a subclass thereof, or nil if none is known.
633 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
634 bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
638 if (!sel || !cls) return NO;
640 // Avoids +initialize because it historically did so.
641 // We're not returning a callable IMP anyway.
642 imp = lookUpImpOrNil(cls, sel, inst,
643 NO/*initialize*/, YES/*cache*/, YES/*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(cls, sel, nil,
672 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
674 // Translate forwarding function to C-callable external version
676 return _objc_msgForward;
683 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
685 IMP imp = class_getMethodImplementation(cls, sel);
687 // Translate forwarding function to struct-returning version
688 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
689 return (IMP)&_objc_msgForward_stret;
696 /***********************************************************************
697 * instrumentObjcMessageSends
698 **********************************************************************/
699 // Define this everywhere even if it isn't used to simplify fork() safety code.
700 spinlock_t objcMsgLogLock;
702 #if !SUPPORT_MESSAGE_LOGGING
704 void instrumentObjcMessageSends(BOOL flag)
710 bool objcMsgLogEnabled = false;
711 static int objcMsgLogFD = -1;
713 bool logMessageSend(bool isClassMethod,
714 const char *objectsClass,
715 const char *implementingClass,
720 // Create/open the log file
721 if (objcMsgLogFD == (-1))
723 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
724 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
725 if (objcMsgLogFD < 0) {
726 // no log file - disable logging
727 objcMsgLogEnabled = false;
733 // Make the log entry
734 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
735 isClassMethod ? '+' : '-',
738 sel_getName(selector));
740 objcMsgLogLock.lock();
741 write (objcMsgLogFD, buf, strlen(buf));
742 objcMsgLogLock.unlock();
744 // Tell caller to not cache the method
748 void instrumentObjcMessageSends(BOOL flag)
753 if (objcMsgLogEnabled == enable)
756 // If enabling, flush all method caches so we get some traces
758 _objc_flush_caches(Nil);
761 if (objcMsgLogFD != -1)
762 fsync (objcMsgLogFD);
764 objcMsgLogEnabled = enable;
767 // SUPPORT_MESSAGE_LOGGING
771 Class _calloc_class(size_t size)
773 return (Class) calloc(1, size);
776 Class class_getSuperclass(Class cls)
778 if (!cls) return nil;
779 return cls->superclass;
782 BOOL class_isMetaClass(Class cls)
785 return cls->isMetaClass();
789 size_t class_getInstanceSize(Class cls)
792 return cls->alignedInstanceSize();
796 /***********************************************************************
797 * method_getNumberOfArguments.
798 **********************************************************************/
799 unsigned int method_getNumberOfArguments(Method m)
802 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
806 void method_getReturnType(Method m, char *dst, size_t dst_len)
808 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
812 char * method_copyReturnType(Method m)
814 return encoding_copyReturnType(method_getTypeEncoding(m));
818 void method_getArgumentType(Method m, unsigned int index,
819 char *dst, size_t dst_len)
821 encoding_getArgumentType(method_getTypeEncoding(m),
822 index, dst, dst_len);
826 char * method_copyArgumentType(Method m, unsigned int index)
828 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
832 /***********************************************************************
833 * _objc_constructOrFree
834 * Call C++ constructors, and free() if they fail.
835 * bytes->isa must already be set.
836 * cls must have cxx constructors.
837 * Returns the object, or nil.
838 **********************************************************************/
840 _objc_constructOrFree(id bytes, Class cls)
842 assert(cls->hasCxxCtor()); // for performance, not correctness
844 id obj = object_cxxConstructFromClass(bytes, cls);
845 if (!obj) free(bytes);
851 /***********************************************************************
852 * _class_createInstancesFromZone
853 * Batch-allocating version of _class_createInstanceFromZone.
854 * Attempts to allocate num_requested objects, each with extraBytes.
855 * Returns the number of allocated objects (possibly zero), with
856 * the allocated pointers in *results.
857 **********************************************************************/
859 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
860 id *results, unsigned num_requested)
862 unsigned num_allocated;
865 size_t size = cls->instanceSize(extraBytes);
868 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
869 size, (void**)results, num_requested);
870 for (unsigned i = 0; i < num_allocated; i++) {
871 bzero(results[i], size);
874 // Construct each object, and delete any that fail construction.
877 bool ctor = cls->hasCxxCtor();
878 for (unsigned i = 0; i < num_allocated; i++) {
880 obj->initIsa(cls); // fixme allow nonpointer
881 if (ctor) obj = _objc_constructOrFree(obj, cls);
884 results[i-shift] = obj;
890 return num_allocated - shift;
894 /***********************************************************************
895 * inform_duplicate. Complain about duplicate class implementations.
896 **********************************************************************/
898 inform_duplicate(const char *name, Class oldCls, Class newCls)
901 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
902 ("Class %s is implemented in two different images.", name);
904 const header_info *oldHeader = _headerForClass(oldCls);
905 const header_info *newHeader = _headerForClass(newCls);
906 const char *oldName = oldHeader ? oldHeader->fname() : "??";
907 const char *newName = newHeader ? newHeader->fname() : "??";
909 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
910 ("Class %s is implemented in both %s (%p) and %s (%p). "
911 "One of the two will be used. Which one is undefined.",
912 name, oldName, oldCls, newName, newCls);
918 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
923 if (count == 0) return strdup("");
926 // debug build: sanitize input
927 for (i = 0; i < count; i++) {
928 assert(attrs[i].name);
929 assert(strlen(attrs[i].name) > 0);
930 assert(! strchr(attrs[i].name, ','));
931 assert(! strchr(attrs[i].name, '"'));
932 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
937 for (i = 0; i < count; i++) {
938 if (attrs[i].value) {
939 size_t namelen = strlen(attrs[i].name);
940 if (namelen > 1) namelen += 2; // long names get quoted
941 len += namelen + strlen(attrs[i].value) + 1;
945 result = (char *)malloc(len + 1);
947 for (i = 0; i < count; i++) {
948 if (attrs[i].value) {
949 size_t namelen = strlen(attrs[i].name);
951 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
953 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
958 // remove trailing ',' if any
959 if (s > result) s[-1] = '\0';
965 Property attribute string format:
967 - Comma-separated name-value pairs.
968 - Name and value may not contain ,
969 - Name may not contain "
971 - Name is single char, value follows
972 - OR Name is double-quoted string of 2+ chars, value follows
976 attribute-string: name-value-pair (',' name-value-pair)*
977 name-value-pair: unquoted-name optional-value
978 name-value-pair: quoted-name optional-value
980 quoted-name: '"' [^",]{2,} '"'
981 optional-value: [^,]*
985 iteratePropertyAttributes(const char *attrs,
986 bool (*fn)(unsigned int index,
987 void *ctx1, void *ctx2,
988 const char *name, size_t nlen,
989 const char *value, size_t vlen),
990 void *ctx1, void *ctx2)
992 if (!attrs) return 0;
995 const char *attrsend = attrs + strlen(attrs);
997 unsigned int attrcount = 0;
1000 // Find the next comma-separated attribute
1001 const char *start = attrs;
1002 const char *end = start + strcspn(attrs, ",");
1004 // Move attrs past this attribute and the comma (if any)
1005 attrs = *end ? end+1 : end;
1007 assert(attrs <= attrsend);
1008 assert(start <= attrsend);
1009 assert(end <= attrsend);
1011 // Skip empty attribute
1012 if (start == end) continue;
1014 // Process one non-empty comma-free attribute [start,end)
1015 const char *nameStart;
1016 const char *nameEnd;
1018 assert(start < end);
1020 if (*start != '\"') {
1021 // single-char short name
1027 // double-quoted long name
1028 nameStart = start+1;
1029 nameEnd = nameStart + strcspn(nameStart, "\",");
1030 start++; // leading quote
1031 start += nameEnd - nameStart; // name
1032 if (*start == '\"') start++; // trailing quote, if any
1035 // Process one possibly-empty comma-free attribute value [start,end)
1036 const char *valueStart;
1037 const char *valueEnd;
1039 assert(start <= end);
1044 bool more = (*fn)(attrcount, ctx1, ctx2,
1045 nameStart, nameEnd-nameStart,
1046 valueStart, valueEnd-valueStart);
1056 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1057 const char *name, size_t nlen, const char *value, size_t vlen)
1059 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1060 char **sp = (char **)ctxs;
1062 objc_property_attribute_t *a = *ap;
1066 memcpy(s, name, nlen);
1071 memcpy(s, value, vlen);
1084 objc_property_attribute_t *
1085 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1088 if (outCount) *outCount = 0;
1093 // number of commas plus 1 for the attributes (upper bound)
1094 // plus another attribute for the attribute array terminator
1095 // plus strlen(attrs) for name/value string data (upper bound)
1096 // plus count*2 for the name/value string terminators (upper bound)
1097 unsigned int attrcount = 1;
1099 for (s = attrs; s && *s; s++) {
1100 if (*s == ',') attrcount++;
1104 attrcount * sizeof(objc_property_attribute_t) +
1105 sizeof(objc_property_attribute_t) +
1108 objc_property_attribute_t *result = (objc_property_attribute_t *)
1111 objc_property_attribute_t *ra = result;
1112 char *rs = (char *)(ra+attrcount+1);
1114 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1116 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1117 assert((uint8_t *)rs <= (uint8_t *)result+size);
1119 if (attrcount == 0) {
1124 if (outCount) *outCount = attrcount;
1130 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1131 const char *name, size_t nlen, const char *value, size_t vlen)
1133 const char *query = (char *)ctxa;
1134 char **resultp = (char **)ctxs;
1136 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1137 char *result = (char *)calloc(vlen+1, 1);
1138 memcpy(result, value, vlen);
1139 result[vlen] = '\0';
1147 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1151 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);