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>
164 /* overriding the default object allocation and error handling routines */
166 OBJC_EXPORT id (*_alloc)(Class, size_t);
167 OBJC_EXPORT id (*_copy)(id, size_t);
168 OBJC_EXPORT id (*_realloc)(id, size_t);
169 OBJC_EXPORT id (*_dealloc)(id);
170 OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *);
171 OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *);
172 OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *);
175 /***********************************************************************
176 * Information about multi-thread support:
178 * Since we do not lock many operations which walk the superclass, method
179 * and ivar chains, these chains must remain intact once a class is published
180 * by inserting it into the class hashtable. All modifications must be
181 * atomic so that someone walking these chains will always geta valid
183 ***********************************************************************/
187 /***********************************************************************
189 * Locking: None. If you add locking, tell gdb (rdar://7516456).
190 **********************************************************************/
191 Class object_getClass(id obj)
193 if (obj) return obj->getIsa();
198 /***********************************************************************
200 **********************************************************************/
201 Class object_setClass(id obj, Class cls)
203 if (!obj) return nil;
205 // Prevent a deadlock between the weak reference machinery
206 // and the +initialize machinery by ensuring that no
207 // weakly-referenced object has an un-+initialized isa.
208 // Unresolved future classes are not so protected.
209 if (!cls->isFuture() && !cls->isInitialized()) {
210 _class_initialize(_class_getNonMetaClass(cls, nil));
213 return obj->changeIsa(cls);
217 /***********************************************************************
219 **********************************************************************/
220 BOOL object_isClass(id obj)
223 return obj->isClass();
227 /***********************************************************************
228 * object_getClassName.
229 **********************************************************************/
230 const char *object_getClassName(id obj)
232 return class_getName(obj ? obj->getIsa() : nil);
236 /***********************************************************************
237 * object_getMethodImplementation.
238 **********************************************************************/
239 IMP object_getMethodImplementation(id obj, SEL name)
241 Class cls = (obj ? obj->getIsa() : nil);
242 return class_getMethodImplementation(cls, name);
246 /***********************************************************************
247 * object_getMethodImplementation_stret.
248 **********************************************************************/
250 IMP object_getMethodImplementation_stret(id obj, SEL name)
252 Class cls = (obj ? obj->getIsa() : nil);
253 return class_getMethodImplementation_stret(cls, name);
258 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
260 if (!layout) return NO;
262 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
264 while ((byte = *layout++)) {
265 unsigned skips = (byte >> 4);
266 unsigned scans = (byte & 0x0F);
268 if (index > ivar_index) return NO;
270 if (index > ivar_index) return YES;
276 /***********************************************************************
278 * Given an object and an ivar in it, look up some data about that ivar:
280 * - its memory management behavior
281 * The ivar is assumed to be word-aligned and of of object type.
282 **********************************************************************/
284 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
285 objc_ivar_memory_management_t& memoryManagement)
287 ivarOffset = ivar_getOffset(ivar);
289 // Look for ARC variables and ARC-style weak.
291 // Preflight the hasAutomaticIvars check
292 // because _class_getClassForIvar() may need to take locks.
293 bool hasAutomaticIvars = NO;
294 for (Class c = cls; c; c = c->superclass) {
295 if (c->hasAutomaticIvars()) {
296 hasAutomaticIvars = YES;
301 if (hasAutomaticIvars) {
302 Class ivarCls = _class_getClassForIvar(cls, ivar);
303 if (ivarCls->hasAutomaticIvars()) {
304 // ARC layout bitmaps encode the class's own ivars only.
305 // Use alignedInstanceStart() because unaligned bytes at the start
306 // of this class's ivars are not represented in the layout bitmap.
307 ptrdiff_t localOffset =
308 ivarOffset - ivarCls->alignedInstanceStart();
310 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
311 memoryManagement = objc_ivar_memoryStrong;
315 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
316 memoryManagement = objc_ivar_memoryWeak;
320 // Unretained is only for true ARC classes.
321 if (ivarCls->isARC()) {
322 memoryManagement = objc_ivar_memoryUnretained;
328 memoryManagement = objc_ivar_memoryUnknown;
332 /***********************************************************************
333 * _class_getIvarMemoryManagement
334 * SPI for KVO and others to decide what memory management to use
335 * when setting instance variables directly.
336 **********************************************************************/
337 objc_ivar_memory_management_t
338 _class_getIvarMemoryManagement(Class cls, Ivar ivar)
341 objc_ivar_memory_management_t memoryManagement;
342 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
343 return memoryManagement;
348 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
350 if (!obj || !ivar || obj->isTaggedPointer()) return;
353 objc_ivar_memory_management_t memoryManagement;
354 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
356 if (memoryManagement == objc_ivar_memoryUnknown) {
357 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
358 else memoryManagement = objc_ivar_memoryUnretained;
361 id *location = (id *)((char *)obj + offset);
363 switch (memoryManagement) {
364 case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
365 case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
366 case objc_ivar_memoryUnretained: *location = value; break;
367 case objc_ivar_memoryUnknown: _objc_fatal("impossible");
371 void object_setIvar(id obj, Ivar ivar, id value)
373 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
376 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
378 return _object_setIvar(obj, ivar, value, true /*strong default*/);
382 id object_getIvar(id obj, Ivar ivar)
384 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
387 objc_ivar_memory_management_t memoryManagement;
388 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
390 id *location = (id *)((char *)obj + offset);
392 if (memoryManagement == objc_ivar_memoryWeak) {
393 return objc_loadWeak(location);
401 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
406 if (obj && name && !obj->isTaggedPointer()) {
407 if ((ivar = _class_getVariable(obj->ISA(), name))) {
408 _object_setIvar(obj, ivar, (id)value, assumeStrong);
414 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
416 return _object_setInstanceVariable(obj, name, value, false);
419 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
422 return _object_setInstanceVariable(obj, name, value, true);
426 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
428 if (obj && name && !obj->isTaggedPointer()) {
430 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
431 if (value) *value = (void *)object_getIvar(obj, ivar);
435 if (value) *value = nil;
440 /***********************************************************************
441 * object_cxxDestructFromClass.
442 * Call C++ destructors on obj, starting with cls's
443 * dtor method (if any) followed by superclasses' dtors (if any),
444 * stopping at cls's dtor (if any).
445 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
446 **********************************************************************/
447 static void object_cxxDestructFromClass(id obj, Class cls)
451 // Call cls's dtor first, then superclasses's dtors.
453 for ( ; cls; cls = cls->superclass) {
454 if (!cls->hasCxxDtor()) return;
456 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
457 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
459 _objc_inform("CXX: calling C++ destructors for class %s",
460 cls->nameForLogging());
468 /***********************************************************************
469 * object_cxxDestruct.
470 * Call C++ destructors on obj, if any.
471 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
472 **********************************************************************/
473 void object_cxxDestruct(id obj)
476 if (obj->isTaggedPointer()) return;
477 object_cxxDestructFromClass(obj, obj->ISA());
481 /***********************************************************************
482 * object_cxxConstructFromClass.
483 * Recursively call C++ constructors on obj, starting with base class's
484 * ctor method (if any) followed by subclasses' ctors (if any), stopping
485 * at cls's ctor (if any).
486 * Does not check cls->hasCxxCtor(). The caller should preflight that.
487 * Returns self if construction succeeded.
488 * Returns nil if some constructor threw an exception. The exception is
489 * caught and discarded. Any partial construction is destructed.
490 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
492 * .cxx_construct returns id. This really means:
493 * return self: construction succeeded
494 * return nil: construction failed because a C++ constructor threw an exception
495 **********************************************************************/
497 object_cxxConstructFromClass(id obj, Class cls)
499 assert(cls->hasCxxCtor()); // required for performance, not correctness
504 supercls = cls->superclass;
506 // Call superclasses' ctors first, if any.
507 if (supercls && supercls->hasCxxCtor()) {
508 bool ok = object_cxxConstructFromClass(obj, supercls);
509 if (!ok) return nil; // some superclass's ctor failed - give up
512 // Find this class's ctor, if any.
513 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
514 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
516 // Call this class's ctor.
518 _objc_inform("CXX: calling C++ constructors for class %s",
519 cls->nameForLogging());
521 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
523 // This class's ctor was called and failed.
524 // Call superclasses's dtors to clean up.
525 if (supercls) object_cxxDestructFromClass(obj, supercls);
530 /***********************************************************************
532 * Fix up ARC strong and ARC-style weak variables
533 * after oldObject was memcpy'd to newObject.
534 **********************************************************************/
535 void fixupCopiedIvars(id newObject, id oldObject)
537 for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
538 if (cls->hasAutomaticIvars()) {
539 // Use alignedInstanceStart() because unaligned bytes at the start
540 // of this class's ivars are not represented in the layout bitmap.
541 size_t instanceStart = cls->alignedInstanceStart();
543 const uint8_t *strongLayout = class_getIvarLayout(cls);
545 id *newPtr = (id *)((char*)newObject + instanceStart);
547 while ((byte = *strongLayout++)) {
548 unsigned skips = (byte >> 4);
549 unsigned scans = (byte & 0x0F);
552 // ensure strong references are properly retained.
553 id value = *newPtr++;
554 if (value) objc_retain(value);
559 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
560 // fix up weak references if any.
562 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
564 while ((byte = *weakLayout++)) {
565 unsigned skips = (byte >> 4);
566 unsigned weaks = (byte & 0x0F);
567 newPtr += skips, oldPtr += skips;
569 objc_copyWeak(newPtr, oldPtr);
579 /***********************************************************************
580 * _class_resolveClassMethod
581 * Call +resolveClassMethod, looking for a method to be added to class cls.
582 * cls should be a metaclass.
583 * Does not check if the method already exists.
584 **********************************************************************/
585 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
587 assert(cls->isMetaClass());
589 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
590 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
592 // Resolver not implemented.
596 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
597 bool resolved = msg(_class_getNonMetaClass(cls, inst),
598 SEL_resolveClassMethod, sel);
600 // Cache the result (good or bad) so the resolver doesn't fire next time.
601 // +resolveClassMethod adds to self->ISA() a.k.a. cls
602 IMP imp = lookUpImpOrNil(cls, sel, inst,
603 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
605 if (resolved && PrintResolving) {
607 _objc_inform("RESOLVE: method %c[%s %s] "
608 "dynamically resolved to %p",
609 cls->isMetaClass() ? '+' : '-',
610 cls->nameForLogging(), sel_getName(sel), imp);
613 // Method resolver didn't add anything?
614 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
615 ", but no new implementation of %c[%s %s] was found",
616 cls->nameForLogging(), sel_getName(sel),
617 cls->isMetaClass() ? '+' : '-',
618 cls->nameForLogging(), sel_getName(sel));
624 /***********************************************************************
625 * _class_resolveInstanceMethod
626 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
627 * cls may be a metaclass or a non-meta class.
628 * Does not check if the method already exists.
629 **********************************************************************/
630 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
632 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
633 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
635 // Resolver not implemented.
639 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
640 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
642 // Cache the result (good or bad) so the resolver doesn't fire next time.
643 // +resolveInstanceMethod adds to self a.k.a. cls
644 IMP imp = lookUpImpOrNil(cls, sel, inst,
645 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
647 if (resolved && PrintResolving) {
649 _objc_inform("RESOLVE: method %c[%s %s] "
650 "dynamically resolved to %p",
651 cls->isMetaClass() ? '+' : '-',
652 cls->nameForLogging(), sel_getName(sel), imp);
655 // Method resolver didn't add anything?
656 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
657 ", but no new implementation of %c[%s %s] was found",
658 cls->nameForLogging(), sel_getName(sel),
659 cls->isMetaClass() ? '+' : '-',
660 cls->nameForLogging(), sel_getName(sel));
666 /***********************************************************************
667 * _class_resolveMethod
668 * Call +resolveClassMethod or +resolveInstanceMethod.
669 * Returns nothing; any result would be potentially out-of-date already.
670 * Does not check if the method already exists.
671 **********************************************************************/
672 void _class_resolveMethod(Class cls, SEL sel, id inst)
674 if (! cls->isMetaClass()) {
675 // try [cls resolveInstanceMethod:sel]
676 _class_resolveInstanceMethod(cls, sel, inst);
679 // try [nonMetaClass resolveClassMethod:sel]
680 // and [cls resolveInstanceMethod:sel]
681 _class_resolveClassMethod(cls, sel, inst);
682 if (!lookUpImpOrNil(cls, sel, inst,
683 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
685 _class_resolveInstanceMethod(cls, sel, inst);
691 /***********************************************************************
692 * class_getClassMethod. Return the class method for the specified
693 * class and selector.
694 **********************************************************************/
695 Method class_getClassMethod(Class cls, SEL sel)
697 if (!cls || !sel) return nil;
699 return class_getInstanceMethod(cls->getMeta(), sel);
703 /***********************************************************************
704 * class_getInstanceVariable. Return the named instance variable.
705 **********************************************************************/
706 Ivar class_getInstanceVariable(Class cls, const char *name)
708 if (!cls || !name) return nil;
710 return _class_getVariable(cls, name);
714 /***********************************************************************
715 * class_getClassVariable. Return the named class variable.
716 **********************************************************************/
717 Ivar class_getClassVariable(Class cls, const char *name)
719 if (!cls) return nil;
721 return class_getInstanceVariable(cls->ISA(), name);
725 /***********************************************************************
726 * gdb_objc_class_changed
727 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
728 * Does nothing; gdb sets a breakpoint on it.
729 **********************************************************************/
731 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
735 /***********************************************************************
736 * class_respondsToSelector.
737 **********************************************************************/
738 BOOL class_respondsToMethod(Class cls, SEL sel)
740 OBJC_WARN_DEPRECATED;
742 return class_respondsToSelector(cls, sel);
746 BOOL class_respondsToSelector(Class cls, SEL sel)
748 return class_respondsToSelector_inst(cls, sel, nil);
752 // inst is an instance of cls or a subclass thereof, or nil if none is known.
753 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
754 bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
758 if (!sel || !cls) return NO;
760 // Avoids +initialize because it historically did so.
761 // We're not returning a callable IMP anyway.
762 imp = lookUpImpOrNil(cls, sel, inst,
763 NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
768 /***********************************************************************
769 * class_getMethodImplementation.
770 * Returns the IMP that would be invoked if [obj sel] were sent,
771 * where obj is an instance of class cls.
772 **********************************************************************/
773 IMP class_lookupMethod(Class cls, SEL sel)
775 OBJC_WARN_DEPRECATED;
777 // No one responds to zero!
779 __objc_error(cls, "invalid selector (null)");
782 return class_getMethodImplementation(cls, sel);
785 IMP class_getMethodImplementation(Class cls, SEL sel)
789 if (!cls || !sel) return nil;
791 imp = lookUpImpOrNil(cls, sel, nil,
792 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
794 // Translate forwarding function to C-callable external version
796 return _objc_msgForward;
803 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
805 IMP imp = class_getMethodImplementation(cls, sel);
807 // Translate forwarding function to struct-returning version
808 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
809 return (IMP)&_objc_msgForward_stret;
816 /***********************************************************************
817 * instrumentObjcMessageSends
818 **********************************************************************/
819 // Define this everywhere even if it isn't used to simplify fork() safety code.
820 spinlock_t objcMsgLogLock;
822 #if !SUPPORT_MESSAGE_LOGGING
824 void instrumentObjcMessageSends(BOOL flag)
830 bool objcMsgLogEnabled = false;
831 static int objcMsgLogFD = -1;
833 bool logMessageSend(bool isClassMethod,
834 const char *objectsClass,
835 const char *implementingClass,
840 // Create/open the log file
841 if (objcMsgLogFD == (-1))
843 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
844 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
845 if (objcMsgLogFD < 0) {
846 // no log file - disable logging
847 objcMsgLogEnabled = false;
853 // Make the log entry
854 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
855 isClassMethod ? '+' : '-',
858 sel_getName(selector));
860 objcMsgLogLock.lock();
861 write (objcMsgLogFD, buf, strlen(buf));
862 objcMsgLogLock.unlock();
864 // Tell caller to not cache the method
868 void instrumentObjcMessageSends(BOOL flag)
873 if (objcMsgLogEnabled == enable)
876 // If enabling, flush all method caches so we get some traces
878 _objc_flush_caches(Nil);
881 if (objcMsgLogFD != -1)
882 fsync (objcMsgLogFD);
884 objcMsgLogEnabled = enable;
887 // SUPPORT_MESSAGE_LOGGING
891 Class _calloc_class(size_t size)
893 return (Class) calloc(1, size);
896 Class class_getSuperclass(Class cls)
898 if (!cls) return nil;
899 return cls->superclass;
902 BOOL class_isMetaClass(Class cls)
905 return cls->isMetaClass();
909 size_t class_getInstanceSize(Class cls)
912 return cls->alignedInstanceSize();
916 /***********************************************************************
917 * method_getNumberOfArguments.
918 **********************************************************************/
919 unsigned int method_getNumberOfArguments(Method m)
922 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
926 void method_getReturnType(Method m, char *dst, size_t dst_len)
928 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
932 char * method_copyReturnType(Method m)
934 return encoding_copyReturnType(method_getTypeEncoding(m));
938 void method_getArgumentType(Method m, unsigned int index,
939 char *dst, size_t dst_len)
941 encoding_getArgumentType(method_getTypeEncoding(m),
942 index, dst, dst_len);
946 char * method_copyArgumentType(Method m, unsigned int index)
948 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
952 /***********************************************************************
953 * _objc_constructOrFree
954 * Call C++ constructors, and free() if they fail.
955 * bytes->isa must already be set.
956 * cls must have cxx constructors.
957 * Returns the object, or nil.
958 **********************************************************************/
960 _objc_constructOrFree(id bytes, Class cls)
962 assert(cls->hasCxxCtor()); // for performance, not correctness
964 id obj = object_cxxConstructFromClass(bytes, cls);
965 if (!obj) free(bytes);
971 /***********************************************************************
972 * _class_createInstancesFromZone
973 * Batch-allocating version of _class_createInstanceFromZone.
974 * Attempts to allocate num_requested objects, each with extraBytes.
975 * Returns the number of allocated objects (possibly zero), with
976 * the allocated pointers in *results.
977 **********************************************************************/
979 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
980 id *results, unsigned num_requested)
982 unsigned num_allocated;
985 size_t size = cls->instanceSize(extraBytes);
988 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
989 size, (void**)results, num_requested);
990 for (unsigned i = 0; i < num_allocated; i++) {
991 bzero(results[i], size);
994 // Construct each object, and delete any that fail construction.
997 bool ctor = cls->hasCxxCtor();
998 for (unsigned i = 0; i < num_allocated; i++) {
1000 obj->initIsa(cls); // fixme allow nonpointer
1001 if (ctor) obj = _objc_constructOrFree(obj, cls);
1004 results[i-shift] = obj;
1010 return num_allocated - shift;
1014 /***********************************************************************
1015 * inform_duplicate. Complain about duplicate class implementations.
1016 **********************************************************************/
1018 inform_duplicate(const char *name, Class oldCls, Class newCls)
1021 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1022 ("Class %s is implemented in two different images.", name);
1024 const header_info *oldHeader = _headerForClass(oldCls);
1025 const header_info *newHeader = _headerForClass(newCls);
1026 const char *oldName = oldHeader ? oldHeader->fname() : "??";
1027 const char *newName = newHeader ? newHeader->fname() : "??";
1029 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1030 ("Class %s is implemented in both %s (%p) and %s (%p). "
1031 "One of the two will be used. Which one is undefined.",
1032 name, oldName, oldCls, newName, newCls);
1038 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
1043 if (count == 0) return strdup("");
1046 // debug build: sanitize input
1047 for (i = 0; i < count; i++) {
1048 assert(attrs[i].name);
1049 assert(strlen(attrs[i].name) > 0);
1050 assert(! strchr(attrs[i].name, ','));
1051 assert(! strchr(attrs[i].name, '"'));
1052 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
1057 for (i = 0; i < count; i++) {
1058 if (attrs[i].value) {
1059 size_t namelen = strlen(attrs[i].name);
1060 if (namelen > 1) namelen += 2; // long names get quoted
1061 len += namelen + strlen(attrs[i].value) + 1;
1065 result = (char *)malloc(len + 1);
1067 for (i = 0; i < count; i++) {
1068 if (attrs[i].value) {
1069 size_t namelen = strlen(attrs[i].name);
1071 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
1073 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
1078 // remove trailing ',' if any
1079 if (s > result) s[-1] = '\0';
1085 Property attribute string format:
1087 - Comma-separated name-value pairs.
1088 - Name and value may not contain ,
1089 - Name may not contain "
1090 - Value may be empty
1091 - Name is single char, value follows
1092 - OR Name is double-quoted string of 2+ chars, value follows
1095 attribute-string: \0
1096 attribute-string: name-value-pair (',' name-value-pair)*
1097 name-value-pair: unquoted-name optional-value
1098 name-value-pair: quoted-name optional-value
1099 unquoted-name: [^",]
1100 quoted-name: '"' [^",]{2,} '"'
1101 optional-value: [^,]*
1105 iteratePropertyAttributes(const char *attrs,
1106 bool (*fn)(unsigned int index,
1107 void *ctx1, void *ctx2,
1108 const char *name, size_t nlen,
1109 const char *value, size_t vlen),
1110 void *ctx1, void *ctx2)
1112 if (!attrs) return 0;
1115 const char *attrsend = attrs + strlen(attrs);
1117 unsigned int attrcount = 0;
1120 // Find the next comma-separated attribute
1121 const char *start = attrs;
1122 const char *end = start + strcspn(attrs, ",");
1124 // Move attrs past this attribute and the comma (if any)
1125 attrs = *end ? end+1 : end;
1127 assert(attrs <= attrsend);
1128 assert(start <= attrsend);
1129 assert(end <= attrsend);
1131 // Skip empty attribute
1132 if (start == end) continue;
1134 // Process one non-empty comma-free attribute [start,end)
1135 const char *nameStart;
1136 const char *nameEnd;
1138 assert(start < end);
1140 if (*start != '\"') {
1141 // single-char short name
1147 // double-quoted long name
1148 nameStart = start+1;
1149 nameEnd = nameStart + strcspn(nameStart, "\",");
1150 start++; // leading quote
1151 start += nameEnd - nameStart; // name
1152 if (*start == '\"') start++; // trailing quote, if any
1155 // Process one possibly-empty comma-free attribute value [start,end)
1156 const char *valueStart;
1157 const char *valueEnd;
1159 assert(start <= end);
1164 bool more = (*fn)(attrcount, ctx1, ctx2,
1165 nameStart, nameEnd-nameStart,
1166 valueStart, valueEnd-valueStart);
1176 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1177 const char *name, size_t nlen, const char *value, size_t vlen)
1179 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1180 char **sp = (char **)ctxs;
1182 objc_property_attribute_t *a = *ap;
1186 memcpy(s, name, nlen);
1191 memcpy(s, value, vlen);
1204 objc_property_attribute_t *
1205 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1208 if (outCount) *outCount = 0;
1213 // number of commas plus 1 for the attributes (upper bound)
1214 // plus another attribute for the attribute array terminator
1215 // plus strlen(attrs) for name/value string data (upper bound)
1216 // plus count*2 for the name/value string terminators (upper bound)
1217 unsigned int attrcount = 1;
1219 for (s = attrs; s && *s; s++) {
1220 if (*s == ',') attrcount++;
1224 attrcount * sizeof(objc_property_attribute_t) +
1225 sizeof(objc_property_attribute_t) +
1228 objc_property_attribute_t *result = (objc_property_attribute_t *)
1231 objc_property_attribute_t *ra = result;
1232 char *rs = (char *)(ra+attrcount+1);
1234 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1236 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1237 assert((uint8_t *)rs <= (uint8_t *)result+size);
1239 if (attrcount == 0) {
1244 if (outCount) *outCount = attrcount;
1250 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1251 const char *name, size_t nlen, const char *value, size_t vlen)
1253 const char *query = (char *)ctxa;
1254 char **resultp = (char **)ctxs;
1256 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1257 char *result = (char *)calloc(vlen+1, 1);
1258 memcpy(result, value, vlen);
1259 result[vlen] = '\0';
1267 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1271 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);