]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-class.mm
objc4-750.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 * Information about multi-thread support:
165 *
166 * Since we do not lock many operations which walk the superclass, method
167 * and ivar chains, these chains must remain intact once a class is published
168 * by inserting it into the class hashtable. All modifications must be
169 * atomic so that someone walking these chains will always geta valid
170 * result.
171 ***********************************************************************/
172
173
174
175 /***********************************************************************
176 * object_getClass.
177 * Locking: None. If you add locking, tell gdb (rdar://7516456).
178 **********************************************************************/
179 Class object_getClass(id obj)
180 {
181 if (obj) return obj->getIsa();
182 else return Nil;
183 }
184
185
186 /***********************************************************************
187 * object_setClass.
188 **********************************************************************/
189 Class object_setClass(id obj, Class cls)
190 {
191 if (!obj) return nil;
192
193 // Prevent a deadlock between the weak reference machinery
194 // and the +initialize machinery by ensuring that no
195 // weakly-referenced object has an un-+initialized isa.
196 // Unresolved future classes are not so protected.
197 if (!cls->isFuture() && !cls->isInitialized()) {
198 _class_initialize(_class_getNonMetaClass(cls, nil));
199 }
200
201 return obj->changeIsa(cls);
202 }
203
204
205 /***********************************************************************
206 * object_isClass.
207 **********************************************************************/
208 BOOL object_isClass(id obj)
209 {
210 if (!obj) return NO;
211 return obj->isClass();
212 }
213
214
215 /***********************************************************************
216 * object_getClassName.
217 **********************************************************************/
218 const char *object_getClassName(id obj)
219 {
220 return class_getName(obj ? obj->getIsa() : nil);
221 }
222
223
224 /***********************************************************************
225 * object_getMethodImplementation.
226 **********************************************************************/
227 IMP object_getMethodImplementation(id obj, SEL name)
228 {
229 Class cls = (obj ? obj->getIsa() : nil);
230 return class_getMethodImplementation(cls, name);
231 }
232
233
234 /***********************************************************************
235 * object_getMethodImplementation_stret.
236 **********************************************************************/
237 #if SUPPORT_STRET
238 IMP object_getMethodImplementation_stret(id obj, SEL name)
239 {
240 Class cls = (obj ? obj->getIsa() : nil);
241 return class_getMethodImplementation_stret(cls, name);
242 }
243 #endif
244
245
246 static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
247 {
248 if (!layout) return NO;
249
250 ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
251 uint8_t byte;
252 while ((byte = *layout++)) {
253 unsigned skips = (byte >> 4);
254 unsigned scans = (byte & 0x0F);
255 index += skips;
256 if (index > ivar_index) return NO;
257 index += scans;
258 if (index > ivar_index) return YES;
259 }
260 return NO;
261 }
262
263
264 /***********************************************************************
265 * _class_lookUpIvar
266 * Given an object and an ivar in it, look up some data about that ivar:
267 * - its offset
268 * - its memory management behavior
269 * The ivar is assumed to be word-aligned and of of object type.
270 **********************************************************************/
271 static void
272 _class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
273 objc_ivar_memory_management_t& memoryManagement)
274 {
275 ivarOffset = ivar_getOffset(ivar);
276
277 // Look for ARC variables and ARC-style weak.
278
279 // Preflight the hasAutomaticIvars check
280 // because _class_getClassForIvar() may need to take locks.
281 bool hasAutomaticIvars = NO;
282 for (Class c = cls; c; c = c->superclass) {
283 if (c->hasAutomaticIvars()) {
284 hasAutomaticIvars = YES;
285 break;
286 }
287 }
288
289 if (hasAutomaticIvars) {
290 Class ivarCls = _class_getClassForIvar(cls, ivar);
291 if (ivarCls->hasAutomaticIvars()) {
292 // ARC layout bitmaps encode the class's own ivars only.
293 // Use alignedInstanceStart() because unaligned bytes at the start
294 // of this class's ivars are not represented in the layout bitmap.
295 ptrdiff_t localOffset =
296 ivarOffset - ivarCls->alignedInstanceStart();
297
298 if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
299 memoryManagement = objc_ivar_memoryStrong;
300 return;
301 }
302
303 if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
304 memoryManagement = objc_ivar_memoryWeak;
305 return;
306 }
307
308 // Unretained is only for true ARC classes.
309 if (ivarCls->isARC()) {
310 memoryManagement = objc_ivar_memoryUnretained;
311 return;
312 }
313 }
314 }
315
316 memoryManagement = objc_ivar_memoryUnknown;
317 }
318
319
320 /***********************************************************************
321 * _class_getIvarMemoryManagement
322 * SPI for KVO and others to decide what memory management to use
323 * when setting instance variables directly.
324 **********************************************************************/
325 objc_ivar_memory_management_t
326 _class_getIvarMemoryManagement(Class cls, Ivar ivar)
327 {
328 ptrdiff_t offset;
329 objc_ivar_memory_management_t memoryManagement;
330 _class_lookUpIvar(cls, ivar, offset, memoryManagement);
331 return memoryManagement;
332 }
333
334
335 static ALWAYS_INLINE
336 void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
337 {
338 if (!obj || !ivar || obj->isTaggedPointer()) return;
339
340 ptrdiff_t offset;
341 objc_ivar_memory_management_t memoryManagement;
342 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
343
344 if (memoryManagement == objc_ivar_memoryUnknown) {
345 if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
346 else memoryManagement = objc_ivar_memoryUnretained;
347 }
348
349 id *location = (id *)((char *)obj + offset);
350
351 switch (memoryManagement) {
352 case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
353 case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
354 case objc_ivar_memoryUnretained: *location = value; break;
355 case objc_ivar_memoryUnknown: _objc_fatal("impossible");
356 }
357 }
358
359 void object_setIvar(id obj, Ivar ivar, id value)
360 {
361 return _object_setIvar(obj, ivar, value, false /*not strong default*/);
362 }
363
364 void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
365 {
366 return _object_setIvar(obj, ivar, value, true /*strong default*/);
367 }
368
369
370 id object_getIvar(id obj, Ivar ivar)
371 {
372 if (!obj || !ivar || obj->isTaggedPointer()) return nil;
373
374 ptrdiff_t offset;
375 objc_ivar_memory_management_t memoryManagement;
376 _class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
377
378 id *location = (id *)((char *)obj + offset);
379
380 if (memoryManagement == objc_ivar_memoryWeak) {
381 return objc_loadWeak(location);
382 } else {
383 return *location;
384 }
385 }
386
387
388 static ALWAYS_INLINE
389 Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
390 bool assumeStrong)
391 {
392 Ivar ivar = nil;
393
394 if (obj && name && !obj->isTaggedPointer()) {
395 if ((ivar = _class_getVariable(obj->ISA(), name))) {
396 _object_setIvar(obj, ivar, (id)value, assumeStrong);
397 }
398 }
399 return ivar;
400 }
401
402 Ivar object_setInstanceVariable(id obj, const char *name, void *value)
403 {
404 return _object_setInstanceVariable(obj, name, value, false);
405 }
406
407 Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
408 void *value)
409 {
410 return _object_setInstanceVariable(obj, name, value, true);
411 }
412
413
414 Ivar object_getInstanceVariable(id obj, const char *name, void **value)
415 {
416 if (obj && name && !obj->isTaggedPointer()) {
417 Ivar ivar;
418 if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
419 if (value) *value = (void *)object_getIvar(obj, ivar);
420 return ivar;
421 }
422 }
423 if (value) *value = nil;
424 return nil;
425 }
426
427
428 /***********************************************************************
429 * object_cxxDestructFromClass.
430 * Call C++ destructors on obj, starting with cls's
431 * dtor method (if any) followed by superclasses' dtors (if any),
432 * stopping at cls's dtor (if any).
433 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
434 **********************************************************************/
435 static void object_cxxDestructFromClass(id obj, Class cls)
436 {
437 void (*dtor)(id);
438
439 // Call cls's dtor first, then superclasses's dtors.
440
441 for ( ; cls; cls = cls->superclass) {
442 if (!cls->hasCxxDtor()) return;
443 dtor = (void(*)(id))
444 lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
445 if (dtor != (void(*)(id))_objc_msgForward_impcache) {
446 if (PrintCxxCtors) {
447 _objc_inform("CXX: calling C++ destructors for class %s",
448 cls->nameForLogging());
449 }
450 (*dtor)(obj);
451 }
452 }
453 }
454
455
456 /***********************************************************************
457 * object_cxxDestruct.
458 * Call C++ destructors on obj, if any.
459 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
460 **********************************************************************/
461 void object_cxxDestruct(id obj)
462 {
463 if (!obj) return;
464 if (obj->isTaggedPointer()) return;
465 object_cxxDestructFromClass(obj, obj->ISA());
466 }
467
468
469 /***********************************************************************
470 * object_cxxConstructFromClass.
471 * Recursively call C++ constructors on obj, starting with base class's
472 * ctor method (if any) followed by subclasses' ctors (if any), stopping
473 * at cls's ctor (if any).
474 * Does not check cls->hasCxxCtor(). The caller should preflight that.
475 * Returns self if construction succeeded.
476 * Returns nil if some constructor threw an exception. The exception is
477 * caught and discarded. Any partial construction is destructed.
478 * Uses methodListLock and cacheUpdateLock. The caller must hold neither.
479 *
480 * .cxx_construct returns id. This really means:
481 * return self: construction succeeded
482 * return nil: construction failed because a C++ constructor threw an exception
483 **********************************************************************/
484 id
485 object_cxxConstructFromClass(id obj, Class cls)
486 {
487 assert(cls->hasCxxCtor()); // required for performance, not correctness
488
489 id (*ctor)(id);
490 Class supercls;
491
492 supercls = cls->superclass;
493
494 // Call superclasses' ctors first, if any.
495 if (supercls && supercls->hasCxxCtor()) {
496 bool ok = object_cxxConstructFromClass(obj, supercls);
497 if (!ok) return nil; // some superclass's ctor failed - give up
498 }
499
500 // Find this class's ctor, if any.
501 ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
502 if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
503
504 // Call this class's ctor.
505 if (PrintCxxCtors) {
506 _objc_inform("CXX: calling C++ constructors for class %s",
507 cls->nameForLogging());
508 }
509 if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
510
511 // This class's ctor was called and failed.
512 // Call superclasses's dtors to clean up.
513 if (supercls) object_cxxDestructFromClass(obj, supercls);
514 return nil;
515 }
516
517
518 /***********************************************************************
519 * fixupCopiedIvars
520 * Fix up ARC strong and ARC-style weak variables
521 * after oldObject was memcpy'd to newObject.
522 **********************************************************************/
523 void fixupCopiedIvars(id newObject, id oldObject)
524 {
525 for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
526 if (cls->hasAutomaticIvars()) {
527 // Use alignedInstanceStart() because unaligned bytes at the start
528 // of this class's ivars are not represented in the layout bitmap.
529 size_t instanceStart = cls->alignedInstanceStart();
530
531 const uint8_t *strongLayout = class_getIvarLayout(cls);
532 if (strongLayout) {
533 id *newPtr = (id *)((char*)newObject + instanceStart);
534 unsigned char byte;
535 while ((byte = *strongLayout++)) {
536 unsigned skips = (byte >> 4);
537 unsigned scans = (byte & 0x0F);
538 newPtr += skips;
539 while (scans--) {
540 // ensure strong references are properly retained.
541 id value = *newPtr++;
542 if (value) objc_retain(value);
543 }
544 }
545 }
546
547 const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
548 // fix up weak references if any.
549 if (weakLayout) {
550 id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
551 unsigned char byte;
552 while ((byte = *weakLayout++)) {
553 unsigned skips = (byte >> 4);
554 unsigned weaks = (byte & 0x0F);
555 newPtr += skips, oldPtr += skips;
556 while (weaks--) {
557 objc_copyWeak(newPtr, oldPtr);
558 ++newPtr, ++oldPtr;
559 }
560 }
561 }
562 }
563 }
564 }
565
566
567 /***********************************************************************
568 * _class_resolveClassMethod
569 * Call +resolveClassMethod, looking for a method to be added to class cls.
570 * cls should be a metaclass.
571 * Does not check if the method already exists.
572 **********************************************************************/
573 static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
574 {
575 assert(cls->isMetaClass());
576
577 if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
578 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
579 {
580 // Resolver not implemented.
581 return;
582 }
583
584 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
585 bool resolved = msg(_class_getNonMetaClass(cls, inst),
586 SEL_resolveClassMethod, sel);
587
588 // Cache the result (good or bad) so the resolver doesn't fire next time.
589 // +resolveClassMethod adds to self->ISA() a.k.a. cls
590 IMP imp = lookUpImpOrNil(cls, sel, inst,
591 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
592
593 if (resolved && PrintResolving) {
594 if (imp) {
595 _objc_inform("RESOLVE: method %c[%s %s] "
596 "dynamically resolved to %p",
597 cls->isMetaClass() ? '+' : '-',
598 cls->nameForLogging(), sel_getName(sel), imp);
599 }
600 else {
601 // Method resolver didn't add anything?
602 _objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
603 ", but no new implementation of %c[%s %s] was found",
604 cls->nameForLogging(), sel_getName(sel),
605 cls->isMetaClass() ? '+' : '-',
606 cls->nameForLogging(), sel_getName(sel));
607 }
608 }
609 }
610
611
612 /***********************************************************************
613 * _class_resolveInstanceMethod
614 * Call +resolveInstanceMethod, looking for a method to be added to class cls.
615 * cls may be a metaclass or a non-meta class.
616 * Does not check if the method already exists.
617 **********************************************************************/
618 static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
619 {
620 if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
621 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
622 {
623 // Resolver not implemented.
624 return;
625 }
626
627 BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
628 bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
629
630 // Cache the result (good or bad) so the resolver doesn't fire next time.
631 // +resolveInstanceMethod adds to self a.k.a. cls
632 IMP imp = lookUpImpOrNil(cls, sel, inst,
633 NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
634
635 if (resolved && PrintResolving) {
636 if (imp) {
637 _objc_inform("RESOLVE: method %c[%s %s] "
638 "dynamically resolved to %p",
639 cls->isMetaClass() ? '+' : '-',
640 cls->nameForLogging(), sel_getName(sel), imp);
641 }
642 else {
643 // Method resolver didn't add anything?
644 _objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
645 ", but no new implementation of %c[%s %s] was found",
646 cls->nameForLogging(), sel_getName(sel),
647 cls->isMetaClass() ? '+' : '-',
648 cls->nameForLogging(), sel_getName(sel));
649 }
650 }
651 }
652
653
654 /***********************************************************************
655 * _class_resolveMethod
656 * Call +resolveClassMethod or +resolveInstanceMethod.
657 * Returns nothing; any result would be potentially out-of-date already.
658 * Does not check if the method already exists.
659 **********************************************************************/
660 void _class_resolveMethod(Class cls, SEL sel, id inst)
661 {
662 if (! cls->isMetaClass()) {
663 // try [cls resolveInstanceMethod:sel]
664 _class_resolveInstanceMethod(cls, sel, inst);
665 }
666 else {
667 // try [nonMetaClass resolveClassMethod:sel]
668 // and [cls resolveInstanceMethod:sel]
669 _class_resolveClassMethod(cls, sel, inst);
670 if (!lookUpImpOrNil(cls, sel, inst,
671 NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
672 {
673 _class_resolveInstanceMethod(cls, sel, inst);
674 }
675 }
676 }
677
678
679 /***********************************************************************
680 * class_getClassMethod. Return the class method for the specified
681 * class and selector.
682 **********************************************************************/
683 Method class_getClassMethod(Class cls, SEL sel)
684 {
685 if (!cls || !sel) return nil;
686
687 return class_getInstanceMethod(cls->getMeta(), sel);
688 }
689
690
691 /***********************************************************************
692 * class_getInstanceVariable. Return the named instance variable.
693 **********************************************************************/
694 Ivar class_getInstanceVariable(Class cls, const char *name)
695 {
696 if (!cls || !name) return nil;
697
698 return _class_getVariable(cls, name);
699 }
700
701
702 /***********************************************************************
703 * class_getClassVariable. Return the named class variable.
704 **********************************************************************/
705 Ivar class_getClassVariable(Class cls, const char *name)
706 {
707 if (!cls) return nil;
708
709 return class_getInstanceVariable(cls->ISA(), name);
710 }
711
712
713 /***********************************************************************
714 * gdb_objc_class_changed
715 * Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
716 * Does nothing; gdb sets a breakpoint on it.
717 **********************************************************************/
718 BREAKPOINT_FUNCTION(
719 void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
720 );
721
722
723 /***********************************************************************
724 * class_respondsToSelector.
725 **********************************************************************/
726 BOOL class_respondsToMethod(Class cls, SEL sel)
727 {
728 OBJC_WARN_DEPRECATED;
729
730 return class_respondsToSelector(cls, sel);
731 }
732
733
734 BOOL class_respondsToSelector(Class cls, SEL sel)
735 {
736 return class_respondsToSelector_inst(cls, sel, nil);
737 }
738
739
740 // inst is an instance of cls or a subclass thereof, or nil if none is known.
741 // Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
742 bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
743 {
744 IMP imp;
745
746 if (!sel || !cls) return NO;
747
748 // Avoids +initialize because it historically did so.
749 // We're not returning a callable IMP anyway.
750 imp = lookUpImpOrNil(cls, sel, inst,
751 NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
752 return bool(imp);
753 }
754
755
756 /***********************************************************************
757 * class_getMethodImplementation.
758 * Returns the IMP that would be invoked if [obj sel] were sent,
759 * where obj is an instance of class cls.
760 **********************************************************************/
761 IMP class_lookupMethod(Class cls, SEL sel)
762 {
763 OBJC_WARN_DEPRECATED;
764
765 // No one responds to zero!
766 if (!sel) {
767 __objc_error(cls, "invalid selector (null)");
768 }
769
770 return class_getMethodImplementation(cls, sel);
771 }
772
773 IMP class_getMethodImplementation(Class cls, SEL sel)
774 {
775 IMP imp;
776
777 if (!cls || !sel) return nil;
778
779 imp = lookUpImpOrNil(cls, sel, nil,
780 YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
781
782 // Translate forwarding function to C-callable external version
783 if (!imp) {
784 return _objc_msgForward;
785 }
786
787 return imp;
788 }
789
790 #if SUPPORT_STRET
791 IMP class_getMethodImplementation_stret(Class cls, SEL sel)
792 {
793 IMP imp = class_getMethodImplementation(cls, sel);
794
795 // Translate forwarding function to struct-returning version
796 if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
797 return (IMP)&_objc_msgForward_stret;
798 }
799 return imp;
800 }
801 #endif
802
803
804 /***********************************************************************
805 * instrumentObjcMessageSends
806 **********************************************************************/
807 // Define this everywhere even if it isn't used to simplify fork() safety code.
808 spinlock_t objcMsgLogLock;
809
810 #if !SUPPORT_MESSAGE_LOGGING
811
812 void instrumentObjcMessageSends(BOOL flag)
813 {
814 }
815
816 #else
817
818 bool objcMsgLogEnabled = false;
819 static int objcMsgLogFD = -1;
820
821 bool logMessageSend(bool isClassMethod,
822 const char *objectsClass,
823 const char *implementingClass,
824 SEL selector)
825 {
826 char buf[ 1024 ];
827
828 // Create/open the log file
829 if (objcMsgLogFD == (-1))
830 {
831 snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
832 objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
833 if (objcMsgLogFD < 0) {
834 // no log file - disable logging
835 objcMsgLogEnabled = false;
836 objcMsgLogFD = -1;
837 return true;
838 }
839 }
840
841 // Make the log entry
842 snprintf(buf, sizeof(buf), "%c %s %s %s\n",
843 isClassMethod ? '+' : '-',
844 objectsClass,
845 implementingClass,
846 sel_getName(selector));
847
848 objcMsgLogLock.lock();
849 write (objcMsgLogFD, buf, strlen(buf));
850 objcMsgLogLock.unlock();
851
852 // Tell caller to not cache the method
853 return false;
854 }
855
856 void instrumentObjcMessageSends(BOOL flag)
857 {
858 bool enable = flag;
859
860 // Shortcut NOP
861 if (objcMsgLogEnabled == enable)
862 return;
863
864 // If enabling, flush all method caches so we get some traces
865 if (enable)
866 _objc_flush_caches(Nil);
867
868 // Sync our log file
869 if (objcMsgLogFD != -1)
870 fsync (objcMsgLogFD);
871
872 objcMsgLogEnabled = enable;
873 }
874
875 // SUPPORT_MESSAGE_LOGGING
876 #endif
877
878
879 Class _calloc_class(size_t size)
880 {
881 return (Class) calloc(1, size);
882 }
883
884 Class class_getSuperclass(Class cls)
885 {
886 if (!cls) return nil;
887 return cls->superclass;
888 }
889
890 BOOL class_isMetaClass(Class cls)
891 {
892 if (!cls) return NO;
893 return cls->isMetaClass();
894 }
895
896
897 size_t class_getInstanceSize(Class cls)
898 {
899 if (!cls) return 0;
900 return cls->alignedInstanceSize();
901 }
902
903
904 /***********************************************************************
905 * method_getNumberOfArguments.
906 **********************************************************************/
907 unsigned int method_getNumberOfArguments(Method m)
908 {
909 if (!m) return 0;
910 return encoding_getNumberOfArguments(method_getTypeEncoding(m));
911 }
912
913
914 void method_getReturnType(Method m, char *dst, size_t dst_len)
915 {
916 encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
917 }
918
919
920 char * method_copyReturnType(Method m)
921 {
922 return encoding_copyReturnType(method_getTypeEncoding(m));
923 }
924
925
926 void method_getArgumentType(Method m, unsigned int index,
927 char *dst, size_t dst_len)
928 {
929 encoding_getArgumentType(method_getTypeEncoding(m),
930 index, dst, dst_len);
931 }
932
933
934 char * method_copyArgumentType(Method m, unsigned int index)
935 {
936 return encoding_copyArgumentType(method_getTypeEncoding(m), index);
937 }
938
939
940 /***********************************************************************
941 * _objc_constructOrFree
942 * Call C++ constructors, and free() if they fail.
943 * bytes->isa must already be set.
944 * cls must have cxx constructors.
945 * Returns the object, or nil.
946 **********************************************************************/
947 id
948 _objc_constructOrFree(id bytes, Class cls)
949 {
950 assert(cls->hasCxxCtor()); // for performance, not correctness
951
952 id obj = object_cxxConstructFromClass(bytes, cls);
953 if (!obj) free(bytes);
954
955 return obj;
956 }
957
958
959 /***********************************************************************
960 * _class_createInstancesFromZone
961 * Batch-allocating version of _class_createInstanceFromZone.
962 * Attempts to allocate num_requested objects, each with extraBytes.
963 * Returns the number of allocated objects (possibly zero), with
964 * the allocated pointers in *results.
965 **********************************************************************/
966 unsigned
967 _class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
968 id *results, unsigned num_requested)
969 {
970 unsigned num_allocated;
971 if (!cls) return 0;
972
973 size_t size = cls->instanceSize(extraBytes);
974
975 num_allocated =
976 malloc_zone_batch_malloc((malloc_zone_t *)(zone ? zone : malloc_default_zone()),
977 size, (void**)results, num_requested);
978 for (unsigned i = 0; i < num_allocated; i++) {
979 bzero(results[i], size);
980 }
981
982 // Construct each object, and delete any that fail construction.
983
984 unsigned shift = 0;
985 bool ctor = cls->hasCxxCtor();
986 for (unsigned i = 0; i < num_allocated; i++) {
987 id obj = results[i];
988 obj->initIsa(cls); // fixme allow nonpointer
989 if (ctor) obj = _objc_constructOrFree(obj, cls);
990
991 if (obj) {
992 results[i-shift] = obj;
993 } else {
994 shift++;
995 }
996 }
997
998 return num_allocated - shift;
999 }
1000
1001
1002 /***********************************************************************
1003 * inform_duplicate. Complain about duplicate class implementations.
1004 **********************************************************************/
1005 void
1006 inform_duplicate(const char *name, Class oldCls, Class newCls)
1007 {
1008 #if TARGET_OS_WIN32
1009 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1010 ("Class %s is implemented in two different images.", name);
1011 #else
1012 const header_info *oldHeader = _headerForClass(oldCls);
1013 const header_info *newHeader = _headerForClass(newCls);
1014 const char *oldName = oldHeader ? oldHeader->fname() : "??";
1015 const char *newName = newHeader ? newHeader->fname() : "??";
1016
1017 (DebugDuplicateClasses ? _objc_fatal : _objc_inform)
1018 ("Class %s is implemented in both %s (%p) and %s (%p). "
1019 "One of the two will be used. Which one is undefined.",
1020 name, oldName, oldCls, newName, newCls);
1021 #endif
1022 }
1023
1024
1025 const char *
1026 copyPropertyAttributeString(const objc_property_attribute_t *attrs,
1027 unsigned int count)
1028 {
1029 char *result;
1030 unsigned int i;
1031 if (count == 0) return strdup("");
1032
1033 #if DEBUG
1034 // debug build: sanitize input
1035 for (i = 0; i < count; i++) {
1036 assert(attrs[i].name);
1037 assert(strlen(attrs[i].name) > 0);
1038 assert(! strchr(attrs[i].name, ','));
1039 assert(! strchr(attrs[i].name, '"'));
1040 if (attrs[i].value) assert(! strchr(attrs[i].value, ','));
1041 }
1042 #endif
1043
1044 size_t len = 0;
1045 for (i = 0; i < count; i++) {
1046 if (attrs[i].value) {
1047 size_t namelen = strlen(attrs[i].name);
1048 if (namelen > 1) namelen += 2; // long names get quoted
1049 len += namelen + strlen(attrs[i].value) + 1;
1050 }
1051 }
1052
1053 result = (char *)malloc(len + 1);
1054 char *s = result;
1055 for (i = 0; i < count; i++) {
1056 if (attrs[i].value) {
1057 size_t namelen = strlen(attrs[i].name);
1058 if (namelen > 1) {
1059 s += sprintf(s, "\"%s\"%s,", attrs[i].name, attrs[i].value);
1060 } else {
1061 s += sprintf(s, "%s%s,", attrs[i].name, attrs[i].value);
1062 }
1063 }
1064 }
1065
1066 // remove trailing ',' if any
1067 if (s > result) s[-1] = '\0';
1068
1069 return result;
1070 }
1071
1072 /*
1073 Property attribute string format:
1074
1075 - Comma-separated name-value pairs.
1076 - Name and value may not contain ,
1077 - Name may not contain "
1078 - Value may be empty
1079 - Name is single char, value follows
1080 - OR Name is double-quoted string of 2+ chars, value follows
1081
1082 Grammar:
1083 attribute-string: \0
1084 attribute-string: name-value-pair (',' name-value-pair)*
1085 name-value-pair: unquoted-name optional-value
1086 name-value-pair: quoted-name optional-value
1087 unquoted-name: [^",]
1088 quoted-name: '"' [^",]{2,} '"'
1089 optional-value: [^,]*
1090
1091 */
1092 static unsigned int
1093 iteratePropertyAttributes(const char *attrs,
1094 bool (*fn)(unsigned int index,
1095 void *ctx1, void *ctx2,
1096 const char *name, size_t nlen,
1097 const char *value, size_t vlen),
1098 void *ctx1, void *ctx2)
1099 {
1100 if (!attrs) return 0;
1101
1102 #if DEBUG
1103 const char *attrsend = attrs + strlen(attrs);
1104 #endif
1105 unsigned int attrcount = 0;
1106
1107 while (*attrs) {
1108 // Find the next comma-separated attribute
1109 const char *start = attrs;
1110 const char *end = start + strcspn(attrs, ",");
1111
1112 // Move attrs past this attribute and the comma (if any)
1113 attrs = *end ? end+1 : end;
1114
1115 assert(attrs <= attrsend);
1116 assert(start <= attrsend);
1117 assert(end <= attrsend);
1118
1119 // Skip empty attribute
1120 if (start == end) continue;
1121
1122 // Process one non-empty comma-free attribute [start,end)
1123 const char *nameStart;
1124 const char *nameEnd;
1125
1126 assert(start < end);
1127 assert(*start);
1128 if (*start != '\"') {
1129 // single-char short name
1130 nameStart = start;
1131 nameEnd = start+1;
1132 start++;
1133 }
1134 else {
1135 // double-quoted long name
1136 nameStart = start+1;
1137 nameEnd = nameStart + strcspn(nameStart, "\",");
1138 start++; // leading quote
1139 start += nameEnd - nameStart; // name
1140 if (*start == '\"') start++; // trailing quote, if any
1141 }
1142
1143 // Process one possibly-empty comma-free attribute value [start,end)
1144 const char *valueStart;
1145 const char *valueEnd;
1146
1147 assert(start <= end);
1148
1149 valueStart = start;
1150 valueEnd = end;
1151
1152 bool more = (*fn)(attrcount, ctx1, ctx2,
1153 nameStart, nameEnd-nameStart,
1154 valueStart, valueEnd-valueStart);
1155 attrcount++;
1156 if (!more) break;
1157 }
1158
1159 return attrcount;
1160 }
1161
1162
1163 static bool
1164 copyOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1165 const char *name, size_t nlen, const char *value, size_t vlen)
1166 {
1167 objc_property_attribute_t **ap = (objc_property_attribute_t**)ctxa;
1168 char **sp = (char **)ctxs;
1169
1170 objc_property_attribute_t *a = *ap;
1171 char *s = *sp;
1172
1173 a->name = s;
1174 memcpy(s, name, nlen);
1175 s += nlen;
1176 *s++ = '\0';
1177
1178 a->value = s;
1179 memcpy(s, value, vlen);
1180 s += vlen;
1181 *s++ = '\0';
1182
1183 a++;
1184
1185 *ap = a;
1186 *sp = s;
1187
1188 return YES;
1189 }
1190
1191
1192 objc_property_attribute_t *
1193 copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
1194 {
1195 if (!attrs) {
1196 if (outCount) *outCount = 0;
1197 return nil;
1198 }
1199
1200 // Result size:
1201 // number of commas plus 1 for the attributes (upper bound)
1202 // plus another attribute for the attribute array terminator
1203 // plus strlen(attrs) for name/value string data (upper bound)
1204 // plus count*2 for the name/value string terminators (upper bound)
1205 unsigned int attrcount = 1;
1206 const char *s;
1207 for (s = attrs; s && *s; s++) {
1208 if (*s == ',') attrcount++;
1209 }
1210
1211 size_t size =
1212 attrcount * sizeof(objc_property_attribute_t) +
1213 sizeof(objc_property_attribute_t) +
1214 strlen(attrs) +
1215 attrcount * 2;
1216 objc_property_attribute_t *result = (objc_property_attribute_t *)
1217 calloc(size, 1);
1218
1219 objc_property_attribute_t *ra = result;
1220 char *rs = (char *)(ra+attrcount+1);
1221
1222 attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);
1223
1224 assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
1225 assert((uint8_t *)rs <= (uint8_t *)result+size);
1226
1227 if (attrcount == 0) {
1228 free(result);
1229 result = nil;
1230 }
1231
1232 if (outCount) *outCount = attrcount;
1233 return result;
1234 }
1235
1236
1237 static bool
1238 findOneAttribute(unsigned int index, void *ctxa, void *ctxs,
1239 const char *name, size_t nlen, const char *value, size_t vlen)
1240 {
1241 const char *query = (char *)ctxa;
1242 char **resultp = (char **)ctxs;
1243
1244 if (strlen(query) == nlen && 0 == strncmp(name, query, nlen)) {
1245 char *result = (char *)calloc(vlen+1, 1);
1246 memcpy(result, value, vlen);
1247 result[vlen] = '\0';
1248 *resultp = result;
1249 return NO;
1250 }
1251
1252 return YES;
1253 }
1254
1255 char *copyPropertyAttributeValue(const char *attrs, const char *name)
1256 {
1257 char *result = nil;
1258
1259 iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);
1260
1261 return result;
1262 }