2 * Copyright (c) 1998-2012 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@
29 * Copyright (c) 1998 Apple Inc. All rights reserved.
35 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
36 * support for mandatory and extensible security protections. This notice
37 * is included in support of clause 2.2 (b) of the Apple Public License,
42 #include <machine/machine_routines.h>
43 #include <libkern/kernel_mach_header.h>
44 #include <kern/host.h>
45 #include <security/mac_data.h>
48 #include <libkern/c++/OSContainers.h>
49 #include <libkern/c++/OSUnserialize.h>
50 #include <libkern/c++/OSKext.h>
51 #include <libkern/OSKextLibPrivate.h>
52 #include <libkern/OSDebug.h>
54 #include <IOKit/IODeviceTreeSupport.h>
55 #include <IOKit/IOService.h>
56 #include <IOKit/IOCatalogue.h>
58 #include <IOKit/IOLib.h>
59 #include <IOKit/assert.h>
62 #pragma mark Internal Declarations
64 /*********************************************************************
65 *********************************************************************/
67 IOCatalogue
* gIOCatalogue
;
68 const OSSymbol
* gIOClassKey
;
69 const OSSymbol
* gIOProbeScoreKey
;
70 const OSSymbol
* gIOModuleIdentifierKey
;
71 IORWLock
* gIOCatalogLock
;
74 #pragma mark Utility functions
78 #pragma mark IOCatalogue class implementation
80 /*********************************************************************
81 *********************************************************************/
83 #define super OSObject
84 OSDefineMetaClassAndStructors(IOCatalogue
, OSObject
)
86 static bool isModuleLoadedNoOSKextLock(OSDictionary
*theKexts
,
87 OSDictionary
*theModuleDict
);
90 /*********************************************************************
91 *********************************************************************/
92 void IOCatalogue::initialize(void)
95 OSString
* errorString
;
98 extern const char * gIOKernelConfigTables
;
100 array
= OSDynamicCast(OSArray
, OSUnserialize(gIOKernelConfigTables
, &errorString
));
101 if (!array
&& errorString
) {
102 IOLog("KernelConfigTables syntax error: %s\n",
103 errorString
->getCStringNoCopy());
104 errorString
->release();
107 gIOClassKey
= OSSymbol::withCStringNoCopy( kIOClassKey
);
108 gIOProbeScoreKey
= OSSymbol::withCStringNoCopy( kIOProbeScoreKey
);
109 gIOModuleIdentifierKey
= OSSymbol::withCStringNoCopy( kCFBundleIdentifierKey
);
111 assert( array
&& gIOClassKey
&& gIOProbeScoreKey
112 && gIOModuleIdentifierKey
);
114 gIOCatalogue
= new IOCatalogue
;
115 assert(gIOCatalogue
);
116 rc
= gIOCatalogue
->init(array
);
121 /*********************************************************************
122 * Initialize the IOCatalog object.
123 *********************************************************************/
124 OSArray
* IOCatalogue::arrayForPersonality(OSDictionary
* dict
)
126 const OSSymbol
* sym
;
128 sym
= OSDynamicCast(OSSymbol
, dict
->getObject(gIOProviderClassKey
));
129 if (!sym
) return (0);
131 return ((OSArray
*) personalities
->getObject(sym
));
134 void IOCatalogue::addPersonality(OSDictionary
* dict
)
136 const OSSymbol
* sym
;
139 sym
= OSDynamicCast(OSSymbol
, dict
->getObject(gIOProviderClassKey
));
141 arr
= (OSArray
*) personalities
->getObject(sym
);
142 if (arr
) arr
->setObject(dict
);
145 arr
= OSArray::withObjects((const OSObject
**)&dict
, 1, 2);
146 personalities
->setObject(sym
, arr
);
151 /*********************************************************************
152 * Initialize the IOCatalog object.
153 *********************************************************************/
154 bool IOCatalogue::init(OSArray
* initArray
)
159 if ( !super::init() )
164 personalities
= OSDictionary::withCapacity(32);
165 personalities
->setOptions(OSCollection::kSort
, OSCollection::kSort
);
166 for (unsigned int idx
= 0; (obj
= initArray
->getObject(idx
)); idx
++)
168 dict
= OSDynamicCast(OSDictionary
, obj
);
170 OSKext::uniquePersonalityProperties(dict
);
171 if( 0 == dict
->getObject( gIOClassKey
))
173 IOLog("Missing or bad \"%s\" key\n",
174 gIOClassKey
->getCStringNoCopy());
177 dict
->setObject("KernelConfigTable", kOSBooleanTrue
);
178 addPersonality(dict
);
181 gIOCatalogLock
= IORWLockAlloc();
182 lock
= gIOCatalogLock
;
187 /*********************************************************************
188 * Release all resources used by IOCatalogue and deallocate.
189 * This will probably never be called.
190 *********************************************************************/
191 void IOCatalogue::free( void )
196 /*********************************************************************
197 *********************************************************************/
199 IOCatalogue::findDrivers(
201 SInt32
* generationCount
)
203 OSDictionary
* nextTable
;
206 const OSMetaClass
* meta
;
209 set
= OSOrderedSet::withCapacity( 1, IOServiceOrdering
,
210 (void *)gIOProbeScoreKey
);
216 meta
= service
->getMetaClass();
219 array
= (OSArray
*) personalities
->getObject(meta
->getClassNameSymbol());
220 if (array
) for (idx
= 0; (nextTable
= (OSDictionary
*) array
->getObject(idx
)); idx
++)
222 set
->setObject(nextTable
);
224 if (meta
== &IOService::gMetaClass
) break;
225 meta
= meta
->getSuperClass();
228 *generationCount
= getGenerationCount();
230 IORWLockUnlock(lock
);
235 /*********************************************************************
236 * Is personality already in the catalog?
237 *********************************************************************/
239 IOCatalogue::findDrivers(
240 OSDictionary
* matching
,
241 SInt32
* generationCount
)
243 OSCollectionIterator
* iter
;
247 const OSSymbol
* key
;
250 OSKext::uniquePersonalityProperties(matching
);
252 set
= OSOrderedSet::withCapacity( 1, IOServiceOrdering
,
253 (void *)gIOProbeScoreKey
);
254 if (!set
) return (0);
255 iter
= OSCollectionIterator::withCollection(personalities
);
263 while ((key
= (const OSSymbol
*) iter
->getNextObject()))
265 array
= (OSArray
*) personalities
->getObject(key
);
266 if (array
) for (idx
= 0; (dict
= (OSDictionary
*) array
->getObject(idx
)); idx
++)
268 /* This comparison must be done with only the keys in the
269 * "matching" dict to enable general searches.
271 if ( dict
->isEqualTo(matching
, matching
) )
272 set
->setObject(dict
);
275 *generationCount
= getGenerationCount();
276 IORWLockUnlock(lock
);
282 /*********************************************************************
283 * Add driver config tables to catalog and start matching process.
285 * Important that existing personalities are kept (not replaced)
286 * if duplicates found. Personalities can come from OSKext objects
287 * or from userland kext library. We want to minimize distinct
288 * copies between OSKext & IOCatalogue.
290 * xxx - userlib used to refuse to send personalities with IOKitDebug
291 * xxx - during safe boot. That would be better implemented here.
292 *********************************************************************/
294 bool IOCatalogue::addDrivers(
299 OSCollectionIterator
* iter
= NULL
; // must release
300 OSOrderedSet
* set
= NULL
; // must release
301 OSObject
* object
= NULL
; // do not release
302 OSArray
* persons
= NULL
; // do not release
304 persons
= OSDynamicCast(OSArray
, drivers
);
309 set
= OSOrderedSet::withCapacity( 10, IOServiceOrdering
,
310 (void *)gIOProbeScoreKey
);
315 iter
= OSCollectionIterator::withCollection(persons
);
320 /* Start with success; clear it on an error.
325 while ( (object
= iter
->getNextObject()) ) {
327 // xxx Deleted OSBundleModuleDemand check; will handle in other ways for SL
329 OSDictionary
* personality
= OSDynamicCast(OSDictionary
, object
);
334 IOLog("IOCatalogue::addDrivers() encountered non-dictionary; bailing.\n");
339 OSKext::uniquePersonalityProperties(personality
);
341 // Add driver personality to catalogue.
343 OSArray
* array
= arrayForPersonality(personality
);
344 if (!array
) addPersonality(personality
);
347 count
= array
->getCount();
349 OSDictionary
* driver
;
351 // Be sure not to double up on personalities.
352 driver
= (OSDictionary
*)array
->getObject(count
);
354 /* Unlike in other functions, this comparison must be exact!
355 * The catalogue must be able to contain personalities that
356 * are proper supersets of others.
357 * Do not compare just the properties present in one driver
358 * personality or the other.
360 if (personality
->isEqualTo(driver
)) {
368 result
= array
->setObject(personality
);
374 set
->setObject(personality
);
376 // Start device matching.
377 if (result
&& doNubMatching
&& (set
->getCount() > 0)) {
378 IOService::catalogNewDrivers(set
);
381 IORWLockUnlock(lock
);
384 if (set
) set
->release();
385 if (iter
) iter
->release();
390 /*********************************************************************
391 * Remove drivers from the catalog which match the
392 * properties in the matching dictionary.
393 *********************************************************************/
395 IOCatalogue::removeDrivers(
396 OSDictionary
* matching
,
400 OSCollectionIterator
* iter
;
403 const OSSymbol
* key
;
409 set
= OSOrderedSet::withCapacity(10,
411 (void *)gIOProbeScoreKey
);
414 iter
= OSCollectionIterator::withCollection(personalities
);
422 while ((key
= (const OSSymbol
*) iter
->getNextObject()))
424 array
= (OSArray
*) personalities
->getObject(key
);
425 if (array
) for (idx
= 0; (dict
= (OSDictionary
*) array
->getObject(idx
)); idx
++)
427 /* This comparison must be done with only the keys in the
428 * "matching" dict to enable general searches.
430 if ( dict
->isEqualTo(matching
, matching
) ) {
431 set
->setObject(dict
);
432 array
->removeObject(idx
);
436 // Start device matching.
437 if ( doNubMatching
&& (set
->getCount() > 0) ) {
438 IOService::catalogNewDrivers(set
);
442 IORWLockUnlock(lock
);
450 // Return the generation count.
451 SInt32
IOCatalogue::getGenerationCount(void) const
453 return( generation
);
456 bool IOCatalogue::isModuleLoaded(OSString
* moduleName
) const
458 return isModuleLoaded(moduleName
->getCStringNoCopy());
461 bool IOCatalogue::isModuleLoaded(const char * moduleName
) const
464 ret
= OSKext::loadKextWithIdentifier(moduleName
);
465 if (kOSKextReturnDeferred
== ret
) {
466 // a request has been queued but the module isn't necessarily
467 // loaded yet, so stall.
470 // module is present or never will be
474 // Check to see if module has been loaded already.
475 bool IOCatalogue::isModuleLoaded(OSDictionary
* driver
) const
477 OSString
* moduleName
= NULL
;
478 OSString
* publisherName
= NULL
;
483 /* The personalities of codeless kexts often contain the bundle ID of the
484 * kext they reference, and not the bundle ID of the codeless kext itself.
485 * The prelinked kernel needs to know the bundle ID of the codeless kext
486 * so it can include these personalities, so OSKext stores that bundle ID
487 * in the IOPersonalityPublisher key, and we record it as requested here.
489 publisherName
= OSDynamicCast(OSString
,
490 driver
->getObject(kIOPersonalityPublisherKey
));
491 OSKext::recordIdentifierRequest(publisherName
);
493 moduleName
= OSDynamicCast(OSString
, driver
->getObject(gIOModuleIdentifierKey
));
495 return isModuleLoaded(moduleName
);
497 /* If a personality doesn't hold the "CFBundleIdentifier" key
498 * it is assumed to be an "in-kernel" driver.
503 /* This function is called after a module has been loaded.
504 * Is invoked from user client call, ultimately from IOKitLib's
505 * IOCatalogueModuleLoaded(). Sent from kextd.
507 void IOCatalogue::moduleHasLoaded(OSString
* moduleName
)
511 dict
= OSDictionary::withCapacity(2);
512 dict
->setObject(gIOModuleIdentifierKey
, moduleName
);
516 (void) OSKext::setDeferredLoadSucceeded();
517 (void) OSKext::considerRebuildOfPrelinkedKernel();
520 void IOCatalogue::moduleHasLoaded(const char * moduleName
)
524 name
= OSString::withCString(moduleName
);
525 moduleHasLoaded(name
);
529 // xxx - return is really OSReturn/kern_return_t
530 IOReturn
IOCatalogue::unloadModule(OSString
* moduleName
) const
532 return OSKext::removeKextWithIdentifier(moduleName
->getCStringNoCopy());
535 IOReturn
IOCatalogue::_terminateDrivers(OSDictionary
* matching
)
543 return kIOReturnBadArgument
;
545 ret
= kIOReturnSuccess
;
547 iter
= IORegistryIterator::iterateOver(gIOServicePlane
,
548 kIORegistryIterateRecursively
);
550 return kIOReturnNoMemory
;
552 OSKext::uniquePersonalityProperties( matching
);
554 // terminate instances.
557 while( (service
= (IOService
*)iter
->getNextObject()) ) {
558 dict
= service
->getPropertyTable();
562 /* Terminate only for personalities that match the matching dictionary.
563 * This comparison must be done with only the keys in the
564 * "matching" dict to enable general matching.
566 if ( !dict
->isEqualTo(matching
, matching
) )
569 if ( !service
->terminate(kIOServiceRequired
|kIOServiceSynchronous
) ) {
570 ret
= kIOReturnUnsupported
;
574 } while( !service
&& !iter
->isValid());
580 IOReturn
IOCatalogue::_removeDrivers(OSDictionary
* matching
)
582 IOReturn ret
= kIOReturnSuccess
;
583 OSCollectionIterator
* iter
;
586 const OSSymbol
* key
;
589 // remove configs from catalog.
591 iter
= OSCollectionIterator::withCollection(personalities
);
592 if (!iter
) return (kIOReturnNoMemory
);
594 while ((key
= (const OSSymbol
*) iter
->getNextObject()))
596 array
= (OSArray
*) personalities
->getObject(key
);
597 if (array
) for (idx
= 0; (dict
= (OSDictionary
*) array
->getObject(idx
)); idx
++)
600 /* Remove from the catalogue's array any personalities
601 * that match the matching dictionary.
602 * This comparison must be done with only the keys in the
603 * "matching" dict to enable general matching.
605 if (dict
->isEqualTo(matching
, matching
))
607 array
->removeObject(idx
);
617 IOReturn
IOCatalogue::terminateDrivers(OSDictionary
* matching
)
621 ret
= _terminateDrivers(matching
);
623 if (kIOReturnSuccess
== ret
)
624 ret
= _removeDrivers(matching
);
625 IORWLockUnlock(lock
);
630 IOReturn
IOCatalogue::terminateDriversForModule(
631 OSString
* moduleName
,
636 bool isLoaded
= false;
638 /* Check first if the kext currently has any linkage dependents;
639 * in such a case the unload would fail so let's not terminate any
640 * IOServices (since doing so typically results in a panic when there
641 * are loaded dependencies). Note that we aren't locking the kext here
642 * so it might lose or gain dependents by the time we call unloadModule();
643 * I think that's ok, our unload can fail if a kext comes in on top of
644 * this one even after we've torn down IOService objects. Conversely,
645 * if we fail the unload here and then lose a library, the autounload
646 * thread will get us in short order.
648 if (OSKext::isKextWithIdentifierLoaded(moduleName
->getCStringNoCopy())) {
652 if (!OSKext::canUnloadKextWithIdentifier(moduleName
,
653 /* checkClasses */ false)) {
654 ret
= kOSKextReturnInUse
;
658 dict
= OSDictionary::withCapacity(1);
660 ret
= kIOReturnNoMemory
;
664 dict
->setObject(gIOModuleIdentifierKey
, moduleName
);
666 ret
= _terminateDrivers(dict
);
668 /* No goto between IOLock calls!
671 if (kIOReturnSuccess
== ret
) {
672 ret
= _removeDrivers(dict
);
675 // Unload the module itself.
676 if (unload
&& isLoaded
&& ret
== kIOReturnSuccess
) {
677 ret
= unloadModule(moduleName
);
680 IORWLockUnlock(lock
);
688 IOReturn
IOCatalogue::terminateDriversForModule(
689 const char * moduleName
,
695 name
= OSString::withCString(moduleName
);
697 return kIOReturnNoMemory
;
699 ret
= terminateDriversForModule(name
, unload
);
705 bool IOCatalogue::startMatching( OSDictionary
* matching
)
707 OSCollectionIterator
* iter
;
711 const OSSymbol
* key
;
717 set
= OSOrderedSet::withCapacity(10, IOServiceOrdering
,
718 (void *)gIOProbeScoreKey
);
722 iter
= OSCollectionIterator::withCollection(personalities
);
731 while ((key
= (const OSSymbol
*) iter
->getNextObject()))
733 array
= (OSArray
*) personalities
->getObject(key
);
734 if (array
) for (idx
= 0; (dict
= (OSDictionary
*) array
->getObject(idx
)); idx
++)
736 /* This comparison must be done with only the keys in the
737 * "matching" dict to enable general matching.
739 if (dict
->isEqualTo(matching
, matching
)) {
740 set
->setObject(dict
);
745 // Start device matching.
746 if ( set
->getCount() > 0 ) {
747 IOService::catalogNewDrivers(set
);
751 IORWLockUnlock(lock
);
759 void IOCatalogue::reset(void)
761 IOCatalogue::resetAndAddDrivers(/* no drivers; true reset */ NULL
,
762 /* doMatching */ false);
766 bool IOCatalogue::resetAndAddDrivers(OSArray
* drivers
, bool doNubMatching
)
769 OSArray
* newPersonalities
= NULL
; // do not release
770 OSCollectionIterator
* iter
= NULL
; // must release
771 OSOrderedSet
* matchSet
= NULL
; // must release
772 const OSSymbol
* key
;
774 OSDictionary
* thisNewPersonality
= NULL
; // do not release
775 OSDictionary
* thisOldPersonality
= NULL
; // do not release
776 OSDictionary
* myKexts
= NULL
; // must release
777 signed int idx
, newIdx
;
780 newPersonalities
= OSDynamicCast(OSArray
, drivers
);
781 if (!newPersonalities
) {
785 matchSet
= OSOrderedSet::withCapacity(10, IOServiceOrdering
,
786 (void *)gIOProbeScoreKey
);
790 iter
= OSCollectionIterator::withCollection(personalities
);
795 /* need copy of loaded kexts so we can check if for loaded modules without
796 * taking the OSKext lock. There is a potential of deadlocking if we get
797 * an OSKext via the normal path. See 14672140.
799 myKexts
= OSKext::copyKexts();
803 IOLog("Resetting IOCatalogue.\n");
805 /* No goto finish from here to unlock.
809 while ((key
= (const OSSymbol
*) iter
->getNextObject()))
811 array
= (OSArray
*) personalities
->getObject(key
);
812 if (!array
) continue;
815 (thisOldPersonality
= (OSDictionary
*) array
->getObject(idx
));
818 if (thisOldPersonality
->getObject("KernelConfigTable")) continue;
819 thisNewPersonality
= NULL
;
821 if (newPersonalities
) {
823 (thisNewPersonality
= (OSDictionary
*) newPersonalities
->getObject(newIdx
));
826 /* Unlike in other functions, this comparison must be exact!
827 * The catalogue must be able to contain personalities that
828 * are proper supersets of others.
829 * Do not compare just the properties present in one driver
830 * personality or the other.
832 if (OSDynamicCast(OSDictionary
, thisNewPersonality
) == NULL
) {
833 /* skip thisNewPersonality if it is not an OSDictionary */
836 if (thisNewPersonality
->isEqualTo(thisOldPersonality
))
840 if (thisNewPersonality
) {
842 newPersonalities
->removeObject(newIdx
);
845 // not in new set - remove
846 // only remove dictionary if this module in not loaded - 9953845
847 if ( isModuleLoadedNoOSKextLock(myKexts
, thisOldPersonality
) == false ) {
849 matchSet
->setObject(thisOldPersonality
);
851 array
->removeObject(idx
);
859 if (newPersonalities
) {
861 (thisNewPersonality
= (OSDictionary
*) newPersonalities
->getObject(newIdx
));
864 if (OSDynamicCast(OSDictionary
, thisNewPersonality
) == NULL
) {
865 /* skip thisNewPersonality if it is not an OSDictionary */
869 OSKext::uniquePersonalityProperties(thisNewPersonality
);
870 addPersonality(thisNewPersonality
);
871 matchSet
->setObject(thisNewPersonality
);
875 /* Finally, start device matching on all new & removed personalities.
877 if (result
&& doNubMatching
&& (matchSet
->getCount() > 0)) {
878 IOService::catalogNewDrivers(matchSet
);
882 IORWLockUnlock(lock
);
885 if (matchSet
) matchSet
->release();
886 if (iter
) iter
->release();
887 if (myKexts
) myKexts
->release();
892 bool IOCatalogue::serialize(OSSerialize
* s
) const
897 return super::serialize(s
);
900 bool IOCatalogue::serializeData(IOOptionBits kind
, OSSerialize
* s
) const
902 kern_return_t kr
= kIOReturnSuccess
;
906 case kIOCatalogGetContents
:
907 kr
= KERN_NOT_SUPPORTED
;
910 case kIOCatalogGetModuleDemandList
:
911 kr
= KERN_NOT_SUPPORTED
;
914 case kIOCatalogGetCacheMissList
:
915 kr
= KERN_NOT_SUPPORTED
;
918 case kIOCatalogGetROMMkextList
:
919 kr
= KERN_NOT_SUPPORTED
;
923 kr
= kIOReturnBadArgument
;
930 /* isModuleLoadedNoOSKextLock - used to check to see if a kext is loaded
931 * without taking the OSKext lock. We use this to avoid the problem
932 * where taking the IOCatalog lock then the OSKext lock will dealock when
933 * a kext load or unload is happening at the same time as IOCatalog changing.
935 * theKexts - is a dictionary of current kexts (from OSKext::copyKexts) with
936 * key set to the kext bundle ID and value set to an OSKext object
937 * theModuleDict - is an IOKit personality dictionary for a given module (kext)
939 static bool isModuleLoadedNoOSKextLock(OSDictionary
*theKexts
,
940 OSDictionary
*theModuleDict
)
942 bool myResult
= false;
943 const OSString
* myBundleID
= NULL
; // do not release
944 OSKext
* myKext
= NULL
; // do not release
946 if (theKexts
== NULL
|| theModuleDict
== NULL
) {
950 // gIOModuleIdentifierKey is "CFBundleIdentifier"
951 myBundleID
= OSDynamicCast(OSString
,
952 theModuleDict
->getObject(gIOModuleIdentifierKey
));
953 if (myBundleID
== NULL
) {
957 myKext
= OSDynamicCast(OSKext
, theKexts
->getObject(myBundleID
->getCStringNoCopy()));
959 myResult
= myKext
->isLoaded();
967 #pragma mark Obsolete Kext Loading Stuff
969 /*********************************************************************
970 **********************************************************************
971 *** BINARY COMPATIBILITY SECTION ***
972 **********************************************************************
973 **********************************************************************
974 * These functions are no longer used are necessary for C++ binary
975 * compatibility on i386.
976 **********************************************************************/