]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-class.mm
objc4-709.tar.gz
[apple/objc4.git] / runtime / objc-class.mm
1 /*
2 * Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /***********************************************************************
24 * objc-class.m
25 * Copyright 1988-1997, Apple Computer, Inc.
26 * Author: s. naroff
27 **********************************************************************/
28
29
30 /***********************************************************************
31 * Lazy method list arrays and method list locking (2004-10-19)
32 *
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.
41 *
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.
45 *
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.
50 *
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.
55 *
56 * The following functions acquire methodListLock:
57 * class_getInstanceMethod
58 * class_getClassMethod
59 * class_nextMethodList
60 * class_addMethods
61 * class_removeMethods
62 * class_respondsToMethod
63 * _class_lookupMethodAndLoadCache
64 * lookupMethodInClassAndLoadCache
65 * _objc_add_category_flush_caches
66 *
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
72 * _objc_addClass
73 * _objc_remove_classes_in_image
74 *
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 ***********************************************************************/
92
93 /***********************************************************************
94 * Thread-safety of class info bits (2004-10-19)
95 *
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.
99 *
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.
105 *
106 * Three modification windows are defined:
107 * - compile time
108 * - class construction or image load (before +load) in one thread
109 * - multi-threaded messaging and method caches
110 *
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.
116 *
117 * Modification windows for each flag:
118 *
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
135 *
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.
139 *
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.
145 *
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 ***********************************************************************/
154
155 /***********************************************************************
156 * Imports.
157 **********************************************************************/
158
159 #include "objc-private.h"
160 #include "objc-abi.h"
161 #include <objc/message.h>
162
163
164 /* overriding the default object allocation and error handling routines */
165
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 *);
173
174
175 /***********************************************************************
176 * Information about multi-thread support:
177 *
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
182 * result.
183 ***********************************************************************/
184
185
186
187 /***********************************************************************
188 * object_getClass.
189 * Locking: None. If you add locking, tell gdb (rdar://7516456).
190 **********************************************************************/
191 Class object_getClass(id obj)
192 {
193 if (obj) return obj->getIsa();
194 else return Nil;
195 }
196
197
198 /***********************************************************************
199 * object_setClass.
200 **********************************************************************/
201 Class object_setClass(id obj, Class cls)
202 {
203 if (!obj) return nil;
204
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));
211 }
212
213 return obj->changeIsa(cls);
214 }
215
216
217 /***********************************************************************
218 * object_isClass.
219 **********************************************************************/
220 BOOL object_isClass(id obj)
221 {
222 if (!obj) return NO;
223 return obj->isClass();
224 }
225
226
227 /***********************************************************************
228 * object_getClassName.
229 **********************************************************************/
230 const char *object_getClassName(id obj)
231 {
232 return class_getName(obj ? obj->getIsa() : nil);
233 }
234
235
236 /***********************************************************************
237 * object_getMethodImplementation.
238 **********************************************************************/
239 IMP object_getMethodImplementation(id obj, SEL name)
240 {
241 Class cls = (obj ? obj->getIsa() : nil);
242 return class_getMethodImplementation(cls, name);
243 }
244
245
246 /***********************************************************************
247 * object_getMethodImplementation_stret.
248 **********************************************************************/
249 #if SUPPORT_STRET
250 IMP object_getMethodImplementation_stret(id obj, SEL name)
251 {
252 Class cls = (obj ? obj->getIsa() : nil);
253 return class_getMethodImplementation_stret(cls, name);
254 }
255 #endif
256
257
258 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
259 {
260 if (!layout) return NO;
261
262 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
263 uint8_t byte;
264 while ((byte = *layout++)) {
265 unsigned skips = (byte >> 4);
266 unsigned scans = (byte & 0x0F);
267 index += skips;
268 if (index > ivar_index) return NO;
269 index += scans;
270 if (index > ivar_index) return YES;
271 }
272 return NO;
273 }
274
275
276 /***********************************************************************
277 * _class_lookUpIvar
278 * Given an object and an ivar in it, look up some data about that ivar:
279 * - its offset
280 * - its memory management behavior
281 * The ivar is assumed to be word-aligned and of of object type.
282 **********************************************************************/
283 static void
284 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
285 objc_ivar_memory_management_t& memoryManagement)
286 {
287 ivarOffset = ivar_getOffset(ivar);
288
289 // Look for ARC variables and ARC-style weak.
290
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;
297 break;
298 }
299 }
300
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();
309
310 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
311 memoryManagement = objc_ivar_memoryStrong;
312 return;
313 }
314
315 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
316 memoryManagement = objc_ivar_memoryWeak;
317 return;
318 }
319
320 // Unretained is only for true ARC classes.
321 if (ivarCls->isARC()) {
322 memoryManagement = objc_ivar_memoryUnretained;
323 return;
324 }
325 }
326 }
327
328 memoryManagement = objc_ivar_memoryUnknown;
329 }
330
331
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)
339 {
340 ptrdiff_t offset;
341 objc_ivar_memory_management_t memoryManagement;
342 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
343 return memoryManagement;
344 }
345
346
347 static ALWAYS_INLINE
348 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
349 {
350 if (!obj || !ivar || obj->isTaggedPointer()) return;
351
352 ptrdiff_t offset;
353 objc_ivar_memory_management_t memoryManagement;
354 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
355
356 if (memoryManagement == objc_ivar_memoryUnknown) {
357 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
358 else memoryManagement = objc_ivar_memoryUnretained;
359 }
360
361 id *location = (id *)((char *)obj + offset);
362
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");
368 }
369 }
370
371 void object_setIvar(id obj, Ivar ivar, id value)
372 {
373 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
374 }
375
376 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
377 {
378 return _object_setIvar(obj, ivar, value, true /*strong default*/);
379 }
380
381
382 id object_getIvar(id obj, Ivar ivar)
383 {
384 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
385
386 ptrdiff_t offset;
387 objc_ivar_memory_management_t memoryManagement;
388 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
389
390 id *location = (id *)((char *)obj + offset);
391
392 if (memoryManagement == objc_ivar_memoryWeak) {
393 return objc_loadWeak(location);
394 } else {
395 return *location;
396 }
397 }
398
399
400 static ALWAYS_INLINE
401 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
402 bool assumeStrong)
403 {
404 Ivar ivar = nil;
405
406 if (obj && name && !obj->isTaggedPointer()) {
407 if ((ivar = _class_getVariable(obj->ISA(), name))) {
408 _object_setIvar(obj, ivar, (id)value, assumeStrong);
409 }
410 }
411 return ivar;
412 }
413
414 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
415 {
416 return _object_setInstanceVariable(obj, name, value, false);
417 }
418
419 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
420 void *value)
421 {
422 return _object_setInstanceVariable(obj, name, value, true);
423 }
424
425
426 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
427 {
428 if (obj && name && !obj->isTaggedPointer()) {
429 Ivar ivar;
430 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
431 if (value) *value = (void *)object_getIvar(obj, ivar);
432 return ivar;
433 }
434 }
435 if (value) *value = nil;
436 return nil;
437 }
438
439
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)
448 {
449 void (*dtor)(id);
450
451 // Call cls's dtor first, then superclasses's dtors.
452
453 for ( ; cls; cls = cls->superclass) {
454 if (!cls->hasCxxDtor()) return;
455 dtor = (void(*)(id))
456 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
457 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
458 if (PrintCxxCtors) {
459 _objc_inform("CXX: calling C++ destructors for class %s",
460 cls->nameForLogging());
461 }
462 (*dtor)(obj);
463 }
464 }
465 }
466
467
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)
474 {
475 if (!obj) return;
476 if (obj->isTaggedPointer()) return;
477 object_cxxDestructFromClass(obj, obj->ISA());
478 }
479
480
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.
491 *
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 **********************************************************************/
496 id
497 object_cxxConstructFromClass(id obj, Class cls)
498 {
499 assert(cls->hasCxxCtor()); // required for performance, not correctness
500
501 id (*ctor)(id);
502 Class supercls;
503
504 supercls = cls->superclass;
505
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
510 }
511
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
515
516 // Call this class's ctor.
517 if (PrintCxxCtors) {
518 _objc_inform("CXX: calling C++ constructors for class %s",
519 cls->nameForLogging());
520 }
521 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
522
523 // This class's ctor was called and failed.
524 // Call superclasses's dtors to clean up.
525 if (supercls) object_cxxDestructFromClass(obj, supercls);
526 return nil;
527 }
528
529
530 /***********************************************************************
531 * fixupCopiedIvars
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)
536 {
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();
542
543 const uint8_t *strongLayout = class_getIvarLayout(cls);
544 if (strongLayout) {
545 id *newPtr = (id *)((char*)newObject + instanceStart);
546 unsigned char byte;
547 while ((byte = *strongLayout++)) {
548 unsigned skips = (byte >> 4);
549 unsigned scans = (byte & 0x0F);
550 newPtr += skips;
551 while (scans--) {
552 // ensure strong references are properly retained.
553 id value = *newPtr++;
554 if (value) objc_retain(value);
555 }
556 }
557 }
558
559 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
560 // fix up weak references if any.
561 if (weakLayout) {
562 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
563 unsigned char byte;
564 while ((byte = *weakLayout++)) {
565 unsigned skips = (byte >> 4);
566 unsigned weaks = (byte & 0x0F);
567 newPtr += skips, oldPtr += skips;
568 while (weaks--) {
569 objc_copyWeak(newPtr, oldPtr);
570 ++newPtr, ++oldPtr;
571 }
572 }
573 }
574 }
575 }
576 }
577
578
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)
586 {
587 assert(cls->isMetaClass());
588
589 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
590 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
591 {
592 // Resolver not implemented.
593 return;
594 }
595
596 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
597 bool resolved = msg(_class_getNonMetaClass(cls, inst),
598 SEL_resolveClassMethod, sel);
599
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*/);
604
605 if (resolved && PrintResolving) {
606 if (imp) {
607 _objc_inform("RESOLVE: method %c[%s %s] "
608 "dynamically resolved to %p",
609 cls->isMetaClass() ? '+' : '-',
610 cls->nameForLogging(), sel_getName(sel), imp);
611 }
612 else {
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));
619 }
620 }
621 }
622
623
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)
631 {
632 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
633 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
634 {
635 // Resolver not implemented.
636 return;
637 }
638
639 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
640 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
641
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*/);
646
647 if (resolved && PrintResolving) {
648 if (imp) {
649 _objc_inform("RESOLVE: method %c[%s %s] "
650 "dynamically resolved to %p",
651 cls->isMetaClass() ? '+' : '-',
652 cls->nameForLogging(), sel_getName(sel), imp);
653 }
654 else {
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));
661 }
662 }
663 }
664
665
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)
673 {
674 if (! cls->isMetaClass()) {
675 // try [cls resolveInstanceMethod:sel]
676 _class_resolveInstanceMethod(cls, sel, inst);
677 }
678 else {
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*/))
684 {
685 _class_resolveInstanceMethod(cls, sel, inst);
686 }
687 }
688 }
689
690
691 /***********************************************************************
692 * class_getClassMethod. Return the class method for the specified
693 * class and selector.
694 **********************************************************************/
695 Method class_getClassMethod(Class cls, SEL sel)
696 {
697 if (!cls || !sel) return nil;
698
699 return class_getInstanceMethod(cls->getMeta(), sel);
700 }
701
702
703 /***********************************************************************
704 * class_getInstanceVariable. Return the named instance variable.
705 **********************************************************************/
706 Ivar class_getInstanceVariable(Class cls, const char *name)
707 {
708 if (!cls || !name) return nil;
709
710 return _class_getVariable(cls, name);
711 }
712
713
714 /***********************************************************************
715 * class_getClassVariable. Return the named class variable.
716 **********************************************************************/
717 Ivar class_getClassVariable(Class cls, const char *name)
718 {
719 if (!cls) return nil;
720
721 return class_getInstanceVariable(cls->ISA(), name);
722 }
723
724
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 **********************************************************************/
730 BREAKPOINT_FUNCTION(
731 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
732 );
733
734
735 /***********************************************************************
736 * class_respondsToSelector.
737 **********************************************************************/
738 BOOL class_respondsToMethod(Class cls, SEL sel)
739 {
740 OBJC_WARN_DEPRECATED;
741
742 return class_respondsToSelector(cls, sel);
743 }
744
745
746 BOOL class_respondsToSelector(Class cls, SEL sel)
747 {
748 return class_respondsToSelector_inst(cls, sel, nil);
749 }
750
751
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)
755 {
756 IMP imp;
757
758 if (!sel || !cls) return NO;
759
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*/);
764 return bool(imp);
765 }
766
767
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)
774 {
775 OBJC_WARN_DEPRECATED;
776
777 // No one responds to zero!
778 if (!sel) {
779 __objc_error(cls, "invalid selector (null)");
780 }
781
782 return class_getMethodImplementation(cls, sel);
783 }
784
785 IMP class_getMethodImplementation(Class cls, SEL sel)
786 {
787 IMP imp;
788
789 if (!cls || !sel) return nil;
790
791 imp = lookUpImpOrNil(cls, sel, nil,
792 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
793
794 // Translate forwarding function to C-callable external version
795 if (!imp) {
796 return _objc_msgForward;
797 }
798
799 return imp;
800 }
801
802 #if SUPPORT_STRET
803 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
804 {
805 IMP imp = class_getMethodImplementation(cls, sel);
806
807 // Translate forwarding function to struct-returning version
808 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
809 return (IMP)&_objc_msgForward_stret;
810 }
811 return imp;
812 }
813 #endif
814
815
816 /***********************************************************************
817 * instrumentObjcMessageSends
818 **********************************************************************/
819 // Define this everywhere even if it isn't used to simplify fork() safety code.
820 spinlock_t objcMsgLogLock;
821
822 #if !SUPPORT_MESSAGE_LOGGING
823
824 void instrumentObjcMessageSends(BOOL flag)
825 {
826 }
827
828 #else
829
830 bool objcMsgLogEnabled = false;
831 static int objcMsgLogFD = -1;
832
833 bool logMessageSend(bool isClassMethod,
834 const char *objectsClass,
835 const char *implementingClass,
836 SEL selector)
837 {
838 char buf[ 1024 ];
839
840 // Create/open the log file
841 if (objcMsgLogFD == (-1))
842 {
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;
848 objcMsgLogFD = -1;
849 return true;
850 }
851 }
852
853 // Make the log entry
854 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
855 isClassMethod ? '+' : '-',
856 objectsClass,
857 implementingClass,
858 sel_getName(selector));
859
860 objcMsgLogLock.lock();
861 write (objcMsgLogFD, buf, strlen(buf));
862 objcMsgLogLock.unlock();
863
864 // Tell caller to not cache the method
865 return false;
866 }
867
868 void instrumentObjcMessageSends(BOOL flag)
869 {
870 bool enable = flag;
871
872 // Shortcut NOP
873 if (objcMsgLogEnabled == enable)
874 return;
875
876 // If enabling, flush all method caches so we get some traces
877 if (enable)
878 _objc_flush_caches(Nil);
879
880 // Sync our log file
881 if (objcMsgLogFD != -1)
882 fsync (objcMsgLogFD);
883
884 objcMsgLogEnabled = enable;
885 }
886
887 // SUPPORT_MESSAGE_LOGGING
888 #endif
889
890
891 Class _calloc_class(size_t size)
892 {
893 return (Class) calloc(1, size);
894 }
895
896 Class class_getSuperclass(Class cls)
897 {
898 if (!cls) return nil;
899 return cls->superclass;
900 }
901
902 BOOL class_isMetaClass(Class cls)
903 {
904 if (!cls) return NO;
905 return cls->isMetaClass();
906 }
907
908
909 size_t class_getInstanceSize(Class cls)
910 {
911 if (!cls) return 0;
912 return cls->alignedInstanceSize();
913 }
914
915
916 /***********************************************************************
917 * method_getNumberOfArguments.
918 **********************************************************************/
919 unsigned int method_getNumberOfArguments(Method m)
920 {
921 if (!m) return 0;
922 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
923 }
924
925
926 void method_getReturnType(Method m, char *dst, size_t dst_len)
927 {
928 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
929 }
930
931
932 char * method_copyReturnType(Method m)
933 {
934 return encoding_copyReturnType(method_getTypeEncoding(m));
935 }
936
937
938 void method_getArgumentType(Method m, unsigned int index,
939 char *dst, size_t dst_len)
940 {
941 encoding_getArgumentType(method_getTypeEncoding(m),
942 index, dst, dst_len);
943 }
944
945
946 char * method_copyArgumentType(Method m, unsigned int index)
947 {
948 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
949 }
950
951
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 **********************************************************************/
959 id
960 _objc_constructOrFree(id bytes, Class cls)
961 {
962 assert(cls->hasCxxCtor()); // for performance, not correctness
963
964 id obj = object_cxxConstructFromClass(bytes, cls);
965 if (!obj) free(bytes);
966
967 return obj;
968 }
969
970
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 **********************************************************************/
978 unsigned
979 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
980 id *results, unsigned num_requested)
981 {
982 unsigned num_allocated;
983 if (!cls) return 0;
984
985 size_t size = cls->instanceSize(extraBytes);
986
987 num_allocated =
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);
992 }
993
994 // Construct each object, and delete any that fail construction.
995
996 unsigned shift = 0;
997 bool ctor = cls->hasCxxCtor();
998 for (unsigned i = 0; i < num_allocated; i++) {
999 id obj = results[i];
1000 obj->initIsa(cls); // fixme allow nonpointer
1001 if (ctor) obj = _objc_constructOrFree(obj, cls);
1002
1003 if (obj) {
1004 results[i-shift] = obj;
1005 } else {
1006 shift++;
1007 }
1008 }
1009
1010 return num_allocated - shift;
1011 }
1012
1013
1014 /***********************************************************************
1015 * inform_duplicate. Complain about duplicate class implementations.
1016 **********************************************************************/
1017 void
1018 inform_duplicate(const char *name, Class oldCls, Class newCls)
1019 {
1020 #if TARGET_OS_WIN32
1021 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1022 ("Class %s is implemented in two different images.", name);
1023 #else
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() : "??";
1028
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);
1033 #endif
1034 }
1035
1036
1037 const char *
1038 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
1039 unsigned int count)
1040 {
1041 char *result;
1042 unsigned int i;
1043 if (count == 0) return strdup("");
1044
1045 #if DEBUG
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, ','));
1053 }
1054 #endif
1055
1056 size_t len = 0;
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;
1062 }
1063 }
1064
1065 result = (char *)malloc(len + 1);
1066 char *s = result;
1067 for (i = 0; i < count; i++) {
1068 if (attrs[i].value) {
1069 size_t namelen = strlen(attrs[i].name);
1070 if (namelen > 1) {
1071 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
1072 } else {
1073 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
1074 }
1075 }
1076 }
1077
1078 // remove trailing ',' if any
1079 if (s > result) s[-1] = '\0';
1080
1081 return result;
1082 }
1083
1084 /*
1085 Property attribute string format:
1086
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
1093
1094 Grammar:
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: [^,]*
1102
1103 */
1104 static unsigned int
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)
1111 {
1112 if (!attrs) return 0;
1113
1114 #if DEBUG
1115 const char *attrsend = attrs + strlen(attrs);
1116 #endif
1117 unsigned int attrcount = 0;
1118
1119 while (*attrs) {
1120 // Find the next comma-separated attribute
1121 const char *start = attrs;
1122 const char *end = start + strcspn(attrs, ",");
1123
1124 // Move attrs past this attribute and the comma (if any)
1125 attrs = *end ? end+1 : end;
1126
1127 assert(attrs <= attrsend);
1128 assert(start <= attrsend);
1129 assert(end <= attrsend);
1130
1131 // Skip empty attribute
1132 if (start == end) continue;
1133
1134 // Process one non-empty comma-free attribute [start,end)
1135 const char *nameStart;
1136 const char *nameEnd;
1137
1138 assert(start < end);
1139 assert(*start);
1140 if (*start != '\"') {
1141 // single-char short name
1142 nameStart = start;
1143 nameEnd = start+1;
1144 start++;
1145 }
1146 else {
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
1153 }
1154
1155 // Process one possibly-empty comma-free attribute value [start,end)
1156 const char *valueStart;
1157 const char *valueEnd;
1158
1159 assert(start <= end);
1160
1161 valueStart = start;
1162 valueEnd = end;
1163
1164 bool more = (*fn)(attrcount, ctx1, ctx2,
1165 nameStart, nameEnd-nameStart,
1166 valueStart, valueEnd-valueStart);
1167 attrcount++;
1168 if (!more) break;
1169 }
1170
1171 return attrcount;
1172 }
1173
1174
1175 static bool
1176 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1177 const char *name, size_t nlen, const char *value, size_t vlen)
1178 {
1179 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1180 char **sp = (char **)ctxs;
1181
1182 objc_property_attribute_t *a = *ap;
1183 char *s = *sp;
1184
1185 a->name = s;
1186 memcpy(s, name, nlen);
1187 s += nlen;
1188 *s++ = '\0';
1189
1190 a->value = s;
1191 memcpy(s, value, vlen);
1192 s += vlen;
1193 *s++ = '\0';
1194
1195 a++;
1196
1197 *ap = a;
1198 *sp = s;
1199
1200 return YES;
1201 }
1202
1203
1204 objc_property_attribute_t *
1205 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1206 {
1207 if (!attrs) {
1208 if (outCount) *outCount = 0;
1209 return nil;
1210 }
1211
1212 // Result size:
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;
1218 const char *s;
1219 for (s = attrs; s && *s; s++) {
1220 if (*s == ',') attrcount++;
1221 }
1222
1223 size_t size =
1224 attrcount * sizeof(objc_property_attribute_t) +
1225 sizeof(objc_property_attribute_t) +
1226 strlen(attrs) +
1227 attrcount * 2;
1228 objc_property_attribute_t *result = (objc_property_attribute_t *)
1229 calloc(size, 1);
1230
1231 objc_property_attribute_t *ra = result;
1232 char *rs = (char *)(ra+attrcount+1);
1233
1234 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1235
1236 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1237 assert((uint8_t *)rs <= (uint8_t *)result+size);
1238
1239 if (attrcount == 0) {
1240 free(result);
1241 result = nil;
1242 }
1243
1244 if (outCount) *outCount = attrcount;
1245 return result;
1246 }
1247
1248
1249 static bool
1250 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1251 const char *name, size_t nlen, const char *value, size_t vlen)
1252 {
1253 const char *query = (char *)ctxa;
1254 char **resultp = (char **)ctxs;
1255
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';
1260 *resultp = result;
1261 return NO;
1262 }
1263
1264 return YES;
1265 }
1266
1267 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1268 {
1269 char *result = nil;
1270
1271 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);
1272
1273 return result;
1274 }