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