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