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 _class_initialize(_class_getNonMetaClass(cls, nil));
201 return obj->changeIsa(cls);
205 /***********************************************************************
207 **********************************************************************/
208 BOOL object_isClass(id obj)
211 return obj->isClass();
215 /***********************************************************************
216 * object_getClassName.
217 **********************************************************************/
218 const char *object_getClassName(id obj)
220 return class_getName(obj ? obj->getIsa() : nil);
224 /***********************************************************************
225 * object_getMethodImplementation.
226 **********************************************************************/
227 IMP object_getMethodImplementation(id obj, SEL name)
229 Class cls = (obj ? obj->getIsa() : nil);
230 return class_getMethodImplementation(cls, name);
234 /***********************************************************************
235 * object_getMethodImplementation_stret.
236 **********************************************************************/
238 IMP object_getMethodImplementation_stret(id obj, SEL name)
240 Class cls = (obj ? obj->getIsa() : nil);
241 return class_getMethodImplementation_stret(cls, name);
246 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
248 if (!layout) return NO;
250 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
252 while ((byte = *layout++)) {
253 unsigned skips = (byte >> 4);
254 unsigned scans = (byte & 0x0F);
256 if (index > ivar_index) return NO;
258 if (index > ivar_index) return YES;
264 /***********************************************************************
266 * Given an object and an ivar in it, look up some data about that ivar:
268 * - its memory management behavior
269 * The ivar is assumed to be word-aligned and of of object type.
270 **********************************************************************/
272 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
273 objc_ivar_memory_management_t& memoryManagement)
275 ivarOffset = ivar_getOffset(ivar);
277 // Look for ARC variables and ARC-style weak.
279 // Preflight the hasAutomaticIvars check
280 // because _class_getClassForIvar() may need to take locks.
281 bool hasAutomaticIvars = NO;
282 for (Class c = cls; c; c = c->superclass) {
283 if (c->hasAutomaticIvars()) {
284 hasAutomaticIvars = YES;
289 if (hasAutomaticIvars) {
290 Class ivarCls = _class_getClassForIvar(cls, ivar);
291 if (ivarCls->hasAutomaticIvars()) {
292 // ARC layout bitmaps encode the class's own ivars only.
293 // Use alignedInstanceStart() because unaligned bytes at the start
294 // of this class's ivars are not represented in the layout bitmap.
295 ptrdiff_t localOffset =
296 ivarOffset - ivarCls->alignedInstanceStart();
298 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
299 memoryManagement = objc_ivar_memoryStrong;
303 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
304 memoryManagement = objc_ivar_memoryWeak;
308 // Unretained is only for true ARC classes.
309 if (ivarCls->isARC()) {
310 memoryManagement = objc_ivar_memoryUnretained;
316 memoryManagement = objc_ivar_memoryUnknown;
320 /***********************************************************************
321 * _class_getIvarMemoryManagement
322 * SPI for KVO and others to decide what memory management to use
323 * when setting instance variables directly.
324 **********************************************************************/
325 objc_ivar_memory_management_t
326 _class_getIvarMemoryManagement(Class cls, Ivar ivar)
329 objc_ivar_memory_management_t memoryManagement;
330 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
331 return memoryManagement;
336 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
338 if (!obj || !ivar || obj->isTaggedPointer()) return;
341 objc_ivar_memory_management_t memoryManagement;
342 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
344 if (memoryManagement == objc_ivar_memoryUnknown) {
345 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
346 else memoryManagement = objc_ivar_memoryUnretained;
349 id *location = (id *)((char *)obj + offset);
351 switch (memoryManagement) {
352 case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
353 case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
354 case objc_ivar_memoryUnretained: *location = value; break;
355 case objc_ivar_memoryUnknown: _objc_fatal("impossible");
359 void object_setIvar(id obj, Ivar ivar, id value)
361 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
364 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
366 return _object_setIvar(obj, ivar, value, true /*strong default*/);
370 id object_getIvar(id obj, Ivar ivar)
372 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
375 objc_ivar_memory_management_t memoryManagement;
376 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
378 id *location = (id *)((char *)obj + offset);
380 if (memoryManagement == objc_ivar_memoryWeak) {
381 return objc_loadWeak(location);
389 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
394 if (obj && name && !obj->isTaggedPointer()) {
395 if ((ivar = _class_getVariable(obj->ISA(), name))) {
396 _object_setIvar(obj, ivar, (id)value, assumeStrong);
402 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
404 return _object_setInstanceVariable(obj, name, value, false);
407 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
410 return _object_setInstanceVariable(obj, name, value, true);
414 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
416 if (obj && name && !obj->isTaggedPointer()) {
418 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
419 if (value) *value = (void *)object_getIvar(obj, ivar);
423 if (value) *value = nil;
428 /***********************************************************************
429 * object_cxxDestructFromClass.
430 * Call C++ destructors on obj, starting with cls's
431 * dtor method (if any) followed by superclasses' dtors (if any),
432 * stopping at cls's dtor (if any).
433 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
434 **********************************************************************/
435 static void object_cxxDestructFromClass(id obj, Class cls)
439 // Call cls's dtor first, then superclasses's dtors.
441 for ( ; cls; cls = cls->superclass) {
442 if (!cls->hasCxxDtor()) return;
444 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
445 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
447 _objc_inform("CXX: calling C++ destructors for class %s",
448 cls->nameForLogging());
456 /***********************************************************************
457 * object_cxxDestruct.
458 * Call C++ destructors on obj, if any.
459 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
460 **********************************************************************/
461 void object_cxxDestruct(id obj)
464 if (obj->isTaggedPointer()) return;
465 object_cxxDestructFromClass(obj, obj->ISA());
469 /***********************************************************************
470 * object_cxxConstructFromClass.
471 * Recursively call C++ constructors on obj, starting with base class's
472 * ctor method (if any) followed by subclasses' ctors (if any), stopping
473 * at cls's ctor (if any).
474 * Does not check cls->hasCxxCtor(). The caller should preflight that.
475 * Returns self if construction succeeded.
476 * Returns nil if some constructor threw an exception. The exception is
477 * caught and discarded. Any partial construction is destructed.
478 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
480 * .cxx_construct returns id. This really means:
481 * return self: construction succeeded
482 * return nil: construction failed because a C++ constructor threw an exception
483 **********************************************************************/
485 object_cxxConstructFromClass(id obj, Class cls)
487 assert(cls->hasCxxCtor()); // required for performance, not correctness
492 supercls = cls->superclass;
494 // Call superclasses' ctors first, if any.
495 if (supercls && supercls->hasCxxCtor()) {
496 bool ok = object_cxxConstructFromClass(obj, supercls);
497 if (!ok) return nil; // some superclass's ctor failed - give up
500 // Find this class's ctor, if any.
501 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
502 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
504 // Call this class's ctor.
506 _objc_inform("CXX: calling C++ constructors for class %s",
507 cls->nameForLogging());
509 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
511 // This class's ctor was called and failed.
512 // Call superclasses's dtors to clean up.
513 if (supercls) object_cxxDestructFromClass(obj, supercls);
518 /***********************************************************************
520 * Fix up ARC strong and ARC-style weak variables
521 * after oldObject was memcpy'd to newObject.
522 **********************************************************************/
523 void fixupCopiedIvars(id newObject, id oldObject)
525 for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
526 if (cls->hasAutomaticIvars()) {
527 // Use alignedInstanceStart() because unaligned bytes at the start
528 // of this class's ivars are not represented in the layout bitmap.
529 size_t instanceStart = cls->alignedInstanceStart();
531 const uint8_t *strongLayout = class_getIvarLayout(cls);
533 id *newPtr = (id *)((char*)newObject + instanceStart);
535 while ((byte = *strongLayout++)) {
536 unsigned skips = (byte >> 4);
537 unsigned scans = (byte & 0x0F);
540 // ensure strong references are properly retained.
541 id value = *newPtr++;
542 if (value) objc_retain(value);
547 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
548 // fix up weak references if any.
550 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
552 while ((byte = *weakLayout++)) {
553 unsigned skips = (byte >> 4);
554 unsigned weaks = (byte & 0x0F);
555 newPtr += skips, oldPtr += skips;
557 objc_copyWeak(newPtr, oldPtr);
567 /***********************************************************************
568 * _class_resolveClassMethod
569 * Call +resolveClassMethod, looking for a method to be added to class cls.
570 * cls should be a metaclass.
571 * Does not check if the method already exists.
572 **********************************************************************/
573 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
575 assert(cls->isMetaClass());
577 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
578 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
580 // Resolver not implemented.
584 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
585 bool resolved = msg(_class_getNonMetaClass(cls, inst),
586 SEL_resolveClassMethod, sel);
588 // Cache the result (good or bad) so the resolver doesn't fire next time.
589 // +resolveClassMethod adds to self->ISA() a.k.a. cls
590 IMP imp = lookUpImpOrNil(cls, sel, inst,
591 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
593 if (resolved && PrintResolving) {
595 _objc_inform("RESOLVE: method %c[%s %s] "
596 "dynamically resolved to %p",
597 cls->isMetaClass() ? '+' : '-',
598 cls->nameForLogging(), sel_getName(sel), imp);
601 // Method resolver didn't add anything?
602 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
603 ", but no new implementation of %c[%s %s] was found",
604 cls->nameForLogging(), sel_getName(sel),
605 cls->isMetaClass() ? '+' : '-',
606 cls->nameForLogging(), sel_getName(sel));
612 /***********************************************************************
613 * _class_resolveInstanceMethod
614 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
615 * cls may be a metaclass or a non-meta class.
616 * Does not check if the method already exists.
617 **********************************************************************/
618 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
620 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
621 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
623 // Resolver not implemented.
627 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
628 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
630 // Cache the result (good or bad) so the resolver doesn't fire next time.
631 // +resolveInstanceMethod adds to self a.k.a. cls
632 IMP imp = lookUpImpOrNil(cls, sel, inst,
633 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
635 if (resolved && PrintResolving) {
637 _objc_inform("RESOLVE: method %c[%s %s] "
638 "dynamically resolved to %p",
639 cls->isMetaClass() ? '+' : '-',
640 cls->nameForLogging(), sel_getName(sel), imp);
643 // Method resolver didn't add anything?
644 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
645 ", but no new implementation of %c[%s %s] was found",
646 cls->nameForLogging(), sel_getName(sel),
647 cls->isMetaClass() ? '+' : '-',
648 cls->nameForLogging(), sel_getName(sel));
654 /***********************************************************************
655 * _class_resolveMethod
656 * Call +resolveClassMethod or +resolveInstanceMethod.
657 * Returns nothing; any result would be potentially out-of-date already.
658 * Does not check if the method already exists.
659 **********************************************************************/
660 void _class_resolveMethod(Class cls, SEL sel, id inst)
662 if (! cls->isMetaClass()) {
663 // try [cls resolveInstanceMethod:sel]
664 _class_resolveInstanceMethod(cls, sel, inst);
667 // try [nonMetaClass resolveClassMethod:sel]
668 // and [cls resolveInstanceMethod:sel]
669 _class_resolveClassMethod(cls, sel, inst);
670 if (!lookUpImpOrNil(cls, sel, inst,
671 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
673 _class_resolveInstanceMethod(cls, sel, inst);
679 /***********************************************************************
680 * class_getClassMethod. Return the class method for the specified
681 * class and selector.
682 **********************************************************************/
683 Method class_getClassMethod(Class cls, SEL sel)
685 if (!cls || !sel) return nil;
687 return class_getInstanceMethod(cls->getMeta(), sel);
691 /***********************************************************************
692 * class_getInstanceVariable. Return the named instance variable.
693 **********************************************************************/
694 Ivar class_getInstanceVariable(Class cls, const char *name)
696 if (!cls || !name) return nil;
698 return _class_getVariable(cls, name);
702 /***********************************************************************
703 * class_getClassVariable. Return the named class variable.
704 **********************************************************************/
705 Ivar class_getClassVariable(Class cls, const char *name)
707 if (!cls) return nil;
709 return class_getInstanceVariable(cls->ISA(), name);
713 /***********************************************************************
714 * gdb_objc_class_changed
715 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
716 * Does nothing; gdb sets a breakpoint on it.
717 **********************************************************************/
719 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
723 /***********************************************************************
724 * class_respondsToSelector.
725 **********************************************************************/
726 BOOL class_respondsToMethod(Class cls, SEL sel)
728 OBJC_WARN_DEPRECATED;
730 return class_respondsToSelector(cls, sel);
734 BOOL class_respondsToSelector(Class cls, SEL sel)
736 return class_respondsToSelector_inst(cls, sel, nil);
740 // inst is an instance of cls or a subclass thereof, or nil if none is known.
741 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
742 bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
746 if (!sel || !cls) return NO;
748 // Avoids +initialize because it historically did so.
749 // We're not returning a callable IMP anyway.
750 imp = lookUpImpOrNil(cls, sel, inst,
751 NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
756 /***********************************************************************
757 * class_getMethodImplementation.
758 * Returns the IMP that would be invoked if [obj sel] were sent,
759 * where obj is an instance of class cls.
760 **********************************************************************/
761 IMP class_lookupMethod(Class cls, SEL sel)
763 OBJC_WARN_DEPRECATED;
765 // No one responds to zero!
767 __objc_error(cls, "invalid selector (null)");
770 return class_getMethodImplementation(cls, sel);
773 IMP class_getMethodImplementation(Class cls, SEL sel)
777 if (!cls || !sel) return nil;
779 imp = lookUpImpOrNil(cls, sel, nil,
780 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
782 // Translate forwarding function to C-callable external version
784 return _objc_msgForward;
791 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
793 IMP imp = class_getMethodImplementation(cls, sel);
795 // Translate forwarding function to struct-returning version
796 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
797 return (IMP)&_objc_msgForward_stret;
804 /***********************************************************************
805 * instrumentObjcMessageSends
806 **********************************************************************/
807 // Define this everywhere even if it isn't used to simplify fork() safety code.
808 spinlock_t objcMsgLogLock;
810 #if !SUPPORT_MESSAGE_LOGGING
812 void instrumentObjcMessageSends(BOOL flag)
818 bool objcMsgLogEnabled = false;
819 static int objcMsgLogFD = -1;
821 bool logMessageSend(bool isClassMethod,
822 const char *objectsClass,
823 const char *implementingClass,
828 // Create/open the log file
829 if (objcMsgLogFD == (-1))
831 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
832 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
833 if (objcMsgLogFD < 0) {
834 // no log file - disable logging
835 objcMsgLogEnabled = false;
841 // Make the log entry
842 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
843 isClassMethod ? '+' : '-',
846 sel_getName(selector));
848 objcMsgLogLock.lock();
849 write (objcMsgLogFD, buf, strlen(buf));
850 objcMsgLogLock.unlock();
852 // Tell caller to not cache the method
856 void instrumentObjcMessageSends(BOOL flag)
861 if (objcMsgLogEnabled == enable)
864 // If enabling, flush all method caches so we get some traces
866 _objc_flush_caches(Nil);
869 if (objcMsgLogFD != -1)
870 fsync (objcMsgLogFD);
872 objcMsgLogEnabled = enable;
875 // SUPPORT_MESSAGE_LOGGING
879 Class _calloc_class(size_t size)
881 return (Class) calloc(1, size);
884 Class class_getSuperclass(Class cls)
886 if (!cls) return nil;
887 return cls->superclass;
890 BOOL class_isMetaClass(Class cls)
893 return cls->isMetaClass();
897 size_t class_getInstanceSize(Class cls)
900 return cls->alignedInstanceSize();
904 /***********************************************************************
905 * method_getNumberOfArguments.
906 **********************************************************************/
907 unsigned int method_getNumberOfArguments(Method m)
910 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
914 void method_getReturnType(Method m, char *dst, size_t dst_len)
916 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
920 char * method_copyReturnType(Method m)
922 return encoding_copyReturnType(method_getTypeEncoding(m));
926 void method_getArgumentType(Method m, unsigned int index,
927 char *dst, size_t dst_len)
929 encoding_getArgumentType(method_getTypeEncoding(m),
930 index, dst, dst_len);
934 char * method_copyArgumentType(Method m, unsigned int index)
936 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
940 /***********************************************************************
941 * _objc_constructOrFree
942 * Call C++ constructors, and free() if they fail.
943 * bytes->isa must already be set.
944 * cls must have cxx constructors.
945 * Returns the object, or nil.
946 **********************************************************************/
948 _objc_constructOrFree(id bytes, Class cls)
950 assert(cls->hasCxxCtor()); // for performance, not correctness
952 id obj = object_cxxConstructFromClass(bytes, cls);
953 if (!obj) free(bytes);
959 /***********************************************************************
960 * _class_createInstancesFromZone
961 * Batch-allocating version of _class_createInstanceFromZone.
962 * Attempts to allocate num_requested objects, each with extraBytes.
963 * Returns the number of allocated objects (possibly zero), with
964 * the allocated pointers in *results.
965 **********************************************************************/
967 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
968 id *results, unsigned num_requested)
970 unsigned num_allocated;
973 size_t size = cls->instanceSize(extraBytes);
976 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
977 size, (void**)results, num_requested);
978 for (unsigned i = 0; i < num_allocated; i++) {
979 bzero(results[i], size);
982 // Construct each object, and delete any that fail construction.
985 bool ctor = cls->hasCxxCtor();
986 for (unsigned i = 0; i < num_allocated; i++) {
988 obj->initIsa(cls); // fixme allow nonpointer
989 if (ctor) obj = _objc_constructOrFree(obj, cls);
992 results[i-shift] = obj;
998 return num_allocated - shift;
1002 /***********************************************************************
1003 * inform_duplicate. Complain about duplicate class implementations.
1004 **********************************************************************/
1006 inform_duplicate(const char *name, Class oldCls, Class newCls)
1009 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1010 ("Class %s is implemented in two different images.", name);
1012 const header_info *oldHeader = _headerForClass(oldCls);
1013 const header_info *newHeader = _headerForClass(newCls);
1014 const char *oldName = oldHeader ? oldHeader->fname() : "??";
1015 const char *newName = newHeader ? newHeader->fname() : "??";
1017 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1018 ("Class %s is implemented in both %s (%p) and %s (%p). "
1019 "One of the two will be used. Which one is undefined.",
1020 name, oldName, oldCls, newName, newCls);
1026 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
1031 if (count == 0) return strdup("");
1034 // debug build: sanitize input
1035 for (i = 0; i < count; i++) {
1036 assert(attrs[i].name);
1037 assert(strlen(attrs[i].name) > 0);
1038 assert(! strchr(attrs[i].name, ','));
1039 assert(! strchr(attrs[i].name, '"'));
1040 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
1045 for (i = 0; i < count; i++) {
1046 if (attrs[i].value) {
1047 size_t namelen = strlen(attrs[i].name);
1048 if (namelen > 1) namelen += 2; // long names get quoted
1049 len += namelen + strlen(attrs[i].value) + 1;
1053 result = (char *)malloc(len + 1);
1055 for (i = 0; i < count; i++) {
1056 if (attrs[i].value) {
1057 size_t namelen = strlen(attrs[i].name);
1059 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
1061 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
1066 // remove trailing ',' if any
1067 if (s > result) s[-1] = '\0';
1073 Property attribute string format:
1075 - Comma-separated name-value pairs.
1076 - Name and value may not contain ,
1077 - Name may not contain "
1078 - Value may be empty
1079 - Name is single char, value follows
1080 - OR Name is double-quoted string of 2+ chars, value follows
1083 attribute-string: \0
1084 attribute-string: name-value-pair (',' name-value-pair)*
1085 name-value-pair: unquoted-name optional-value
1086 name-value-pair: quoted-name optional-value
1087 unquoted-name: [^",]
1088 quoted-name: '"' [^",]{2,} '"'
1089 optional-value: [^,]*
1093 iteratePropertyAttributes(const char *attrs,
1094 bool (*fn)(unsigned int index,
1095 void *ctx1, void *ctx2,
1096 const char *name, size_t nlen,
1097 const char *value, size_t vlen),
1098 void *ctx1, void *ctx2)
1100 if (!attrs) return 0;
1103 const char *attrsend = attrs + strlen(attrs);
1105 unsigned int attrcount = 0;
1108 // Find the next comma-separated attribute
1109 const char *start = attrs;
1110 const char *end = start + strcspn(attrs, ",");
1112 // Move attrs past this attribute and the comma (if any)
1113 attrs = *end ? end+1 : end;
1115 assert(attrs <= attrsend);
1116 assert(start <= attrsend);
1117 assert(end <= attrsend);
1119 // Skip empty attribute
1120 if (start == end) continue;
1122 // Process one non-empty comma-free attribute [start,end)
1123 const char *nameStart;
1124 const char *nameEnd;
1126 assert(start < end);
1128 if (*start != '\"') {
1129 // single-char short name
1135 // double-quoted long name
1136 nameStart = start+1;
1137 nameEnd = nameStart + strcspn(nameStart, "\",");
1138 start++; // leading quote
1139 start += nameEnd - nameStart; // name
1140 if (*start == '\"') start++; // trailing quote, if any
1143 // Process one possibly-empty comma-free attribute value [start,end)
1144 const char *valueStart;
1145 const char *valueEnd;
1147 assert(start <= end);
1152 bool more = (*fn)(attrcount, ctx1, ctx2,
1153 nameStart, nameEnd-nameStart,
1154 valueStart, valueEnd-valueStart);
1164 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1165 const char *name, size_t nlen, const char *value, size_t vlen)
1167 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1168 char **sp = (char **)ctxs;
1170 objc_property_attribute_t *a = *ap;
1174 memcpy(s, name, nlen);
1179 memcpy(s, value, vlen);
1192 objc_property_attribute_t *
1193 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1196 if (outCount) *outCount = 0;
1201 // number of commas plus 1 for the attributes (upper bound)
1202 // plus another attribute for the attribute array terminator
1203 // plus strlen(attrs) for name/value string data (upper bound)
1204 // plus count*2 for the name/value string terminators (upper bound)
1205 unsigned int attrcount = 1;
1207 for (s = attrs; s && *s; s++) {
1208 if (*s == ',') attrcount++;
1212 attrcount * sizeof(objc_property_attribute_t) +
1213 sizeof(objc_property_attribute_t) +
1216 objc_property_attribute_t *result = (objc_property_attribute_t *)
1219 objc_property_attribute_t *ra = result;
1220 char *rs = (char *)(ra+attrcount+1);
1222 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1224 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1225 assert((uint8_t *)rs <= (uint8_t *)result+size);
1227 if (attrcount == 0) {
1232 if (outCount) *outCount = attrcount;
1238 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1239 const char *name, size_t nlen, const char *value, size_t vlen)
1241 const char *query = (char *)ctxa;
1242 char **resultp = (char **)ctxs;
1244 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1245 char *result = (char *)calloc(vlen+1, 1);
1246 memcpy(result, value, vlen);
1247 result[vlen] = '\0';
1255 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1259 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);