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