2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* OSMetaClass.cpp created by gvdl on Fri 1998-11-17 */
32 #include <libkern/OSReturn.h>
34 #include <libkern/c++/OSMetaClass.h>
35 #include <libkern/c++/OSObject.h>
36 #include <libkern/c++/OSKext.h>
38 #include <libkern/c++/OSCollectionIterator.h>
39 #include <libkern/c++/OSDictionary.h>
40 #include <libkern/c++/OSArray.h>
41 #include <libkern/c++/OSSet.h>
42 #include <libkern/c++/OSSymbol.h>
43 #include <libkern/c++/OSNumber.h>
44 #include <libkern/c++/OSSerialize.h>
46 #include <libkern/c++/OSLib.h>
47 #include <libkern/OSAtomic.h>
49 #include <IOKit/IOLib.h>
51 #include <IOKit/IOKitDebug.h>
56 #include <sys/systm.h>
57 #include <mach/mach_types.h>
58 #include <kern/locks.h>
59 #include <kern/clock.h>
60 #include <kern/thread_call.h>
61 #include <kern/host.h>
62 #include <mach/mach_interface.h>
67 #endif /* PRAGMA_MARK */
68 /*********************************************************************
70 *********************************************************************/
74 #pragma mark Internal constants & data structs
75 #endif /* PRAGMA_MARK */
76 /*********************************************************************
77 * Internal constants & data structs
78 *********************************************************************/
79 OSKextLogSpec kOSMetaClassLogSpec
=
80 kOSKextLogErrorLevel
|
82 kOSKextLogKextBookkeepingFlag
;
85 kCompletedBootstrap
= 0,
87 kMakingDictionaries
= 2
88 } sBootstrapState
= kNoDictionaries
;
90 static const int kClassCapacityIncrement
= 40;
91 static const int kKModCapacityIncrement
= 10;
92 static OSDictionary
* sAllClassesDict
;
93 static unsigned int sDeepestClass
;
94 IOLock
* sAllClassesLock
= NULL
;
95 IOLock
* sInstancesLock
= NULL
;
98 * While loading a kext and running all its constructors to register
99 * all OSMetaClass classes, the classes are queued up here. Only one
100 * kext can be in flight at a time, guarded by sStalledClassesLock
102 static struct StalledData
{
103 const char * kextIdentifier
;
105 unsigned int capacity
;
107 OSMetaClass
** classes
;
109 IOLock
* sStalledClassesLock
= NULL
;
111 struct ExpansionData
{
112 OSOrderedSet
* instances
;
116 IOTrackingQueue
* tracking
;
122 #pragma mark OSMetaClassBase
123 #endif /* PRAGMA_MARK */
124 /*********************************************************************
126 *********************************************************************/
128 #if APPLE_KEXT_VTABLE_PADDING
129 /*********************************************************************
130 * Reserved vtable functions.
131 *********************************************************************/
132 #if defined(__arm64__) || defined(__arm__)
134 OSMetaClassBase::_RESERVEDOSMetaClassBase0()
136 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 0);
139 OSMetaClassBase::_RESERVEDOSMetaClassBase1()
141 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 1);
144 OSMetaClassBase::_RESERVEDOSMetaClassBase2()
146 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 2);
149 OSMetaClassBase::_RESERVEDOSMetaClassBase3()
151 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 3);
153 #endif /* defined(__arm64__) || defined(__arm__) */
155 // As these slots are used move them up inside the #if above
157 OSMetaClassBase::_RESERVEDOSMetaClassBase4()
159 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 4);
162 OSMetaClassBase::_RESERVEDOSMetaClassBase5()
164 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 5);
167 OSMetaClassBase::_RESERVEDOSMetaClassBase6()
169 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 6);
173 /*********************************************************************
174 *********************************************************************/
176 #if defined(__arm__) || defined(__arm64__)
178 #if defined(HAS_APPLE_PAC)
180 #endif /* defined(HAS_APPLE_PAC) */
183 * IHI0059A "C++ Application Binary Interface Standard for the ARM 64 - bit Architecture":
185 * 3.2.1 Representation of pointer to member function The generic C++ ABI [GC++ABI]
186 * specifies that a pointer to member function is a pair of words <ptr, adj>. The
187 * least significant bit of ptr discriminates between (0) the address of a non-
188 * virtual member function and (1) the offset in the class's virtual table of the
189 * address of a virtual function. This encoding cannot work for the AArch64
190 * instruction set where the architecture reserves all bits of code addresses. This
191 * ABI specifies that adj contains twice the this adjustment, plus 1 if the member
192 * function is virtual. The least significant bit of adj then makes exactly the
193 * same discrimination as the least significant bit of ptr does for Itanium. A
194 * pointer to member function is NULL when ptr = 0 and the least significant bit of
198 OSMetaClassBase::_ptf_t
199 #if defined(HAS_APPLE_PAC) && \
200 __has_feature(ptrauth_member_function_pointer_type_discrimination)
201 OSMetaClassBase::_ptmf2ptf(const OSMetaClassBase
*self
__attribute__((unused
)),
202 void (OSMetaClassBase::*func
)(void))
204 OSMetaClassBase::_ptmf2ptf(const OSMetaClassBase
*self
,
205 void (OSMetaClassBase::*func
)(void))
213 void (OSMetaClassBase::*fIn
)(void);
221 #if defined(HAS_APPLE_PAC) && \
222 __has_feature(ptrauth_member_function_pointer_type_discrimination)
223 // Authenticate 'pfn' using the member function pointer type discriminator
224 // and resign it as a C function pointer. 'pfn' can point to either a
225 // non-virtual function or a virtual member function thunk.
226 // It can also be NULL.
228 pfn
= ptrauth_auth_and_resign(pfn
, ptrauth_key_function_pointer
,
229 ptrauth_type_discriminator(__typeof__(func
)),
230 ptrauth_key_function_pointer
,
231 ptrauth_function_pointer_type_discriminator(_ptf_t
));
235 if (map
.pTMF
.delta
& 1) {
238 const OSMetaClassBase
*fObj
;
243 // Virtual member function so dereference table
244 #if defined(HAS_APPLE_PAC)
245 // The entity hash is stored in the top 32-bits of the vtable offset of a
246 // member function pointer.
247 uint32_t entity_hash
= ((uintptr_t)pfn
) >> 32;
248 pfn
= (_ptf_t
)(((uintptr_t) pfn
) & 0xFFFFFFFF);
250 #if __has_builtin(__builtin_get_vtable_pointer)
251 const _ptf_t
*vtablep
=
252 (const _ptf_t
*)__builtin_get_vtable_pointer(u
.fObj
);
254 // Authenticate the vtable pointer.
255 const _ptf_t
*vtablep
= ptrauth_auth_data(*u
.vtablep
,
256 ptrauth_key_cxx_vtable_pointer
, 0);
258 // Calculate the address of the vtable entry.
259 _ptf_t
*vtentryp
= (_ptf_t
*)(((uintptr_t)vtablep
) + (uintptr_t)pfn
);
260 // Load the pointer from the vtable entry.
263 // Finally, resign the vtable entry as a function pointer.
264 uintptr_t auth_data
= ptrauth_blend_discriminator(vtentryp
, entity_hash
);
265 pfn
= ptrauth_auth_and_resign(pfn
, ptrauth_key_function_pointer
,
266 auth_data
, ptrauth_key_function_pointer
,
267 ptrauth_function_pointer_type_discriminator(_ptf_t
));
268 #else /* defined(HAS_APPLE_PAC) */
269 pfn
= *(_ptf_t
*)(((uintptr_t)*u
.vtablep
) + (uintptr_t)pfn
);
270 #endif /* !defined(HAS_APPLE_PAC) */
273 // Not virtual, i.e. plain member func
279 #endif /* defined(__arm__) || defined(__arm64__) */
280 /*********************************************************************
281 * These used to be inline in the header but gcc didn't believe us
282 * Now we MUST pull the inline out at least until the compiler is
285 * Helper inlines for runtime type preprocessor macros
286 *********************************************************************/
288 /*********************************************************************
289 *********************************************************************/
291 OSMetaClassBase::safeMetaCast(
292 const OSMetaClassBase
* me
,
293 const OSMetaClass
* toType
)
295 return (me
)? me
->metaCast(toType
) : NULL
;
298 /// A helper function to crash with a kernel panic.
299 __attribute__((cold
, not_tail_called
, noreturn
))
301 panic_crash_fail_cast(const OSMetaClassBase
*me
,
302 const OSMetaClass
*toType
)
304 panic("Unexpected cast fail: from %p to %p", me
, toType
);
305 __builtin_unreachable();
309 OSMetaClassBase::requiredMetaCast(
310 const OSMetaClassBase
* me
,
311 const OSMetaClass
* toType
)
316 OSMetaClassBase
*tmp
= safeMetaCast(me
, toType
);
318 panic_crash_fail_cast(me
, toType
);
323 /*********************************************************************
324 *********************************************************************/
326 OSMetaClassBase::checkTypeInst(
327 const OSMetaClassBase
* inst
,
328 const OSMetaClassBase
* typeinst
)
330 const OSMetaClass
* toType
= OSTypeIDInst(typeinst
);
331 return typeinst
&& inst
&& (NULL
!= inst
->metaCast(toType
));
334 /*********************************************************************
335 *********************************************************************/
340 sAllClassesLock
= IOLockAlloc();
341 sStalledClassesLock
= IOLockAlloc();
342 sInstancesLock
= IOLockAlloc();
345 #if APPLE_KEXT_VTABLE_PADDING
346 /*********************************************************************
347 * If you need this slot you had better setup an IOCTL style interface.
348 * 'Cause the whole kernel world depends on OSMetaClassBase and YOU
349 * CANT change the VTABLE size ever.
350 *********************************************************************/
352 OSMetaClassBase::_RESERVEDOSMetaClassBase7()
354 panic("OSMetaClassBase::_RESERVEDOSMetaClassBase%d called.", 7);
358 /*********************************************************************
359 *********************************************************************/
360 OSMetaClassBase::OSMetaClassBase()
364 /*********************************************************************
365 *********************************************************************/
366 OSMetaClassBase::~OSMetaClassBase()
370 thisVTable
= (void **) this;
371 *thisVTable
= (void *) -1UL;
374 /*********************************************************************
375 *********************************************************************/
377 OSMetaClassBase::isEqualTo(const OSMetaClassBase
* anObj
) const
379 return this == anObj
;
382 /*********************************************************************
383 *********************************************************************/
385 OSMetaClassBase::metaCast(const OSMetaClass
* toMeta
) const
387 return toMeta
->checkMetaCast(this);
390 /*********************************************************************
391 *********************************************************************/
393 OSMetaClassBase::metaCast(const OSSymbol
* toMetaSymb
) const
395 return OSMetaClass::checkMetaCastWithName(toMetaSymb
, this);
398 /*********************************************************************
399 *********************************************************************/
401 OSMetaClassBase::metaCast(const OSString
* toMetaStr
) const
403 const OSSymbol
* tempSymb
= OSSymbol::withString(toMetaStr
);
404 OSMetaClassBase
* ret
= NULL
;
406 ret
= metaCast(tempSymb
);
412 /*********************************************************************
413 *********************************************************************/
415 OSMetaClassBase::metaCast(const char * toMetaCStr
) const
417 const OSSymbol
* tempSymb
= OSSymbol::withCString(toMetaCStr
);
418 OSMetaClassBase
* ret
= NULL
;
420 ret
= metaCast(tempSymb
);
427 #pragma mark OSMetaClassMeta
428 #endif /* PRAGMA_MARK */
429 /*********************************************************************
430 * OSMetaClassMeta - the bootstrap metaclass of OSMetaClass
431 *********************************************************************/
432 class OSMetaClassMeta
: public OSMetaClass
436 OSObject
* alloc() const;
438 OSMetaClassMeta::OSMetaClassMeta()
439 : OSMetaClass("OSMetaClass", NULL
, sizeof(OSMetaClass
))
443 OSMetaClassMeta::alloc() const
448 static OSMetaClassMeta sOSMetaClassMeta
;
450 const OSMetaClass
* const OSMetaClass::metaClass
= &sOSMetaClassMeta
;
452 OSMetaClass::getMetaClass() const
454 return &sOSMetaClassMeta
;
458 #pragma mark OSMetaClass
459 #endif /* PRAGMA_MARK */
460 /*********************************************************************
462 *********************************************************************/
464 #if APPLE_KEXT_VTABLE_PADDING
465 /*********************************************************************
466 * Reserved functions.
467 *********************************************************************/
469 OSMetaClass::_RESERVEDOSMetaClass0()
471 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 0);
474 OSMetaClass::_RESERVEDOSMetaClass1()
476 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 1);
479 OSMetaClass::_RESERVEDOSMetaClass2()
481 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 2);
484 OSMetaClass::_RESERVEDOSMetaClass3()
486 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 3);
489 OSMetaClass::_RESERVEDOSMetaClass4()
491 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 4);
494 OSMetaClass::_RESERVEDOSMetaClass5()
496 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 5);
499 OSMetaClass::_RESERVEDOSMetaClass6()
501 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 6);
504 OSMetaClass::_RESERVEDOSMetaClass7()
506 panic("OSMetaClass::_RESERVEDOSMetaClass%d called", 7);
510 /*********************************************************************
511 *********************************************************************/
513 OSMetaClassLogErrorForKext(
517 const char * message
= NULL
;
520 case kOSReturnSuccess
:
522 case kOSMetaClassNoInit
: // xxx - never returned; logged at fail site
523 message
= "OSMetaClass: preModLoad() wasn't called (runtime internal error).";
525 case kOSMetaClassNoDicts
:
526 message
= "OSMetaClass: Allocation failure for OSMetaClass internal dictionaries.";
528 case kOSMetaClassNoKModSet
:
529 message
= "OSMetaClass: Allocation failure for internal kext recording set/set missing.";
531 case kOSMetaClassNoInsKModSet
:
532 message
= "OSMetaClass: Failed to record class in kext.";
534 case kOSMetaClassDuplicateClass
:
535 message
= "OSMetaClass: Duplicate class encountered.";
537 case kOSMetaClassNoSuper
: // xxx - never returned
538 message
= "OSMetaClass: Can't associate a class with its superclass.";
540 case kOSMetaClassInstNoSuper
: // xxx - never returned
541 message
= "OSMetaClass: Instance construction error; unknown superclass.";
543 case kOSMetaClassNoKext
:
544 message
= "OSMetaClass: Kext not found for metaclass.";
546 case kOSMetaClassInternal
:
548 message
= "OSMetaClass: Runtime internal error.";
553 OSKextLog(aKext
, kOSMetaClassLogSpec
, "%s", message
);
559 OSMetaClass::logError(OSReturn error
)
561 OSMetaClassLogErrorForKext(error
, NULL
);
564 /*********************************************************************
565 * The core constructor for a MetaClass (defined with this name always
566 * but within the scope of its represented class).
568 * MetaClass constructors are invoked in OSRuntimeInitializeCPP(),
569 * in between calls to OSMetaClass::preModLoad(), which sets up for
570 * registration, and OSMetaClass::postModLoad(), which actually
571 * records all the class/kext relationships of the new MetaClasses.
572 *********************************************************************/
574 OSMetaClass::OSMetaClass(
575 const char * inClassName
,
576 const OSMetaClass
* inSuperClass
,
577 unsigned int inClassSize
)
580 classSize
= inClassSize
;
581 superClassLink
= inSuperClass
;
583 reserved
= IONew(ExpansionData
, 1);
584 bzero(reserved
, sizeof(ExpansionData
));
586 uint32_t numSiteQs
= 0;
587 if ((this == &OSSymbol ::gMetaClass
)
588 || (this == &OSString ::gMetaClass
)
589 || (this == &OSNumber ::gMetaClass
)
590 || (this == &OSString ::gMetaClass
)
591 || (this == &OSData ::gMetaClass
)
592 || (this == &OSDictionary::gMetaClass
)
593 || (this == &OSArray ::gMetaClass
)
594 || (this == &OSSet ::gMetaClass
)) {
598 reserved
->tracking
= IOTrackingQueueAlloc(inClassName
, (uintptr_t) this,
599 inClassSize
, 0, kIOTrackingQueueTypeAlloc
,
603 /* Hack alert: We are just casting inClassName and storing it in
604 * an OSString * instance variable. This may be because you can't
605 * create C++ objects in static constructors, but I really don't know!
607 className
= (const OSSymbol
*)inClassName
;
609 // sStalledClassesLock taken in preModLoad
611 /* There's no way we can look up the kext here, unfortunately.
613 OSKextLog(/* kext */ NULL
, kOSMetaClassLogSpec
,
614 "OSMetaClass: preModLoad() wasn't called for class %s "
615 "(runtime internal error).",
617 } else if (!sStalled
->result
) {
618 // Grow stalled array if neccessary
619 if (sStalled
->count
>= sStalled
->capacity
) {
620 OSMetaClass
**oldStalled
= sStalled
->classes
;
621 int oldSize
= sStalled
->capacity
* sizeof(OSMetaClass
*);
622 int newSize
= oldSize
623 + kKModCapacityIncrement
* sizeof(OSMetaClass
*);
625 sStalled
->classes
= (OSMetaClass
**)kalloc_tag(newSize
, VM_KERN_MEMORY_OSKEXT
);
626 if (!sStalled
->classes
) {
627 sStalled
->classes
= oldStalled
;
628 sStalled
->result
= kOSMetaClassNoTempData
;
632 sStalled
->capacity
+= kKModCapacityIncrement
;
633 memmove(sStalled
->classes
, oldStalled
, oldSize
);
634 kfree(oldStalled
, oldSize
);
635 OSMETA_ACCUMSIZE(((size_t)newSize
) - ((size_t)oldSize
));
638 sStalled
->classes
[sStalled
->count
++] = this;
642 OSMetaClass::OSMetaClass(
643 const char * inClassName
,
644 const OSMetaClass
* inSuperClass
,
645 unsigned int inClassSize
,
647 const char * zone_name
,
648 zone_create_flags_t zflags
) : OSMetaClass(inClassName
, inSuperClass
,
651 if (!(kIOTracking
& gIOKitDebug
)) {
652 *inZone
= zone_create(zone_name
, inClassSize
,
653 (zone_create_flags_t
) (ZC_ZFREE_CLEARMEM
| zflags
));
657 /*********************************************************************
658 *********************************************************************/
659 OSMetaClass::~OSMetaClass()
661 OSKext
* myKext
= reserved
->kext
; // do not release
663 /* Hack alert: 'className' is a C string during early C++ init, and
664 * is converted to a real OSSymbol only when we record the OSKext in
665 * OSMetaClass::postModLoad(). So only do this bit if we have an OSKext.
666 * We can't safely cast or check 'className'.
668 * Also, release className *after* calling into the kext,
669 * as removeClass() may access className.
671 IOLockLock(sAllClassesLock
);
672 if (sAllClassesDict
) {
674 sAllClassesDict
->removeObject(className
);
676 sAllClassesDict
->removeObject((const char *)className
);
679 IOLockUnlock(sAllClassesLock
);
682 if (myKext
->removeClass(this) != kOSReturnSuccess
) {
683 // xxx - what can we do?
685 className
->release();
688 // sStalledClassesLock taken in preModLoad
692 /* First pass find class in stalled list. If we find it that means
693 * we started C++ init with constructors but now we're tearing down
694 * because of some failure.
696 for (i
= 0; i
< sStalled
->count
; i
++) {
697 if (this == sStalled
->classes
[i
]) {
702 /* Remove this metaclass from the stalled list so postModLoad() doesn't
703 * try to register it.
705 if (i
< sStalled
->count
) {
707 if (i
< sStalled
->count
) {
708 memmove(&sStalled
->classes
[i
], &sStalled
->classes
[i
+ 1],
709 (sStalled
->count
- i
) * sizeof(OSMetaClass
*));
714 IOTrackingQueueFree(reserved
->tracking
);
716 IODelete(reserved
, ExpansionData
, 1);
719 /*********************************************************************
721 *********************************************************************/
723 OSMetaClass::retain() const
727 OSMetaClass::release() const
731 OSMetaClass::release(__unused
int when
) const
735 OSMetaClass::taggedRetain(__unused
const void * tag
) const
739 OSMetaClass::taggedRelease(__unused
const void * tag
) const
743 OSMetaClass::taggedRelease(__unused
const void * tag
, __unused
const int when
) const
747 OSMetaClass::getRetainCount() const
752 /*********************************************************************
753 *********************************************************************/
755 OSMetaClass::getClassName() const
760 return className
->getCStringNoCopy();
762 /*********************************************************************
763 *********************************************************************/
765 OSMetaClass::getClassNameSymbol() const
769 /*********************************************************************
770 *********************************************************************/
772 OSMetaClass::getClassSize() const
777 /*********************************************************************
778 *********************************************************************/
780 OSMetaClass::preModLoad(const char * kextIdentifier
)
782 IOLockLock(sStalledClassesLock
);
784 assert(sStalled
== NULL
);
785 sStalled
= (StalledData
*)kalloc_tag(sizeof(*sStalled
), VM_KERN_MEMORY_OSKEXT
);
787 sStalled
->classes
= (OSMetaClass
**)
788 kalloc_tag(kKModCapacityIncrement
* sizeof(OSMetaClass
*), VM_KERN_MEMORY_OSKEXT
);
789 if (!sStalled
->classes
) {
790 kfree(sStalled
, sizeof(*sStalled
));
793 OSMETA_ACCUMSIZE((kKModCapacityIncrement
* sizeof(OSMetaClass
*)) +
796 sStalled
->result
= kOSReturnSuccess
;
797 sStalled
->capacity
= kKModCapacityIncrement
;
799 sStalled
->kextIdentifier
= kextIdentifier
;
800 bzero(sStalled
->classes
, kKModCapacityIncrement
* sizeof(OSMetaClass
*));
803 // keep sStalledClassesLock locked until postModLoad
808 /*********************************************************************
809 *********************************************************************/
811 OSMetaClass::checkModLoad(void * loadHandle
)
813 return sStalled
&& loadHandle
== sStalled
&&
814 sStalled
->result
== kOSReturnSuccess
;
817 /*********************************************************************
818 *********************************************************************/
820 OSMetaClass::postModLoad(void * loadHandle
)
822 OSReturn result
= kOSReturnSuccess
;
823 OSSymbol
* myKextName
= NULL
;// must release
824 OSKext
* myKext
= NULL
;// must release
826 if (!sStalled
|| loadHandle
!= sStalled
) {
827 result
= kOSMetaClassInternal
;
831 if (sStalled
->result
) {
832 result
= sStalled
->result
;
834 switch (sBootstrapState
) {
835 case kNoDictionaries
:
836 sBootstrapState
= kMakingDictionaries
;
837 // No break; fall through
838 [[clang::fallthrough]];
840 case kMakingDictionaries
:
841 sAllClassesDict
= OSDictionary::withCapacity(kClassCapacityIncrement
);
842 if (!sAllClassesDict
) {
843 result
= kOSMetaClassNoDicts
;
846 sAllClassesDict
->setOptions(OSCollection::kSort
, OSCollection::kSort
);
848 // No break; fall through
849 [[clang::fallthrough]];
851 case kCompletedBootstrap
:
854 myKextName
= const_cast<OSSymbol
*>(OSSymbol::withCStringNoCopy(
855 sStalled
->kextIdentifier
));
857 if (!sStalled
->count
) {
858 break; // Nothing to do so just get out
861 myKext
= OSKext::lookupKextWithIdentifier(myKextName
);
863 result
= kOSMetaClassNoKext
;
865 /* Log this error here so we can include the kext name.
867 OSKextLog(/* kext */ NULL
, kOSMetaClassLogSpec
,
868 "OSMetaClass: Can't record classes for kext %s - kext not found.",
869 sStalled
->kextIdentifier
);
873 /* First pass checking classes aren't already loaded. If any already
874 * exist, we don't register any, and so we don't technically have
875 * to do any C++ teardown.
877 * Hack alert: me->className has been a C string until now.
878 * We only release the OSSymbol if we store the kext.
880 IOLockLock(sAllClassesLock
);
881 for (i
= 0; i
< sStalled
->count
; i
++) {
882 const OSMetaClass
* me
= sStalled
->classes
[i
];
883 OSMetaClass
* orig
= OSDynamicCast(OSMetaClass
,
884 sAllClassesDict
->getObject((const char *)me
->className
));
887 /* Log this error here so we can include the class name.
888 * xxx - we should look up the other kext that defines the class
890 #if defined(XNU_TARGET_OS_OSX)
891 OSKextLog(myKext
, kOSMetaClassLogSpec
,
894 #endif /* defined(XNU_TARGET_OS_OSX) */
895 "OSMetaClass: Kext %s class %s is a duplicate;"
896 "kext %s already has a class by that name.",
897 sStalled
->kextIdentifier
, (const char *)me
->className
,
898 ((OSKext
*)orig
->reserved
->kext
)->getIdentifierCString());
899 result
= kOSMetaClassDuplicateClass
;
902 unsigned int depth
= 1;
903 while ((me
= me
->superClassLink
)) {
906 if (depth
> sDeepestClass
) {
907 sDeepestClass
= depth
;
910 IOLockUnlock(sAllClassesLock
);
912 /* Bail if we didn't go through the entire list of new classes
913 * (if we hit a duplicate).
915 if (i
!= sStalled
->count
) {
919 // Second pass symbolling strings and inserting classes in dictionary
920 IOLockLock(sAllClassesLock
);
921 for (i
= 0; i
< sStalled
->count
; i
++) {
922 OSMetaClass
* me
= sStalled
->classes
[i
];
924 /* Hack alert: me->className has been a C string until now.
925 * We only release the OSSymbol in ~OSMetaClass()
926 * if we set the reference to the kext.
929 OSSymbol::withCStringNoCopy((const char *)me
->className
);
931 // xxx - I suppose if these fail we're going to panic soon....
932 sAllClassesDict
->setObject(me
->className
, me
);
934 /* Do not retain the kext object here.
936 me
->reserved
->kext
= myKext
;
938 result
= myKext
->addClass(me
, sStalled
->count
);
939 if (result
!= kOSReturnSuccess
) {
940 /* OSKext::addClass() logs with kOSMetaClassNoInsKModSet. */
945 IOLockUnlock(sAllClassesLock
);
946 sBootstrapState
= kCompletedBootstrap
;
951 result
= kOSMetaClassInternal
;
957 /* Don't call logError() for success or the conditions logged above
958 * or by called function.
960 if (result
!= kOSReturnSuccess
&&
961 result
!= kOSMetaClassNoInsKModSet
&&
962 result
!= kOSMetaClassDuplicateClass
&&
963 result
!= kOSMetaClassNoKext
) {
964 OSMetaClassLogErrorForKext(result
, myKext
);
967 OSSafeReleaseNULL(myKextName
);
968 OSSafeReleaseNULL(myKext
);
971 OSMETA_ACCUMSIZE(-(sStalled
->capacity
* sizeof(OSMetaClass
*) +
973 kfree(sStalled
->classes
, sStalled
->capacity
* sizeof(OSMetaClass
*));
974 kfree(sStalled
, sizeof(*sStalled
));
978 IOLockUnlock(sStalledClassesLock
);
984 /*********************************************************************
985 *********************************************************************/
987 OSMetaClass::instanceConstructed() const
989 // if ((0 == OSIncrementAtomic(&(((OSMetaClass *) this)->instanceCount))) && superClassLink)
990 if ((0 == OSIncrementAtomic(&instanceCount
)) && superClassLink
) {
991 superClassLink
->instanceConstructed();
995 /*********************************************************************
996 *********************************************************************/
998 OSMetaClass::instanceDestructed() const
1000 if ((1 == OSDecrementAtomic(&instanceCount
)) && superClassLink
) {
1001 superClassLink
->instanceDestructed();
1004 if (((int)instanceCount
) < 0) {
1005 OSKext
* myKext
= reserved
->kext
;
1007 OSKextLog(myKext
, kOSMetaClassLogSpec
,
1008 // xxx - this phrasing is rather cryptic
1009 "OSMetaClass: Class %s - bad retain (%d)",
1010 getClassName(), instanceCount
);
1014 /*********************************************************************
1015 *********************************************************************/
1017 OSMetaClass::modHasInstance(const char * kextIdentifier
)
1019 bool result
= false;
1020 OSKext
* theKext
= NULL
; // must release
1022 theKext
= OSKext::lookupKextWithIdentifier(kextIdentifier
);
1027 result
= theKext
->hasOSMetaClassInstances();
1030 OSSafeReleaseNULL(theKext
);
1034 /*********************************************************************
1035 *********************************************************************/
1037 OSMetaClass::reportModInstances(const char * kextIdentifier
)
1039 OSKext::reportOSMetaClassInstances(kextIdentifier
,
1040 kOSKextLogExplicitLevel
);
1043 /*********************************************************************
1044 *********************************************************************/
1047 OSMetaClass::addInstance(const OSObject
* instance
, bool super
) const
1050 IOLockLock(sInstancesLock
);
1053 if (!reserved
->instances
) {
1054 reserved
->instances
= OSOrderedSet::withCapacity(16);
1055 if (superClassLink
) {
1056 superClassLink
->addInstance(reserved
->instances
, true);
1059 reserved
->instances
->setLastObject(instance
);
1062 IOLockUnlock(sInstancesLock
);
1067 OSMetaClass::removeInstance(const OSObject
* instance
, bool super
) const
1070 IOLockLock(sInstancesLock
);
1073 if (reserved
->instances
) {
1074 reserved
->instances
->removeObject(instance
);
1075 if (0 == reserved
->instances
->getCount()) {
1076 if (superClassLink
) {
1077 superClassLink
->removeInstance(reserved
->instances
, true);
1079 IOLockLock(sAllClassesLock
);
1080 reserved
->instances
->release();
1081 reserved
->instances
= NULL
;
1082 IOLockUnlock(sAllClassesLock
);
1087 IOLockUnlock(sInstancesLock
);
1092 OSMetaClass::applyToInstances(OSOrderedSet
* set
,
1093 OSMetaClassInstanceApplierFunction applier
,
1096 enum { kLocalDepth
= 24 };
1097 unsigned int _nextIndex
[kLocalDepth
];
1098 OSOrderedSet
* _sets
[kLocalDepth
];
1099 unsigned int * nextIndex
= &_nextIndex
[0];
1100 OSOrderedSet
** sets
= &_sets
[0];
1102 OSOrderedSet
* childSet
;
1103 unsigned int maxDepth
;
1108 maxDepth
= sDeepestClass
;
1109 if (maxDepth
> kLocalDepth
) {
1110 nextIndex
= IONew(typeof(nextIndex
[0]), maxDepth
);
1111 sets
= IONew(typeof(sets
[0]), maxDepth
);
1117 while (!done
&& (obj
= set
->getObject(idx
++))) {
1118 if ((childSet
= OSDynamicCast(OSOrderedSet
, obj
))) {
1119 if (level
>= maxDepth
) {
1123 nextIndex
[level
] = idx
;
1129 done
= (*applier
)(obj
, context
);
1132 if (!done
&& level
) {
1135 idx
= nextIndex
[level
];
1141 if (maxDepth
> kLocalDepth
) {
1142 IODelete(nextIndex
, typeof(nextIndex
[0]), maxDepth
);
1143 IODelete(sets
, typeof(sets
[0]), maxDepth
);
1148 OSMetaClass::applyToInstances(OSMetaClassInstanceApplierFunction applier
,
1149 void * context
) const
1151 IOLockLock(sInstancesLock
);
1152 if (reserved
->instances
) {
1153 applyToInstances(reserved
->instances
, applier
, context
);
1155 IOLockUnlock(sInstancesLock
);
1159 OSMetaClass::applyToInstancesOfClassName(
1160 const OSSymbol
* name
,
1161 OSMetaClassInstanceApplierFunction applier
,
1165 OSOrderedSet
* set
= NULL
;
1167 IOLockLock(sAllClassesLock
);
1169 && (meta
= (OSMetaClass
*) sAllClassesDict
->getObject(name
))
1170 && (set
= meta
->reserved
->instances
)) {
1173 IOLockUnlock(sAllClassesLock
);
1179 IOLockLock(sInstancesLock
);
1180 applyToInstances(set
, applier
, context
);
1181 IOLockUnlock(sInstancesLock
);
1185 /*********************************************************************
1186 *********************************************************************/
1188 OSMetaClass::considerUnloads()
1190 OSKext::considerUnloads();
1193 /*********************************************************************
1194 *********************************************************************/
1196 OSMetaClass::removeClasses(OSCollection
* metaClasses
)
1198 OSCollectionIterator
* classIterator
;
1199 OSMetaClass
* checkClass
;
1202 classIterator
= OSCollectionIterator::withCollection(metaClasses
);
1203 if (!classIterator
) {
1207 IOLockLock(sAllClassesLock
);
1211 while ((checkClass
= (OSMetaClass
*)classIterator
->getNextObject())
1212 && !checkClass
->getInstanceCount()
1213 && !checkClass
->reserved
->retain
) {
1218 classIterator
->reset();
1219 while ((checkClass
= (OSMetaClass
*)classIterator
->getNextObject())) {
1220 sAllClassesDict
->removeObject(checkClass
->className
);
1225 IOLockUnlock(sAllClassesLock
);
1226 OSSafeReleaseNULL(classIterator
);
1232 /*********************************************************************
1233 *********************************************************************/
1235 OSMetaClass::getMetaClassWithName(const OSSymbol
* name
)
1237 OSMetaClass
* retMeta
= NULL
;
1243 IOLockLock(sAllClassesLock
);
1244 if (sAllClassesDict
) {
1245 retMeta
= (OSMetaClass
*) sAllClassesDict
->getObject(name
);
1247 IOLockUnlock(sAllClassesLock
);
1252 /*********************************************************************
1253 *********************************************************************/
1255 OSMetaClass::copyMetaClassWithName(const OSSymbol
* name
)
1257 const OSMetaClass
* meta
;
1264 IOLockLock(sAllClassesLock
);
1265 if (sAllClassesDict
) {
1266 meta
= (OSMetaClass
*) sAllClassesDict
->getObject(name
);
1268 OSIncrementAtomic(&meta
->reserved
->retain
);
1271 IOLockUnlock(sAllClassesLock
);
1276 /*********************************************************************
1277 *********************************************************************/
1279 OSMetaClass::releaseMetaClass() const
1281 OSDecrementAtomic(&reserved
->retain
);
1284 /*********************************************************************
1285 *********************************************************************/
1287 OSMetaClass::allocClassWithName(const OSSymbol
* name
)
1289 const OSMetaClass
* meta
;
1293 meta
= copyMetaClassWithName(name
);
1295 result
= meta
->alloc();
1296 meta
->releaseMetaClass();
1302 /*********************************************************************
1303 *********************************************************************/
1305 OSMetaClass::allocClassWithName(const OSString
* name
)
1307 const OSSymbol
* tmpKey
= OSSymbol::withString(name
);
1308 OSObject
* result
= allocClassWithName(tmpKey
);
1313 /*********************************************************************
1314 *********************************************************************/
1316 OSMetaClass::allocClassWithName(const char * name
)
1318 const OSSymbol
* tmpKey
= OSSymbol::withCStringNoCopy(name
);
1319 OSObject
* result
= allocClassWithName(tmpKey
);
1325 /*********************************************************************
1326 *********************************************************************/
1328 OSMetaClass::checkMetaCastWithName(
1329 const OSSymbol
* name
,
1330 const OSMetaClassBase
* in
)
1332 OSMetaClassBase
* result
= NULL
;
1334 const OSMetaClass
* const meta
= getMetaClassWithName(name
);
1337 result
= meta
->checkMetaCast(in
);
1343 /*********************************************************************
1344 *********************************************************************/
1347 checkMetaCastWithName(
1348 const OSString
* name
,
1349 const OSMetaClassBase
* in
)
1351 const OSSymbol
* tmpKey
= OSSymbol::withString(name
);
1352 OSMetaClassBase
* result
= checkMetaCastWithName(tmpKey
, in
);
1358 /*********************************************************************
1359 *********************************************************************/
1361 OSMetaClass::checkMetaCastWithName(
1363 const OSMetaClassBase
* in
)
1365 const OSSymbol
* tmpKey
= OSSymbol::withCStringNoCopy(name
);
1366 OSMetaClassBase
* result
= checkMetaCastWithName(tmpKey
, in
);
1372 /*********************************************************************
1373 * OSMetaClass::checkMetaCast()
1374 * Check to see if the 'check' object has this object in its metaclass chain.
1375 * Returns check if it is indeed a kind of the current meta class, 0 otherwise.
1377 * Generally this method is not invoked directly but is used to implement
1378 * the OSMetaClassBase::metaCast member function.
1380 * See also OSMetaClassBase::metaCast
1381 *********************************************************************/
1383 OSMetaClass::checkMetaCast(
1384 const OSMetaClassBase
* check
) const
1386 const OSMetaClass
* const toMeta
= this;
1387 const OSMetaClass
* fromMeta
;
1389 for (fromMeta
= check
->getMetaClass();; fromMeta
= fromMeta
->superClassLink
) {
1390 if (toMeta
== fromMeta
) {
1391 return const_cast<OSMetaClassBase
*>(check
); // Discard const
1393 if (!fromMeta
->superClassLink
) {
1401 /*********************************************************************
1402 *********************************************************************/
1405 OSMetaClass::reservedCalled(int ind
) const
1407 const char * cname
= className
->getCStringNoCopy();
1408 panic("%s::_RESERVED%s%d called.", cname
, cname
, ind
);
1411 /*********************************************************************
1412 *********************************************************************/
1415 OSMetaClass::getSuperClass() const
1417 return superClassLink
;
1420 /*********************************************************************
1421 *********************************************************************/
1423 OSMetaClass::getKmodName() const
1425 OSKext
* myKext
= reserved
? reserved
->kext
: NULL
;
1427 return myKext
->getIdentifier();
1429 return OSSymbol::withCStringNoCopy("unknown");
1432 /*********************************************************************
1433 *********************************************************************/
1435 OSMetaClass::getKext() const
1437 return reserved
? reserved
->kext
: NULL
;
1440 /*********************************************************************
1441 *********************************************************************/
1443 OSMetaClass::getInstanceCount() const
1445 return instanceCount
;
1448 /*********************************************************************
1449 *********************************************************************/
1452 OSMetaClass::printInstanceCounts()
1454 OSCollectionIterator
* classes
;
1455 OSSymbol
* className
;
1458 IOLockLock(sAllClassesLock
);
1459 classes
= OSCollectionIterator::withCollection(sAllClassesDict
);
1462 while ((className
= (OSSymbol
*)classes
->getNextObject())) {
1463 meta
= (OSMetaClass
*)sAllClassesDict
->getObject(className
);
1466 printf("%24s count: %03d x 0x%03x = 0x%06x\n",
1467 className
->getCStringNoCopy(),
1468 meta
->getInstanceCount(),
1469 meta
->getClassSize(),
1470 meta
->getInstanceCount() * meta
->getClassSize());
1474 IOLockUnlock(sAllClassesLock
);
1478 /*********************************************************************
1479 *********************************************************************/
1481 OSMetaClass::getClassDictionary()
1483 panic("OSMetaClass::getClassDictionary() is obsoleted.\n");
1487 /*********************************************************************
1488 *********************************************************************/
1490 OSMetaClass::serialize(__unused OSSerialize
* s
) const
1492 panic("OSMetaClass::serialize(): Obsoleted\n");
1496 /*********************************************************************
1497 *********************************************************************/
1500 OSMetaClass::serializeClassDictionary(OSDictionary
* serializeDictionary
)
1502 OSDictionary
* classDict
= NULL
;
1504 IOLockLock(sAllClassesLock
);
1506 classDict
= OSDictionary::withCapacity(sAllClassesDict
->getCount());
1512 OSCollectionIterator
* classes
;
1513 const OSSymbol
* className
;
1515 classes
= OSCollectionIterator::withCollection(sAllClassesDict
);
1520 while ((className
= (const OSSymbol
*)classes
->getNextObject())) {
1521 const OSMetaClass
* meta
;
1524 meta
= (OSMetaClass
*)sAllClassesDict
->getObject(className
);
1525 count
= OSNumber::withNumber(meta
->getInstanceCount(), 32);
1527 classDict
->setObject(className
, count
);
1533 serializeDictionary
->setObject("Classes", classDict
);
1537 OSSafeReleaseNULL(classDict
);
1539 IOLockUnlock(sAllClassesLock
);
1545 /*********************************************************************
1546 *********************************************************************/
1551 OSMetaClass::trackedNew(size_t size
)
1555 mem
= (typeof(mem
))kalloc_tag_bt(size
+ sizeof(IOTracking
), VM_KERN_MEMORY_LIBKERN
);
1561 memset(mem
, 0, size
+ sizeof(IOTracking
));
1564 OSIVAR_ACCUMSIZE(size
);
1570 OSMetaClass::trackedDelete(void * instance
, size_t size
)
1572 IOTracking
* mem
= (typeof(mem
))instance
; mem
--;
1574 kfree(mem
, size
+ sizeof(IOTracking
));
1575 OSIVAR_ACCUMSIZE(-size
);
1579 OSMetaClass::trackedInstance(OSObject
* instance
) const
1581 IOTracking
* mem
= (typeof(mem
))instance
; mem
--;
1583 return IOTrackingAdd(reserved
->tracking
, mem
, classSize
, false, VM_KERN_MEMORY_NONE
);
1587 OSMetaClass::trackedFree(OSObject
* instance
) const
1589 IOTracking
* mem
= (typeof(mem
))instance
; mem
--;
1591 return IOTrackingRemove(reserved
->tracking
, mem
, classSize
);
1595 OSMetaClass::trackedAccumSize(OSObject
* instance
, size_t size
) const
1597 IOTracking
* mem
= (typeof(mem
))instance
; mem
--;
1599 return IOTrackingAccumSize(reserved
->tracking
, mem
, size
);
1603 OSMetaClass::getTracking() const
1605 return reserved
->tracking
;
1608 #endif /* IOTRACKING */