2 * Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
23 /***********************************************************************
25 * Copyright 1988-1997, Apple Computer, Inc.
27 **********************************************************************/
30 /***********************************************************************
31 * Lazy method list arrays and method list locking (2004-10-19)
33 * cls->methodLists may be in one of three forms:
34 * 1. nil: The class has no methods.
35 * 2. non-nil, with CLS_NO_METHOD_ARRAY set: cls->methodLists points
36 * to a single method list, which is the class's only method list.
37 * 3. non-nil, with CLS_NO_METHOD_ARRAY clear: cls->methodLists points to
38 * an array of method list pointers. The end of the array's block
39 * is set to -1. If the actual number of method lists is smaller
40 * than that, the rest of the array is nil.
42 * Attaching categories and adding and removing classes may change
43 * the form of the class list. In addition, individual method lists
44 * may be reallocated when fixed up.
46 * Classes are initially read as #1 or #2. If a category is attached
47 * or other methods added, the class is changed to #3. Once in form #3,
48 * the class is never downgraded to #1 or #2, even if methods are removed.
49 * Classes added with objc_addClass are initially either #1 or #3.
51 * Accessing and manipulating a class's method lists are synchronized,
52 * to prevent races when one thread restructures the list. However,
53 * if the class is not yet in use (i.e. not in class_hash), then the
54 * thread loading the class may access its method lists without locking.
56 * The following functions acquire methodListLock:
57 * class_getInstanceMethod
58 * class_getClassMethod
59 * class_nextMethodList
62 * class_respondsToMethod
63 * _class_lookupMethodAndLoadCache
64 * lookupMethodInClassAndLoadCache
65 * _objc_add_category_flush_caches
67 * The following functions don't acquire methodListLock because they
68 * only access method lists during class load and unload:
69 * _objc_register_category
70 * _resolve_categories_for_class (calls _objc_add_category)
71 * add_class_to_loadable_list
73 * _objc_remove_classes_in_image
75 * The following functions use method lists without holding methodListLock.
76 * The caller must either hold methodListLock, or be loading the class.
77 * _getMethod (called by class_getInstanceMethod, class_getClassMethod,
78 * and class_respondsToMethod)
79 * _findMethodInClass (called by _class_lookupMethodAndLoadCache,
80 * lookupMethodInClassAndLoadCache, _getMethod)
81 * _findMethodInList (called by _findMethodInClass)
82 * nextMethodList (called by _findMethodInClass and class_nextMethodList
83 * fixupSelectorsInMethodList (called by nextMethodList)
84 * _objc_add_category (called by _objc_add_category_flush_caches,
85 * resolve_categories_for_class and _objc_register_category)
86 * _objc_insertMethods (called by class_addMethods and _objc_add_category)
87 * _objc_removeMethods (called by class_removeMethods)
88 * _objcTweakMethodListPointerForClass (called by _objc_insertMethods)
89 * get_base_method_list (called by add_class_to_loadable_list)
90 * lookupNamedMethodInMethodList (called by add_class_to_loadable_list)
91 ***********************************************************************/
93 /***********************************************************************
94 * Thread-safety of class info bits (2004-10-19)
96 * Some class info bits are used to store mutable runtime state.
97 * Modifications of the info bits at particular times need to be
98 * synchronized to prevent races.
100 * Three thread-safe modification functions are provided:
101 * cls->setInfo() // atomically sets some bits
102 * cls->clearInfo() // atomically clears some bits
103 * cls->changeInfo() // atomically sets some bits and clears others
104 * These replace CLS_SETINFO() for the multithreaded cases.
106 * Three modification windows are defined:
108 * - class construction or image load (before +load) in one thread
109 * - multi-threaded messaging and method caches
111 * Info bit modification at compile time and class construction do not
112 * need to be locked, because only one thread is manipulating the class.
113 * Info bit modification during messaging needs to be locked, because
114 * there may be other threads simultaneously messaging or otherwise
115 * manipulating the class.
117 * Modification windows for each flag:
119 * CLS_CLASS: compile-time and class load
120 * CLS_META: compile-time and class load
121 * CLS_INITIALIZED: +initialize
122 * CLS_POSING: messaging
123 * CLS_MAPPED: compile-time
124 * CLS_FLUSH_CACHE: class load and messaging
125 * CLS_GROW_CACHE: messaging
126 * CLS_NEED_BIND: unused
127 * CLS_METHOD_ARRAY: unused
128 * CLS_JAVA_HYBRID: JavaBridge only
129 * CLS_JAVA_CLASS: JavaBridge only
130 * CLS_INITIALIZING: messaging
131 * CLS_FROM_BUNDLE: class load
132 * CLS_HAS_CXX_STRUCTORS: compile-time and class load
133 * CLS_NO_METHOD_ARRAY: class load and messaging
134 * CLS_HAS_LOAD_METHOD: class load
136 * CLS_INITIALIZED and CLS_INITIALIZING have additional thread-safety
137 * constraints to support thread-safe +initialize. See "Thread safety
138 * during class initialization" for details.
140 * CLS_JAVA_HYBRID and CLS_JAVA_CLASS are set immediately after JavaBridge
141 * calls objc_addClass(). The JavaBridge does not use an atomic update,
142 * but the modification counts as "class construction" unless some other
143 * thread quickly finds the class via the class list. This race is
144 * small and unlikely in well-behaved code.
146 * Most info bits that may be modified during messaging are also never
147 * read without a lock. There is no general read lock for the info bits.
148 * CLS_INITIALIZED: classInitLock
149 * CLS_FLUSH_CACHE: cacheUpdateLock
150 * CLS_GROW_CACHE: cacheUpdateLock
151 * CLS_NO_METHOD_ARRAY: methodListLock
152 * CLS_INITIALIZING: classInitLock
153 ***********************************************************************/
155 /***********************************************************************
157 **********************************************************************/
159 #include "objc-private.h"
160 #include "objc-abi.h"
161 #include "objc-auto.h"
162 #include <objc/message.h>
165 /* overriding the default object allocation and error handling routines */
167 OBJC_EXPORT id (*_alloc)(Class, size_t);
168 OBJC_EXPORT id (*_copy)(id, size_t);
169 OBJC_EXPORT id (*_realloc)(id, size_t);
170 OBJC_EXPORT id (*_dealloc)(id);
171 OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *);
172 OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *);
173 OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *);
176 /***********************************************************************
177 * Information about multi-thread support:
179 * Since we do not lock many operations which walk the superclass, method
180 * and ivar chains, these chains must remain intact once a class is published
181 * by inserting it into the class hashtable. All modifications must be
182 * atomic so that someone walking these chains will always geta valid
184 ***********************************************************************/
188 /***********************************************************************
190 * Locking: None. If you add locking, tell gdb (rdar://7516456).
191 **********************************************************************/
192 Class object_getClass(id obj)
194 if (obj) return obj->getIsa();
199 /***********************************************************************
201 **********************************************************************/
202 Class object_setClass(id obj, Class cls)
204 if (obj) return obj->changeIsa(cls);
209 /***********************************************************************
211 **********************************************************************/
212 BOOL object_isClass(id obj)
215 return obj->isClass();
219 /***********************************************************************
220 * object_getClassName.
221 **********************************************************************/
222 const char *object_getClassName(id obj)
224 return class_getName(obj ? obj->getIsa() : nil);
228 /***********************************************************************
229 * object_getMethodImplementation.
230 **********************************************************************/
231 IMP object_getMethodImplementation(id obj, SEL name)
233 Class cls = (obj ? obj->getIsa() : nil);
234 return class_getMethodImplementation(cls, name);
238 /***********************************************************************
239 * object_getMethodImplementation_stret.
240 **********************************************************************/
242 IMP object_getMethodImplementation_stret(id obj, SEL name)
244 Class cls = (obj ? obj->getIsa() : nil);
245 return class_getMethodImplementation_stret(cls, name);
250 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
254 if (obj && name && !obj->isTaggedPointer()) {
255 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
256 object_setIvar(obj, ivar, (id)value);
262 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
264 if (obj && name && !obj->isTaggedPointer()) {
266 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
267 if (value) *value = (void *)object_getIvar(obj, ivar);
271 if (value) *value = nil;
275 static BOOL is_scanned_offset(ptrdiff_t ivar_offset, const uint8_t *layout) {
276 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
278 while ((byte = *layout++)) {
279 unsigned skips = (byte >> 4);
280 unsigned scans = (byte & 0x0F);
283 if (index == ivar_index) return YES;
284 if (index > ivar_index) return NO;
291 // FIXME: this could be optimized.
293 static Class _ivar_getClass(Class cls, Ivar ivar) {
294 Class ivar_class = nil;
295 const char *ivar_name = ivar_getName(ivar);
296 Ivar named_ivar = _class_getVariable(cls, ivar_name, &ivar_class);
298 // the same ivar name can appear multiple times along the superclass chain.
299 while (named_ivar != ivar && ivar_class != nil) {
300 ivar_class = ivar_class->superclass;
301 named_ivar = _class_getVariable(cls, ivar_getName(ivar), &ivar_class);
307 void object_setIvar(id obj, Ivar ivar, id value)
309 if (obj && ivar && !obj->isTaggedPointer()) {
310 Class cls = _ivar_getClass(obj->ISA(), ivar);
311 ptrdiff_t ivar_offset = ivar_getOffset(ivar);
312 id *location = (id *)((char *)obj + ivar_offset);
313 // if this ivar is a member of an ARR compiled class, then issue the correct barrier according to the layout.
314 if (_class_usesAutomaticRetainRelease(cls)) {
315 // for ARR, layout strings are relative to the instance start.
316 uint32_t instanceStart = _class_getInstanceStart(cls);
317 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
318 if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) {
319 // use the weak system to write to this variable.
320 objc_storeWeak(location, value);
323 const uint8_t *strong_layout = class_getIvarLayout(cls);
324 if (strong_layout && is_scanned_offset(ivar_offset - instanceStart, strong_layout)) {
325 objc_storeStrong(location, value);
331 // for GC, check for weak references.
332 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
333 if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) {
334 objc_assign_weak(value, location);
337 objc_assign_ivar(value, obj, ivar_offset);
345 id object_getIvar(id obj, Ivar ivar)
347 if (obj && ivar && !obj->isTaggedPointer()) {
348 Class cls = obj->ISA();
349 ptrdiff_t ivar_offset = ivar_getOffset(ivar);
350 if (_class_usesAutomaticRetainRelease(cls)) {
351 // for ARR, layout strings are relative to the instance start.
352 uint32_t instanceStart = _class_getInstanceStart(cls);
353 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
354 if (weak_layout && is_scanned_offset(ivar_offset - instanceStart, weak_layout)) {
355 // use the weak system to read this variable.
356 id *location = (id *)((char *)obj + ivar_offset);
357 return objc_loadWeak(location);
360 id *idx = (id *)((char *)obj + ivar_offset);
363 const uint8_t *weak_layout = class_getWeakIvarLayout(cls);
364 if (weak_layout && is_scanned_offset(ivar_offset, weak_layout)) {
365 return objc_read_weak(idx);
375 /***********************************************************************
376 * object_cxxDestructFromClass.
377 * Call C++ destructors on obj, starting with cls's
378 * dtor method (if any) followed by superclasses' dtors (if any),
379 * stopping at cls's dtor (if any).
380 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
381 **********************************************************************/
382 static void object_cxxDestructFromClass(id obj, Class cls)
386 // Call cls's dtor first, then superclasses's dtors.
388 for ( ; cls; cls = cls->superclass) {
389 if (!cls->hasCxxDtor()) return;
391 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
392 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
394 _objc_inform("CXX: calling C++ destructors for class %s",
395 cls->nameForLogging());
403 /***********************************************************************
404 * object_cxxDestruct.
405 * Call C++ destructors on obj, if any.
406 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
407 **********************************************************************/
408 void object_cxxDestruct(id obj)
411 if (obj->isTaggedPointer()) return;
412 object_cxxDestructFromClass(obj, obj->ISA());
416 /***********************************************************************
417 * object_cxxConstructFromClass.
418 * Recursively call C++ constructors on obj, starting with base class's
419 * ctor method (if any) followed by subclasses' ctors (if any), stopping
420 * at cls's ctor (if any).
421 * Does not check cls->hasCxxCtor(). The caller should preflight that.
422 * Returns self if construction succeeded.
423 * Returns nil if some constructor threw an exception. The exception is
424 * caught and discarded. Any partial construction is destructed.
425 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
427 * .cxx_construct returns id. This really means:
428 * return self: construction succeeded
429 * return nil: construction failed because a C++ constructor threw an exception
430 **********************************************************************/
432 object_cxxConstructFromClass(id obj, Class cls)
434 assert(cls->hasCxxCtor()); // required for performance, not correctness
439 supercls = cls->superclass;
441 // Call superclasses' ctors first, if any.
442 if (supercls && supercls->hasCxxCtor()) {
443 bool ok = object_cxxConstructFromClass(obj, supercls);
444 if (!ok) return nil; // some superclass's ctor failed - give up
447 // Find this class's ctor, if any.
448 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
449 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
451 // Call this class's ctor.
453 _objc_inform("CXX: calling C++ constructors for class %s",
454 cls->nameForLogging());
456 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
458 // This class's ctor was called and failed.
459 // Call superclasses's dtors to clean up.
460 if (supercls) object_cxxDestructFromClass(obj, supercls);
465 /***********************************************************************
466 * _class_resolveClassMethod
467 * Call +resolveClassMethod, looking for a method to be added to class cls.
468 * cls should be a metaclass.
469 * Does not check if the method already exists.
470 **********************************************************************/
471 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
473 assert(cls->isMetaClass());
475 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
476 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
478 // Resolver not implemented.
482 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
483 BOOL resolved = msg(_class_getNonMetaClass(cls, inst),
484 SEL_resolveClassMethod, sel);
486 // Cache the result (good or bad) so the resolver doesn't fire next time.
487 // +resolveClassMethod adds to self->ISA() a.k.a. cls
488 IMP imp = lookUpImpOrNil(cls, sel, inst,
489 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
491 if (resolved && PrintResolving) {
493 _objc_inform("RESOLVE: method %c[%s %s] "
494 "dynamically resolved to %p",
495 cls->isMetaClass() ? '+' : '-',
496 cls->nameForLogging(), sel_getName(sel), imp);
499 // Method resolver didn't add anything?
500 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
501 ", but no new implementation of %c[%s %s] was found",
502 cls->nameForLogging(), sel_getName(sel),
503 cls->isMetaClass() ? '+' : '-',
504 cls->nameForLogging(), sel_getName(sel));
510 /***********************************************************************
511 * _class_resolveInstanceMethod
512 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
513 * cls may be a metaclass or a non-meta class.
514 * Does not check if the method already exists.
515 **********************************************************************/
516 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
518 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
519 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
521 // Resolver not implemented.
525 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
526 BOOL resolved = msg(cls, SEL_resolveInstanceMethod, sel);
528 // Cache the result (good or bad) so the resolver doesn't fire next time.
529 // +resolveInstanceMethod adds to self a.k.a. cls
530 IMP imp = lookUpImpOrNil(cls, sel, inst,
531 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
533 if (resolved && PrintResolving) {
535 _objc_inform("RESOLVE: method %c[%s %s] "
536 "dynamically resolved to %p",
537 cls->isMetaClass() ? '+' : '-',
538 cls->nameForLogging(), sel_getName(sel), imp);
541 // Method resolver didn't add anything?
542 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
543 ", but no new implementation of %c[%s %s] was found",
544 cls->nameForLogging(), sel_getName(sel),
545 cls->isMetaClass() ? '+' : '-',
546 cls->nameForLogging(), sel_getName(sel));
552 /***********************************************************************
553 * _class_resolveMethod
554 * Call +resolveClassMethod or +resolveInstanceMethod.
555 * Returns nothing; any result would be potentially out-of-date already.
556 * Does not check if the method already exists.
557 **********************************************************************/
558 void _class_resolveMethod(Class cls, SEL sel, id inst)
560 if (! cls->isMetaClass()) {
561 // try [cls resolveInstanceMethod:sel]
562 _class_resolveInstanceMethod(cls, sel, inst);
565 // try [nonMetaClass resolveClassMethod:sel]
566 // and [cls resolveInstanceMethod:sel]
567 _class_resolveClassMethod(cls, sel, inst);
568 if (!lookUpImpOrNil(cls, sel, inst,
569 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
571 _class_resolveInstanceMethod(cls, sel, inst);
577 /***********************************************************************
578 * class_getClassMethod. Return the class method for the specified
579 * class and selector.
580 **********************************************************************/
581 Method class_getClassMethod(Class cls, SEL sel)
583 if (!cls || !sel) return nil;
585 return class_getInstanceMethod(cls->getMeta(), sel);
589 /***********************************************************************
590 * class_getInstanceVariable. Return the named instance variable.
591 **********************************************************************/
592 Ivar class_getInstanceVariable(Class cls, const char *name)
594 if (!cls || !name) return nil;
596 return _class_getVariable(cls, name, nil);
600 /***********************************************************************
601 * class_getClassVariable. Return the named class variable.
602 **********************************************************************/
603 Ivar class_getClassVariable(Class cls, const char *name)
605 if (!cls) return nil;
607 return class_getInstanceVariable(cls->ISA(), name);
611 /***********************************************************************
612 * gdb_objc_class_changed
613 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
614 * Does nothing; gdb sets a breakpoint on it.
615 **********************************************************************/
617 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
621 /***********************************************************************
622 * class_respondsToSelector.
623 **********************************************************************/
624 BOOL class_respondsToMethod(Class cls, SEL sel)
626 OBJC_WARN_DEPRECATED;
628 return class_respondsToSelector(cls, sel);
632 BOOL class_respondsToSelector(Class cls, SEL sel)
634 return class_respondsToSelector_inst(cls, sel, nil);
638 // inst is an instance of cls or a subclass thereof, or nil if none is known.
639 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
640 BOOL class_respondsToSelector_inst(Class cls, SEL sel, id inst)
644 if (!sel || !cls) return NO;
646 // Avoids +initialize because it historically did so.
647 // We're not returning a callable IMP anyway.
648 imp = lookUpImpOrNil(cls, sel, inst,
649 NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
650 return imp ? YES : NO;
654 /***********************************************************************
655 * class_getMethodImplementation.
656 * Returns the IMP that would be invoked if [obj sel] were sent,
657 * where obj is an instance of class cls.
658 **********************************************************************/
659 IMP class_lookupMethod(Class cls, SEL sel)
661 OBJC_WARN_DEPRECATED;
663 // No one responds to zero!
665 __objc_error(cls, "invalid selector (null)");
668 return class_getMethodImplementation(cls, sel);
671 IMP class_getMethodImplementation(Class cls, SEL sel)
675 if (!cls || !sel) return nil;
677 imp = lookUpImpOrNil(cls, sel, nil,
678 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
680 // Translate forwarding function to C-callable external version
682 return _objc_msgForward;
689 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
691 IMP imp = class_getMethodImplementation(cls, sel);
693 // Translate forwarding function to struct-returning version
694 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
695 return (IMP)&_objc_msgForward_stret;
702 /***********************************************************************
703 * instrumentObjcMessageSends
704 **********************************************************************/
705 #if !SUPPORT_MESSAGE_LOGGING
707 void instrumentObjcMessageSends(BOOL flag)
713 bool objcMsgLogEnabled = false;
714 static int objcMsgLogFD = -1;
716 bool logMessageSend(bool isClassMethod,
717 const char *objectsClass,
718 const char *implementingClass,
723 // Create/open the log file
724 if (objcMsgLogFD == (-1))
726 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
727 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
728 if (objcMsgLogFD < 0) {
729 // no log file - disable logging
730 objcMsgLogEnabled = false;
736 // Make the log entry
737 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
738 isClassMethod ? '+' : '-',
741 sel_getName(selector));
743 static spinlock_t lock = SPINLOCK_INITIALIZER;
744 spinlock_lock(&lock);
745 write (objcMsgLogFD, buf, strlen(buf));
746 spinlock_unlock(&lock);
748 // Tell caller to not cache the method
752 void instrumentObjcMessageSends(BOOL flag)
757 if (objcMsgLogEnabled == enable)
760 // If enabling, flush all method caches so we get some traces
762 _objc_flush_caches(Nil);
765 if (objcMsgLogFD != -1)
766 fsync (objcMsgLogFD);
768 objcMsgLogEnabled = enable;
771 // SUPPORT_MESSAGE_LOGGING
775 /***********************************************************************
780 * _strdupcat_internal
783 * Convenience functions for the internal malloc zone.
784 **********************************************************************/
785 void *_malloc_internal(size_t size)
787 return malloc_zone_malloc(_objc_internal_zone(), size);
790 void *_calloc_internal(size_t count, size_t size)
792 return malloc_zone_calloc(_objc_internal_zone(), count, size);
795 void *_realloc_internal(void *ptr, size_t size)
797 return malloc_zone_realloc(_objc_internal_zone(), ptr, size);
800 char *_strdup_internal(const char *str)
804 if (!str) return nil;
806 dup = (char *)malloc_zone_malloc(_objc_internal_zone(), len + 1);
807 memcpy(dup, str, len + 1);
811 uint8_t *_ustrdup_internal(const uint8_t *str)
813 return (uint8_t *)_strdup_internal((char *)str);
816 // allocate a new string that concatenates s1+s2.
817 char *_strdupcat_internal(const char *s1, const char *s2)
819 size_t len1 = strlen(s1);
820 size_t len2 = strlen(s2);
822 malloc_zone_malloc(_objc_internal_zone(), len1 + len2 + 1);
823 memcpy(dup, s1, len1);
824 memcpy(dup + len1, s2, len2 + 1);
828 void *_memdup_internal(const void *mem, size_t len)
830 void *dup = malloc_zone_malloc(_objc_internal_zone(), len);
831 memcpy(dup, mem, len);
835 void _free_internal(void *ptr)
837 malloc_zone_free(_objc_internal_zone(), ptr);
840 size_t _malloc_size_internal(void *ptr)
842 malloc_zone_t *zone = _objc_internal_zone();
843 return zone->size(zone, ptr);
846 Class _calloc_class(size_t size)
849 if (UseGC) return (Class) malloc_zone_calloc(gc_zone, 1, size);
851 return (Class) _calloc_internal(1, size);
854 Class class_getSuperclass(Class cls)
856 if (!cls) return nil;
857 return cls->superclass;
860 BOOL class_isMetaClass(Class cls)
863 return cls->isMetaClass();
867 size_t class_getInstanceSize(Class cls)
870 return cls->alignedInstanceSize();
874 /***********************************************************************
875 * method_getNumberOfArguments.
876 **********************************************************************/
877 unsigned int method_getNumberOfArguments(Method m)
880 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
884 void method_getReturnType(Method m, char *dst, size_t dst_len)
886 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
890 char * method_copyReturnType(Method m)
892 return encoding_copyReturnType(method_getTypeEncoding(m));
896 void method_getArgumentType(Method m, unsigned int index,
897 char *dst, size_t dst_len)
899 encoding_getArgumentType(method_getTypeEncoding(m),
900 index, dst, dst_len);
904 char * method_copyArgumentType(Method m, unsigned int index)
906 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
910 /***********************************************************************
911 * _objc_constructOrFree
912 * Call C++ constructors, and free() if they fail.
913 * bytes->isa must already be set.
914 * cls must have cxx constructors.
915 * Returns the object, or nil.
916 **********************************************************************/
918 _objc_constructOrFree(id bytes, Class cls)
920 assert(cls->hasCxxCtor()); // for performance, not correctness
922 id obj = object_cxxConstructFromClass(bytes, cls);
926 auto_zone_retain(gc_zone, bytes); // gc free expects rc==1
936 /***********************************************************************
937 * _class_createInstancesFromZone
938 * Batch-allocating version of _class_createInstanceFromZone.
939 * Attempts to allocate num_requested objects, each with extraBytes.
940 * Returns the number of allocated objects (possibly zero), with
941 * the allocated pointers in *results.
942 **********************************************************************/
944 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
945 id *results, unsigned num_requested)
947 unsigned num_allocated;
950 size_t size = cls->instanceSize(extraBytes);
955 auto_zone_batch_allocate(gc_zone, size, AUTO_OBJECT_SCANNED, 0, 1,
956 (void**)results, num_requested);
962 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
963 size, (void**)results, num_requested);
964 for (i = 0; i < num_allocated; i++) {
965 bzero(results[i], size);
969 // Construct each object, and delete any that fail construction.
973 bool ctor = cls->hasCxxCtor();
974 for (i = 0; i < num_allocated; i++) {
976 obj->initIsa(cls); // fixme allow indexed
977 if (ctor) obj = _objc_constructOrFree(obj, cls);
980 results[i-shift] = obj;
986 return num_allocated - shift;
990 /***********************************************************************
991 * inform_duplicate. Complain about duplicate class implementations.
992 **********************************************************************/
994 inform_duplicate(const char *name, Class oldCls, Class cls)
997 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
998 ("Class %s is implemented in two different images.", name);
1000 const header_info *oldHeader = _headerForClass(oldCls);
1001 const header_info *newHeader = _headerForClass(cls);
1002 const char *oldName = oldHeader ? oldHeader->fname : "??";
1003 const char *newName = newHeader ? newHeader->fname : "??";
1005 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1006 ("Class %s is implemented in both %s and %s. "
1007 "One of the two will be used. Which one is undefined.",
1008 name, oldName, newName);
1014 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
1019 if (count == 0) return strdup("");
1022 // debug build: sanitize input
1023 for (i = 0; i < count; i++) {
1024 assert(attrs[i].name);
1025 assert(strlen(attrs[i].name) > 0);
1026 assert(! strchr(attrs[i].name, ','));
1027 assert(! strchr(attrs[i].name, '"'));
1028 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
1033 for (i = 0; i < count; i++) {
1034 if (attrs[i].value) {
1035 size_t namelen = strlen(attrs[i].name);
1036 if (namelen > 1) namelen += 2; // long names get quoted
1037 len += namelen + strlen(attrs[i].value) + 1;
1041 result = (char *)malloc(len + 1);
1043 for (i = 0; i < count; i++) {
1044 if (attrs[i].value) {
1045 size_t namelen = strlen(attrs[i].name);
1047 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
1049 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
1054 // remove trailing ',' if any
1055 if (s > result) s[-1] = '\0';
1061 Property attribute string format:
1063 - Comma-separated name-value pairs.
1064 - Name and value may not contain ,
1065 - Name may not contain "
1066 - Value may be empty
1067 - Name is single char, value follows
1068 - OR Name is double-quoted string of 2+ chars, value follows
1071 attribute-string: \0
1072 attribute-string: name-value-pair (',' name-value-pair)*
1073 name-value-pair: unquoted-name optional-value
1074 name-value-pair: quoted-name optional-value
1075 unquoted-name: [^",]
1076 quoted-name: '"' [^",]{2,} '"'
1077 optional-value: [^,]*
1081 iteratePropertyAttributes(const char *attrs,
1082 BOOL (*fn)(unsigned int index,
1083 void *ctx1, void *ctx2,
1084 const char *name, size_t nlen,
1085 const char *value, size_t vlen),
1086 void *ctx1, void *ctx2)
1088 if (!attrs) return 0;
1091 const char *attrsend = attrs + strlen(attrs);
1093 unsigned int attrcount = 0;
1096 // Find the next comma-separated attribute
1097 const char *start = attrs;
1098 const char *end = start + strcspn(attrs, ",");
1100 // Move attrs past this attribute and the comma (if any)
1101 attrs = *end ? end+1 : end;
1103 assert(attrs <= attrsend);
1104 assert(start <= attrsend);
1105 assert(end <= attrsend);
1107 // Skip empty attribute
1108 if (start == end) continue;
1110 // Process one non-empty comma-free attribute [start,end)
1111 const char *nameStart;
1112 const char *nameEnd;
1114 assert(start < end);
1116 if (*start != '\"') {
1117 // single-char short name
1123 // double-quoted long name
1124 nameStart = start+1;
1125 nameEnd = nameStart + strcspn(nameStart, "\",");
1126 start++; // leading quote
1127 start += nameEnd - nameStart; // name
1128 if (*start == '\"') start++; // trailing quote, if any
1131 // Process one possibly-empty comma-free attribute value [start,end)
1132 const char *valueStart;
1133 const char *valueEnd;
1135 assert(start <= end);
1140 BOOL more = (*fn)(attrcount, ctx1, ctx2,
1141 nameStart, nameEnd-nameStart,
1142 valueStart, valueEnd-valueStart);
1152 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1153 const char *name, size_t nlen, const char *value, size_t vlen)
1155 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1156 char **sp = (char **)ctxs;
1158 objc_property_attribute_t *a = *ap;
1162 memcpy(s, name, nlen);
1167 memcpy(s, value, vlen);
1180 objc_property_attribute_t *
1181 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1184 if (outCount) *outCount = 0;
1189 // number of commas plus 1 for the attributes (upper bound)
1190 // plus another attribute for the attribute array terminator
1191 // plus strlen(attrs) for name/value string data (upper bound)
1192 // plus count*2 for the name/value string terminators (upper bound)
1193 unsigned int attrcount = 1;
1195 for (s = attrs; s && *s; s++) {
1196 if (*s == ',') attrcount++;
1200 attrcount * sizeof(objc_property_attribute_t) +
1201 sizeof(objc_property_attribute_t) +
1204 objc_property_attribute_t *result = (objc_property_attribute_t *)
1207 objc_property_attribute_t *ra = result;
1208 char *rs = (char *)(ra+attrcount+1);
1210 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1212 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1213 assert((uint8_t *)rs <= (uint8_t *)result+size);
1215 if (attrcount == 0) {
1220 if (outCount) *outCount = attrcount;
1226 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1227 const char *name, size_t nlen, const char *value, size_t vlen)
1229 const char *query = (char *)ctxa;
1230 char **resultp = (char **)ctxs;
1232 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1233 char *result = (char *)calloc(vlen+1, 1);
1234 memcpy(result, value, vlen);
1235 result[vlen] = '\0';
1243 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1247 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);