]> git.saurik.com Git - apple/xnu.git/blob - iokit/Kernel/IOCatalogue.cpp
a57b083a7213be51dda569145d995fb69856bce8
[apple/xnu.git] / iokit / Kernel / IOCatalogue.cpp
1 /*
2 * Copyright (c) 1998-2012 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_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. 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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1998 Apple Inc. All rights reserved.
30 *
31 * HISTORY
32 *
33 */
34 /*
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,
38 * Version 2.0.
39 */
40
41 #define IOKIT_ENABLE_SHARED_PTR
42
43 extern "C" {
44 #include <machine/machine_routines.h>
45 #include <libkern/kernel_mach_header.h>
46 #include <kern/host.h>
47 #include <security/mac_data.h>
48 };
49
50 #include <libkern/c++/OSContainers.h>
51 #include <libkern/c++/OSUnserialize.h>
52 #include <libkern/c++/OSKext.h>
53 #include <libkern/c++/OSSharedPtr.h>
54 #include <libkern/OSKextLibPrivate.h>
55 #include <libkern/OSDebug.h>
56
57 #include <IOKit/IODeviceTreeSupport.h>
58 #include <IOKit/IOService.h>
59 #include <IOKit/IOCatalogue.h>
60
61 #include <IOKit/IOLib.h>
62 #include <IOKit/assert.h>
63 #include <IOKit/IOKitKeysPrivate.h>
64
65 #if PRAGMA_MARK
66 #pragma mark Internal Declarations
67 #endif
68 /*********************************************************************
69 *********************************************************************/
70
71 OSSharedPtr<IOCatalogue> gIOCatalogue;
72 OSSharedPtr<const OSSymbol> gIOClassKey;
73 OSSharedPtr<const OSSymbol> gIOProbeScoreKey;
74 OSSharedPtr<const OSSymbol> gIOModuleIdentifierKey;
75 OSSharedPtr<const OSSymbol> gIOModuleIdentifierKernelKey;
76 OSSharedPtr<const OSSymbol> gIOHIDInterfaceClassName;
77 IORWLock * gIOCatalogLock;
78
79 #if PRAGMA_MARK
80 #pragma mark Utility functions
81 #endif
82
83 #if PRAGMA_MARK
84 #pragma mark IOCatalogue class implementation
85 #endif
86 /*********************************************************************
87 *********************************************************************/
88
89 #define super OSObject
90 OSDefineMetaClassAndStructors(IOCatalogue, OSObject)
91
92 static bool isModuleLoadedNoOSKextLock(OSDictionary *theKexts,
93 OSDictionary *theModuleDict);
94
95
96 /*********************************************************************
97 *********************************************************************/
98 void
99 IOCatalogue::initialize(void)
100 {
101 OSSharedPtr<OSArray> array;
102 OSSharedPtr<OSString> errorString;
103 bool rc;
104
105 extern const char * gIOKernelConfigTables;
106
107 array = OSDynamicPtrCast<OSArray>(OSUnserialize(gIOKernelConfigTables, errorString));
108 if (!array && errorString) {
109 IOLog("KernelConfigTables syntax error: %s\n",
110 errorString->getCStringNoCopy());
111 }
112
113 gIOClassKey = OSSymbol::withCStringNoCopy( kIOClassKey );
114 gIOProbeScoreKey = OSSymbol::withCStringNoCopy( kIOProbeScoreKey );
115 gIOModuleIdentifierKey = OSSymbol::withCStringNoCopy( kCFBundleIdentifierKey );
116 gIOModuleIdentifierKernelKey = OSSymbol::withCStringNoCopy( kCFBundleIdentifierKernelKey );
117 gIOHIDInterfaceClassName = OSSymbol::withCStringNoCopy( "IOHIDInterface" );
118
119
120 assert( array && gIOClassKey && gIOProbeScoreKey
121 && gIOModuleIdentifierKey);
122
123 gIOCatalogue = OSMakeShared<IOCatalogue>();
124 assert(gIOCatalogue);
125 rc = gIOCatalogue->init(array.get());
126 assert(rc);
127 }
128
129 /*********************************************************************
130 * Initialize the IOCatalog object.
131 *********************************************************************/
132 OSArray *
133 IOCatalogue::arrayForPersonality(OSDictionary * dict)
134 {
135 const OSSymbol * sym;
136
137 sym = OSDynamicCast(OSSymbol, dict->getObject(gIOProviderClassKey));
138 if (!sym) {
139 return NULL;
140 }
141
142 return (OSArray *) personalities->getObject(sym);
143 }
144
145 void
146 IOCatalogue::addPersonality(OSDictionary * dict)
147 {
148 const OSSymbol * sym;
149 OSArray * arr;
150
151 sym = OSDynamicCast(OSSymbol, dict->getObject(gIOProviderClassKey));
152 if (!sym) {
153 return;
154 }
155 arr = (OSArray *) personalities->getObject(sym);
156 if (arr) {
157 arr->setObject(dict);
158 } else {
159 OSSharedPtr<OSArray> sharedArr = OSArray::withObjects((const OSObject **)&dict, 1, 2);
160 personalities->setObject(sym, sharedArr.get());
161 }
162 }
163
164 /*********************************************************************
165 * Initialize the IOCatalog object.
166 *********************************************************************/
167 bool
168 IOCatalogue::init(OSArray * initArray)
169 {
170 OSDictionary * dict;
171 OSObject * obj;
172
173 if (!super::init()) {
174 return false;
175 }
176
177 generation = 1;
178
179 personalities = OSDictionary::withCapacity(32);
180 personalities->setOptions(OSCollection::kSort, OSCollection::kSort);
181 for (unsigned int idx = 0; (obj = initArray->getObject(idx)); idx++) {
182 dict = OSDynamicCast(OSDictionary, obj);
183 if (!dict) {
184 continue;
185 }
186 OSKext::uniquePersonalityProperties(dict);
187 if (NULL == dict->getObject( gIOClassKey.get())) {
188 IOLog("Missing or bad \"%s\" key\n",
189 gIOClassKey->getCStringNoCopy());
190 continue;
191 }
192 dict->setObject("KernelConfigTable", kOSBooleanTrue);
193 addPersonality(dict);
194 }
195
196 gIOCatalogLock = IORWLockAlloc();
197 lock = gIOCatalogLock;
198
199 return true;
200 }
201
202 /*********************************************************************
203 * Release all resources used by IOCatalogue and deallocate.
204 * This will probably never be called.
205 *********************************************************************/
206 void
207 IOCatalogue::free( void )
208 {
209 panic("");
210 }
211
212 /*********************************************************************
213 *********************************************************************/
214 OSPtr<OSOrderedSet>
215 IOCatalogue::findDrivers(
216 IOService * service,
217 SInt32 * generationCount)
218 {
219 OSDictionary * nextTable;
220 OSSharedPtr<OSOrderedSet> set;
221 OSArray * array;
222 const OSMetaClass * meta;
223 unsigned int idx;
224
225 set = OSOrderedSet::withCapacity( 1, IOServiceOrdering,
226 (void *)(gIOProbeScoreKey.get()));
227 if (!set) {
228 return NULL;
229 }
230
231 IORWLockRead(lock);
232
233 meta = service->getMetaClass();
234 while (meta) {
235 array = (OSArray *) personalities->getObject(meta->getClassNameSymbol());
236 if (array) {
237 for (idx = 0; (nextTable = (OSDictionary *) array->getObject(idx)); idx++) {
238 set->setObject(nextTable);
239 }
240 }
241 if (meta == &IOService::gMetaClass) {
242 break;
243 }
244 meta = meta->getSuperClass();
245 }
246
247 *generationCount = getGenerationCount();
248
249 IORWLockUnlock(lock);
250
251 return set;
252 }
253
254 /*********************************************************************
255 * Is personality already in the catalog?
256 *********************************************************************/
257 OSPtr<OSOrderedSet>
258 IOCatalogue::findDrivers(
259 OSDictionary * matching,
260 SInt32 * generationCount)
261 {
262 OSSharedPtr<OSCollectionIterator> iter;
263 OSDictionary * dict;
264 OSSharedPtr<OSOrderedSet> set;
265 OSArray * array;
266 const OSSymbol * key;
267 unsigned int idx;
268
269 OSKext::uniquePersonalityProperties(matching);
270
271 set = OSOrderedSet::withCapacity( 1, IOServiceOrdering,
272 (void *)(gIOProbeScoreKey.get()));
273 if (!set) {
274 return NULL;
275 }
276 iter = OSCollectionIterator::withCollection(personalities.get());
277 if (!iter) {
278 return nullptr;
279 }
280
281 IORWLockRead(lock);
282 while ((key = (const OSSymbol *) iter->getNextObject())) {
283 array = (OSArray *) personalities->getObject(key);
284 if (array) {
285 for (idx = 0; (dict = (OSDictionary *) array->getObject(idx)); idx++) {
286 /* This comparison must be done with only the keys in the
287 * "matching" dict to enable general searches.
288 */
289 if (dict->isEqualTo(matching, matching)) {
290 set->setObject(dict);
291 }
292 }
293 }
294 }
295 *generationCount = getGenerationCount();
296 IORWLockUnlock(lock);
297
298 return set;
299 }
300
301 /*********************************************************************
302 * Add driver config tables to catalog and start matching process.
303 *
304 * Important that existing personalities are kept (not replaced)
305 * if duplicates found. Personalities can come from OSKext objects
306 * or from userland kext library. We want to minimize distinct
307 * copies between OSKext & IOCatalogue.
308 *
309 * xxx - userlib used to refuse to send personalities with IOKitDebug
310 * xxx - during safe boot. That would be better implemented here.
311 *********************************************************************/
312
313 bool
314 IOCatalogue::addDrivers(
315 OSArray * drivers,
316 bool doNubMatching)
317 {
318 bool result = false;
319 OSSharedPtr<OSOrderedSet> set;
320 OSSharedPtr<OSCollectionIterator> iter;
321 OSObject * object = NULL; // do not release
322 OSArray * persons = NULL;// do not release
323
324 persons = OSDynamicCast(OSArray, drivers);
325 if (!persons) {
326 goto finish;
327 }
328
329 set = OSOrderedSet::withCapacity( 10, IOServiceOrdering,
330 (void *)(gIOProbeScoreKey.get()));
331 if (!set) {
332 goto finish;
333 }
334
335 iter = OSCollectionIterator::withCollection(persons);
336 if (!iter) {
337 goto finish;
338 }
339
340 /* Start with success; clear it on an error.
341 */
342 result = true;
343
344 IORWLockWrite(lock);
345 while ((object = iter->getNextObject())) {
346 // xxx Deleted OSBundleModuleDemand check; will handle in other ways for SL
347
348 OSDictionary * personality = OSDynamicCast(OSDictionary, object);
349
350 SInt count;
351
352 if (!personality) {
353 IOLog("IOCatalogue::addDrivers() encountered non-dictionary; bailing.\n");
354 result = false;
355 break;
356 }
357
358 OSKext::uniquePersonalityProperties(personality);
359
360 // Add driver personality to catalogue.
361
362 OSArray * array = arrayForPersonality(personality);
363 if (!array) {
364 addPersonality(personality);
365 } else {
366 count = array->getCount();
367 while (count--) {
368 OSDictionary * driver;
369
370 // Be sure not to double up on personalities.
371 driver = (OSDictionary *)array->getObject(count);
372
373 /* Unlike in other functions, this comparison must be exact!
374 * The catalogue must be able to contain personalities that
375 * are proper supersets of others.
376 * Do not compare just the properties present in one driver
377 * personality or the other.
378 */
379 if (personality->isEqualTo(driver)) {
380 break;
381 }
382 }
383 if (count >= 0) {
384 // its a dup
385 continue;
386 }
387 result = array->setObject(personality);
388 if (!result) {
389 break;
390 }
391 }
392
393 set->setObject(personality);
394 }
395 // Start device matching.
396 if (result && doNubMatching && (set->getCount() > 0)) {
397 IOService::catalogNewDrivers(set.get());
398 generation++;
399 }
400 IORWLockUnlock(lock);
401
402 finish:
403
404 return result;
405 }
406
407 bool
408 IOCatalogue::removeDrivers(bool doNubMatching, bool (^shouldRemove)(OSDictionary *personality))
409 {
410 OSSharedPtr<OSOrderedSet> set;
411 OSSharedPtr<OSCollectionIterator> iter;
412 OSDictionary * dict;
413 OSArray * array;
414 const OSSymbol * key;
415 unsigned int idx;
416
417 set = OSOrderedSet::withCapacity(10,
418 IOServiceOrdering,
419 (void *)(gIOProbeScoreKey.get()));
420 if (!set) {
421 return false;
422 }
423 iter = OSCollectionIterator::withCollection(personalities.get());
424 if (!iter) {
425 return false;
426 }
427
428 IORWLockWrite(lock);
429 while ((key = (const OSSymbol *) iter->getNextObject())) {
430 array = (OSArray *) personalities->getObject(key);
431 if (array) {
432 for (idx = 0; (dict = (OSDictionary *) array->getObject(idx)); idx++) {
433 if (shouldRemove(dict)) {
434 set->setObject(dict);
435 array->removeObject(idx);
436 idx--;
437 }
438 }
439 }
440 // Start device matching.
441 if (doNubMatching && (set->getCount() > 0)) {
442 IOService::catalogNewDrivers(set.get());
443 generation++;
444 }
445 }
446 IORWLockUnlock(lock);
447
448 return true;
449 }
450
451 /*********************************************************************
452 * Remove drivers from the catalog which match the
453 * properties in the matching dictionary.
454 *********************************************************************/
455 bool
456 IOCatalogue::removeDrivers(
457 OSDictionary * matching,
458 bool doNubMatching)
459 {
460 if (!matching) {
461 return false;
462 }
463 return removeDrivers(doNubMatching, ^(OSDictionary *dict) {
464 /* This comparison must be done with only the keys in the
465 * "matching" dict to enable general searches.
466 */
467 return dict->isEqualTo(matching, matching);
468 });
469 }
470
471 // Return the generation count.
472 SInt32
473 IOCatalogue::getGenerationCount(void) const
474 {
475 return generation;
476 }
477
478 // Check to see if kernel module has been loaded already, and request its load.
479 bool
480 IOCatalogue::isModuleLoaded(OSDictionary * driver, OSObject ** kextRef) const
481 {
482 OSString * moduleName = NULL;
483 OSString * publisherName = NULL;
484 OSReturn ret;
485
486 if (kextRef) {
487 *kextRef = NULL;
488 }
489 if (!driver) {
490 return false;
491 }
492
493 /* The personalities of codeless kexts often contain the bundle ID of the
494 * kext they reference, and not the bundle ID of the codeless kext itself.
495 * The prelinked kernel needs to know the bundle ID of the codeless kext
496 * so it can include these personalities, so OSKext stores that bundle ID
497 * in the IOPersonalityPublisher key, and we record it as requested here.
498 */
499 publisherName = OSDynamicCast(OSString,
500 driver->getObject(kIOPersonalityPublisherKey));
501 OSKext::recordIdentifierRequest(publisherName);
502
503 moduleName = OSDynamicCast(OSString, driver->getObject(gIOModuleIdentifierKernelKey.get()));
504 if (moduleName) {
505 ret = OSKext::loadKextWithIdentifier(moduleName, kextRef);
506 if (kOSKextReturnDeferred == ret) {
507 // a request has been queued but the module isn't necessarily
508 // loaded yet, so stall.
509 return false;
510 }
511 OSString *moduleDextName = OSDynamicCast(OSString, driver->getObject(gIOModuleIdentifierKey.get()));
512 if (moduleDextName && !(moduleName->isEqualTo(moduleDextName))) {
513 OSSharedPtr<OSObject> dextRef;
514 ret = OSKext::loadKextWithIdentifier(moduleDextName, dextRef);
515 }
516 // module is present or never will be
517 return true;
518 }
519
520 /* If a personality doesn't hold the "CFBundleIdentifier" or "CFBundleIdentifierKernel" key
521 * it is assumed to be an "in-kernel" driver.
522 */
523 return true;
524 }
525
526 bool
527 IOCatalogue::isModuleLoaded(OSDictionary * driver, OSSharedPtr<OSObject>& kextRef) const
528 {
529 OSObject* kextRefRaw = NULL;
530 bool result = isModuleLoaded(driver, &kextRefRaw);
531 kextRef.reset(kextRefRaw, OSNoRetain);
532 return result;
533 }
534
535 /* This function is called after a module has been loaded.
536 * Is invoked from user client call, ultimately from IOKitLib's
537 * IOCatalogueModuleLoaded(). Sent from kextd.
538 */
539 void
540 IOCatalogue::moduleHasLoaded(const OSSymbol * moduleName)
541 {
542 startMatching(moduleName);
543
544 (void) OSKext::setDeferredLoadSucceeded();
545 (void) OSKext::considerRebuildOfPrelinkedKernel();
546 }
547
548 void
549 IOCatalogue::moduleHasLoaded(const char * moduleName)
550 {
551 OSSharedPtr<const OSSymbol> name;
552
553 name = OSSymbol::withCString(moduleName);
554 moduleHasLoaded(name.get());
555 }
556
557 // xxx - return is really OSReturn/kern_return_t
558 IOReturn
559 IOCatalogue::unloadModule(OSString * moduleName) const
560 {
561 return OSKext::removeKextWithIdentifier(moduleName->getCStringNoCopy());
562 }
563
564 IOReturn
565 IOCatalogue::terminateDrivers(OSDictionary * matching, io_name_t className)
566 {
567 OSDictionary * dict;
568 OSSharedPtr<OSIterator> iter;
569 IOService * service;
570 IOReturn ret;
571
572 ret = kIOReturnSuccess;
573 dict = NULL;
574 iter = IORegistryIterator::iterateOver(gIOServicePlane,
575 kIORegistryIterateRecursively);
576 if (!iter) {
577 return kIOReturnNoMemory;
578 }
579
580 if (matching) {
581 OSKext::uniquePersonalityProperties( matching, false );
582 }
583
584 // terminate instances.
585 do {
586 iter->reset();
587 while ((service = (IOService *)iter->getNextObject())) {
588 if (className && !service->metaCast(className)) {
589 continue;
590 }
591 if (matching) {
592 /* Terminate only for personalities that match the matching dictionary.
593 * This comparison must be done with only the keys in the
594 * "matching" dict to enable general matching.
595 */
596 dict = service->getPropertyTable();
597 if (!dict) {
598 continue;
599 }
600 if (!dict->isEqualTo(matching, matching)) {
601 continue;
602 }
603 }
604
605 OSKext * kext;
606 OSSharedPtr<OSString> dextBundleID;
607 const char * bundleIDStr;
608 OSObject * prop;
609 bool okToTerminate;
610 bool isDext = service->hasUserServer();
611 for (okToTerminate = true;;) {
612 if (isDext) {
613 dextBundleID = OSDynamicPtrCast<OSString>(service->copyProperty(gIOModuleIdentifierKey.get()));
614 if (!dextBundleID) {
615 break;
616 }
617 bundleIDStr = dextBundleID->getCStringNoCopy();
618 } else {
619 kext = service->getMetaClass()->getKext();
620 if (!kext) {
621 break;
622 }
623 bundleIDStr = kext->getIdentifierCString();
624 prop = kext->getPropertyForHostArch(kOSBundleAllowUserTerminateKey);
625 if (prop) {
626 okToTerminate = (kOSBooleanTrue == prop);
627 break;
628 }
629 }
630 if (!bundleIDStr) {
631 break;
632 }
633 if (!strcmp(kOSKextKernelIdentifier, bundleIDStr)) {
634 okToTerminate = false;
635 break;
636 }
637 if (!strncmp("com.apple.", bundleIDStr, strlen("com.apple."))) {
638 okToTerminate = false;
639 break;
640 }
641 break;
642 }
643 if (!okToTerminate) {
644 #if DEVELOPMENT || DEBUG
645 okToTerminate = true;
646 #endif /* DEVELOPMENT || DEBUG */
647 IOLog("%sallowing kextunload terminate for bundleID %s\n",
648 okToTerminate ? "" : "dis", bundleIDStr ? bundleIDStr : "?");
649 if (!okToTerminate) {
650 ret = kIOReturnUnsupported;
651 break;
652 }
653 }
654 IOOptionBits terminateOptions = kIOServiceRequired | kIOServiceSynchronous;
655 if (isDext) {
656 terminateOptions |= kIOServiceTerminateNeedWillTerminate;
657 }
658 if (!service->terminate(terminateOptions)) {
659 ret = kIOReturnUnsupported;
660 break;
661 }
662 }
663 } while (!service && !iter->isValid());
664
665 return ret;
666 }
667
668 IOReturn
669 IOCatalogue::_removeDrivers(OSDictionary * matching)
670 {
671 IOReturn ret = kIOReturnSuccess;
672 OSSharedPtr<OSCollectionIterator> iter;
673 OSDictionary * dict;
674 OSArray * array;
675 const OSSymbol * key;
676 unsigned int idx;
677
678 // remove configs from catalog.
679
680 iter = OSCollectionIterator::withCollection(personalities.get());
681 if (!iter) {
682 return kIOReturnNoMemory;
683 }
684
685 while ((key = (const OSSymbol *) iter->getNextObject())) {
686 array = (OSArray *) personalities->getObject(key);
687 if (array) {
688 for (idx = 0; (dict = (OSDictionary *) array->getObject(idx)); idx++) {
689 /* Remove from the catalogue's array any personalities
690 * that match the matching dictionary.
691 * This comparison must be done with only the keys in the
692 * "matching" dict to enable general matching.
693 */
694 if (dict->isEqualTo(matching, matching)) {
695 array->removeObject(idx);
696 idx--;
697 }
698 }
699 }
700 }
701
702 return ret;
703 }
704
705 IOReturn
706 IOCatalogue::terminateDrivers(OSDictionary * matching)
707 {
708 IOReturn ret;
709
710 if (!matching) {
711 return kIOReturnBadArgument;
712 }
713 ret = terminateDrivers(matching, NULL);
714 IORWLockWrite(lock);
715 if (kIOReturnSuccess == ret) {
716 ret = _removeDrivers(matching);
717 }
718 IORWLockUnlock(lock);
719
720 return ret;
721 }
722
723 IOReturn
724 IOCatalogue::terminateDriversForUserspaceReboot()
725 {
726 IOReturn ret = kIOReturnSuccess;
727
728 #if !NO_KEXTD
729 OSSharedPtr<OSIterator> iter;
730 IOService * service;
731 bool isDeferredMatch;
732 bool isDext;
733 IOOptionBits terminateOptions;
734
735 iter = IORegistryIterator::iterateOver(gIOServicePlane,
736 kIORegistryIterateRecursively);
737 if (!iter) {
738 return kIOReturnNoMemory;
739 }
740
741 do {
742 iter->reset();
743 while ((service = (IOService *)iter->getNextObject())) {
744 isDeferredMatch = service->propertyHasValue(gIOMatchDeferKey, kOSBooleanTrue);
745 isDext = service->hasUserServer();
746 if (isDeferredMatch || isDext) {
747 if (isDext) {
748 OSSharedPtr<OSString> name = OSDynamicPtrCast<OSString>(service->copyProperty(gIOUserServerNameKey));
749 const char *userServerName = NULL;
750 if (name) {
751 userServerName = name->getCStringNoCopy();
752 }
753 IOLog("terminating service %s-0x%llx [dext %s]\n", service->getName(), service->getRegistryEntryID(), userServerName ? userServerName : "(null)");
754 } else {
755 OSKext *kext = service->getMetaClass()->getKext();
756 const char *bundleID = NULL;
757 if (kext) {
758 bundleID = kext->getIdentifierCString();
759 }
760 IOLog("terminating service %s-0x%llx [kext %s]\n", service->getName(), service->getRegistryEntryID(), bundleID ? bundleID : "(null)");
761 }
762 terminateOptions = kIOServiceRequired | kIOServiceSynchronous;
763 if (isDext) {
764 terminateOptions |= kIOServiceTerminateNeedWillTerminate;
765 }
766 if (!service->terminate(terminateOptions)) {
767 IOLog("failed to terminate service %s-0x%llx\n", service->getName(), service->getRegistryEntryID());
768 ret = kIOReturnUnsupported;
769 break;
770 }
771 }
772 }
773 } while (!service && !iter->isValid());
774 #endif
775
776 return ret;
777 }
778
779 IOReturn
780 IOCatalogue::resetAfterUserspaceReboot(void)
781 {
782 OSSharedPtr<OSIterator> iter;
783 IOService * service;
784
785 iter = IORegistryIterator::iterateOver(gIOServicePlane,
786 kIORegistryIterateRecursively);
787 if (!iter) {
788 return kIOReturnNoMemory;
789 }
790
791 do {
792 iter->reset();
793 while ((service = (IOService *)iter->getNextObject())) {
794 service->resetRematchProperties();
795 }
796 } while (!service && !iter->isValid());
797
798 /* Remove all dext personalities */
799 removeDrivers(false, ^(OSDictionary *dict) {
800 return dict->getObject(gIOUserServerNameKey) != NULL;
801 });
802
803 return kIOReturnSuccess;
804 }
805
806 IOReturn
807 IOCatalogue::terminateDriversForModule(
808 OSString * moduleName,
809 bool unload)
810 {
811 IOReturn ret;
812 OSSharedPtr<OSDictionary> dict;
813 OSSharedPtr<OSKext> kext;
814 bool isLoaded = false;
815 bool isDext = false;
816
817 /* Check first if the kext currently has any linkage dependents;
818 * in such a case the unload would fail so let's not terminate any
819 * IOServices (since doing so typically results in a panic when there
820 * are loaded dependencies). Note that we aren't locking the kext here
821 * so it might lose or gain dependents by the time we call unloadModule();
822 * I think that's ok, our unload can fail if a kext comes in on top of
823 * this one even after we've torn down IOService objects. Conversely,
824 * if we fail the unload here and then lose a library, the autounload
825 * thread will get us in short order.
826 */
827 if (OSKext::isKextWithIdentifierLoaded(moduleName->getCStringNoCopy())) {
828 isLoaded = true;
829
830 if (!OSKext::canUnloadKextWithIdentifier(moduleName,
831 /* checkClasses */ false)) {
832 ret = kOSKextReturnInUse;
833 goto finish;
834 }
835 }
836 kext = OSKext::lookupKextWithIdentifier(moduleName->getCStringNoCopy());
837 if (kext) {
838 isDext = kext->isDriverKit();
839 }
840
841 dict = OSDictionary::withCapacity(1);
842 if (!dict) {
843 ret = kIOReturnNoMemory;
844 goto finish;
845 }
846
847 dict->setObject(gIOModuleIdentifierKey.get(), moduleName);
848
849 ret = terminateDrivers(dict.get(), NULL);
850
851 if (isDext) {
852 /* Force rematching after removing personalities. Dexts are never considered to be "loaded" (from OSKext),
853 * so we can't call unloadModule() to remove personalities and start rematching. */
854 removeDrivers(dict.get(), true);
855 } else {
856 /* No goto between IOLock calls!
857 */
858 IORWLockWrite(lock);
859 if (kIOReturnSuccess == ret) {
860 ret = _removeDrivers(dict.get());
861 }
862
863 // Unload the module itself.
864 if (unload && isLoaded && ret == kIOReturnSuccess) {
865 ret = unloadModule(moduleName);
866 }
867 IORWLockUnlock(lock);
868 }
869
870 finish:
871 return ret;
872 }
873
874 IOReturn
875 IOCatalogue::terminateDriversForModule(
876 const char * moduleName,
877 bool unload)
878 {
879 OSSharedPtr<OSString> name;
880 IOReturn ret;
881
882 name = OSString::withCString(moduleName);
883 if (!name) {
884 return kIOReturnNoMemory;
885 }
886
887 ret = terminateDriversForModule(name.get(), unload);
888
889 return ret;
890 }
891
892 #if defined(__i386__) || defined(__x86_64__)
893 bool
894 IOCatalogue::startMatching( OSDictionary * matching )
895 {
896 OSSharedPtr<OSOrderedSet> set;
897
898 if (!matching) {
899 return false;
900 }
901
902 set = OSOrderedSet::withCapacity(10, IOServiceOrdering,
903 (void *)(gIOProbeScoreKey.get()));
904 if (!set) {
905 return false;
906 }
907
908 IORWLockRead(lock);
909
910 personalities->iterateObjects(^bool (const OSSymbol * key, OSObject * value) {
911 OSArray * array;
912 OSDictionary * dict;
913 unsigned int idx;
914
915 array = (OSArray *) value;
916 for (idx = 0; (dict = (OSDictionary *) array->getObject(idx)); idx++) {
917 /* This comparison must be done with only the keys in the
918 * "matching" dict to enable general matching.
919 */
920 if (dict->isEqualTo(matching, matching)) {
921 set->setObject(dict);
922 }
923 }
924 return false;
925 });
926
927 // Start device matching.
928 if (set->getCount() > 0) {
929 IOService::catalogNewDrivers(set.get());
930 generation++;
931 }
932
933 IORWLockUnlock(lock);
934
935 return true;
936 }
937 #endif /* defined(__i386__) || defined(__x86_64__) */
938
939 bool
940 IOCatalogue::startMatching( const OSSymbol * moduleName )
941 {
942 OSSharedPtr<OSOrderedSet> set;
943 OSSharedPtr<OSKext> kext;
944 OSSharedPtr<OSArray> servicesToTerminate;
945
946 if (!moduleName) {
947 return false;
948 }
949
950 set = OSOrderedSet::withCapacity(10, IOServiceOrdering,
951 (void *)(gIOProbeScoreKey.get()));
952 if (!set) {
953 return false;
954 }
955
956 IORWLockRead(lock);
957
958 kext = OSKext::lookupKextWithIdentifier(moduleName->getCStringNoCopy());
959 if (kext && kext->isDriverKit()) {
960 /* We're here because kernelmanagerd called IOCatalogueModuleLoaded after launching a dext.
961 * Determine what providers the dext would match against. If there's something already attached
962 * to the provider, terminate it.
963 *
964 * This is only safe to do for HID dexts.
965 */
966 OSSharedPtr<OSArray> dextPersonalities = kext->copyPersonalitiesArray();
967
968 if (!dextPersonalities) {
969 return false;
970 }
971
972 servicesToTerminate = OSArray::withCapacity(1);
973 if (!servicesToTerminate) {
974 return false;
975 }
976
977 dextPersonalities->iterateObjects(^bool (OSObject * obj) {
978 OSDictionary * personality = OSDynamicCast(OSDictionary, obj);
979 OSSharedPtr<OSIterator> iter;
980 IOService * provider;
981 OSSharedPtr<IOService> service;
982 const OSSymbol * category;
983
984 if (personality) {
985 category = OSDynamicCast(OSSymbol, personality->getObject(gIOMatchCategoryKey));
986 if (!category) {
987 category = gIODefaultMatchCategoryKey;
988 }
989 iter = IOService::getMatchingServices(personality);
990
991 while (iter && (provider = OSDynamicCast(IOService, iter->getNextObject()))) {
992 if (provider->metaCast(gIOHIDInterfaceClassName.get()) != NULL) {
993 service.reset(provider->copyClientWithCategory(category), OSNoRetain);
994 if (service) {
995 servicesToTerminate->setObject(service);
996 }
997 }
998 }
999 }
1000
1001 return false;
1002 });
1003 }
1004
1005 personalities->iterateObjects(^bool (const OSSymbol * key, OSObject * value) {
1006 OSArray * array;
1007 OSDictionary * dict;
1008 OSObject * moduleIdentifierKernel;
1009 OSObject * moduleIdentifier;
1010 unsigned int idx;
1011
1012 array = (OSArray *) value;
1013 for (idx = 0; (dict = (OSDictionary *) array->getObject(idx)); idx++) {
1014 moduleIdentifierKernel = dict->getObject(gIOModuleIdentifierKernelKey.get());
1015 moduleIdentifier = dict->getObject(gIOModuleIdentifierKey.get());
1016 if ((moduleIdentifierKernel && moduleName->isEqualTo(moduleIdentifierKernel)) ||
1017 (moduleIdentifier && moduleName->isEqualTo(moduleIdentifier))) {
1018 set->setObject(dict);
1019 }
1020 }
1021 return false;
1022 });
1023
1024 if (servicesToTerminate) {
1025 servicesToTerminate->iterateObjects(^bool (OSObject * obj) {
1026 IOService * service = OSDynamicCast(IOService, obj);
1027 if (service) {
1028 IOOptionBits terminateOptions = kIOServiceRequired;
1029 if (service->hasUserServer()) {
1030 terminateOptions |= kIOServiceTerminateNeedWillTerminate;
1031 }
1032 if (!service->terminate(terminateOptions)) {
1033 IOLog("%s: failed to terminate service %s-0x%qx with options %08llx for new dext %s\n", __FUNCTION__, service->getName(), service->getRegistryEntryID(), (long long)terminateOptions, moduleName->getCStringNoCopy());
1034 }
1035 }
1036 return false;
1037 });
1038 }
1039
1040 // Start device matching.
1041 if (set->getCount() > 0) {
1042 IOService::catalogNewDrivers(set.get());
1043 generation++;
1044 }
1045
1046 IORWLockUnlock(lock);
1047
1048 return true;
1049 }
1050
1051 void
1052 IOCatalogue::reset(void)
1053 {
1054 IOCatalogue::resetAndAddDrivers(/* no drivers; true reset */ NULL,
1055 /* doMatching */ false);
1056 return;
1057 }
1058
1059 bool
1060 IOCatalogue::resetAndAddDrivers(OSArray * drivers, bool doNubMatching)
1061 {
1062 bool result = false;
1063 OSArray * newPersonalities = NULL;// do not release
1064 const OSSymbol * key;
1065 OSArray * array;
1066 OSDictionary * thisNewPersonality = NULL;// do not release
1067 OSDictionary * thisOldPersonality = NULL;// do not release
1068 OSSharedPtr<OSDictionary> myKexts;
1069 OSSharedPtr<OSCollectionIterator> iter;
1070 OSSharedPtr<OSOrderedSet> matchSet;
1071 signed int idx, newIdx;
1072
1073 if (drivers) {
1074 newPersonalities = OSDynamicCast(OSArray, drivers);
1075 if (!newPersonalities) {
1076 goto finish;
1077 }
1078 }
1079 matchSet = OSOrderedSet::withCapacity(10, IOServiceOrdering,
1080 (void *)(gIOProbeScoreKey.get()));
1081 if (!matchSet) {
1082 goto finish;
1083 }
1084 iter = OSCollectionIterator::withCollection(personalities.get());
1085 if (!iter) {
1086 goto finish;
1087 }
1088
1089 /* need copy of loaded kexts so we can check if for loaded modules without
1090 * taking the OSKext lock. There is a potential of deadlocking if we get
1091 * an OSKext via the normal path. See 14672140.
1092 */
1093 myKexts = OSKext::copyKexts();
1094
1095 result = true;
1096
1097 IOLog("Resetting IOCatalogue.\n");
1098
1099 /* No goto finish from here to unlock.
1100 */
1101 IORWLockWrite(lock);
1102
1103 while ((key = (const OSSymbol *) iter->getNextObject())) {
1104 array = (OSArray *) personalities->getObject(key);
1105 if (!array) {
1106 continue;
1107 }
1108
1109 for (idx = 0;
1110 (thisOldPersonality = (OSDictionary *) array->getObject(idx));
1111 idx++) {
1112 if (thisOldPersonality->getObject("KernelConfigTable")) {
1113 continue;
1114 }
1115 thisNewPersonality = NULL;
1116
1117 if (newPersonalities) {
1118 for (newIdx = 0;
1119 (thisNewPersonality = (OSDictionary *) newPersonalities->getObject(newIdx));
1120 newIdx++) {
1121 /* Unlike in other functions, this comparison must be exact!
1122 * The catalogue must be able to contain personalities that
1123 * are proper supersets of others.
1124 * Do not compare just the properties present in one driver
1125 * personality or the other.
1126 */
1127 if (OSDynamicCast(OSDictionary, thisNewPersonality) == NULL) {
1128 /* skip thisNewPersonality if it is not an OSDictionary */
1129 continue;
1130 }
1131 if (thisNewPersonality->isEqualTo(thisOldPersonality)) {
1132 break;
1133 }
1134 }
1135 }
1136 if (thisNewPersonality) {
1137 // dup, ignore
1138 newPersonalities->removeObject(newIdx);
1139 } else {
1140 // not in new set - remove
1141 // only remove dictionary if this module in not loaded - 9953845
1142 if (isModuleLoadedNoOSKextLock(myKexts.get(), thisOldPersonality) == false) {
1143 if (matchSet) {
1144 matchSet->setObject(thisOldPersonality);
1145 }
1146 array->removeObject(idx);
1147 idx--;
1148 }
1149 }
1150 } // for...
1151 } // while...
1152
1153 // add new
1154 if (newPersonalities) {
1155 for (newIdx = 0;
1156 (thisNewPersonality = (OSDictionary *) newPersonalities->getObject(newIdx));
1157 newIdx++) {
1158 if (OSDynamicCast(OSDictionary, thisNewPersonality) == NULL) {
1159 /* skip thisNewPersonality if it is not an OSDictionary */
1160 continue;
1161 }
1162
1163 OSKext::uniquePersonalityProperties(thisNewPersonality);
1164 addPersonality(thisNewPersonality);
1165 matchSet->setObject(thisNewPersonality);
1166 }
1167 }
1168
1169 /* Finally, start device matching on all new & removed personalities.
1170 */
1171 if (result && doNubMatching && (matchSet->getCount() > 0)) {
1172 IOService::catalogNewDrivers(matchSet.get());
1173 generation++;
1174 }
1175
1176 IORWLockUnlock(lock);
1177
1178 finish:
1179
1180 return result;
1181 }
1182
1183 bool
1184 IOCatalogue::serialize(OSSerialize * s) const
1185 {
1186 if (!s) {
1187 return false;
1188 }
1189
1190 return super::serialize(s);
1191 }
1192
1193 bool
1194 IOCatalogue::serializeData(IOOptionBits kind, OSSerialize * s) const
1195 {
1196 kern_return_t kr = kIOReturnSuccess;
1197
1198 switch (kind) {
1199 case kIOCatalogGetContents:
1200 kr = KERN_NOT_SUPPORTED;
1201 break;
1202
1203 case kIOCatalogGetModuleDemandList:
1204 kr = KERN_NOT_SUPPORTED;
1205 break;
1206
1207 case kIOCatalogGetCacheMissList:
1208 kr = KERN_NOT_SUPPORTED;
1209 break;
1210
1211 case kIOCatalogGetROMMkextList:
1212 kr = KERN_NOT_SUPPORTED;
1213 break;
1214
1215 default:
1216 kr = kIOReturnBadArgument;
1217 break;
1218 }
1219
1220 return kr;
1221 }
1222
1223 /* isModuleLoadedNoOSKextLock - used to check to see if a kext is loaded
1224 * without taking the OSKext lock. We use this to avoid the problem
1225 * where taking the IOCatalog lock then the OSKext lock will dealock when
1226 * a kext load or unload is happening at the same time as IOCatalog changing.
1227 *
1228 * theKexts - is a dictionary of current kexts (from OSKext::copyKexts) with
1229 * key set to the kext bundle ID and value set to an OSKext object
1230 * theModuleDict - is an IOKit personality dictionary for a given module (kext)
1231 */
1232 static bool
1233 isModuleLoadedNoOSKextLock(OSDictionary *theKexts,
1234 OSDictionary *theModuleDict)
1235 {
1236 bool myResult = false;
1237 const OSString * myBundleID = NULL;// do not release
1238 OSKext * myKext = NULL; // do not release
1239
1240 if (theKexts == NULL || theModuleDict == NULL) {
1241 return myResult;
1242 }
1243
1244 // gIOModuleIdentifierKey is "CFBundleIdentifier"
1245 myBundleID = OSDynamicCast(OSString,
1246 theModuleDict->getObject(gIOModuleIdentifierKey.get()));
1247 if (myBundleID == NULL) {
1248 return myResult;
1249 }
1250
1251 myKext = OSDynamicCast(OSKext, theKexts->getObject(myBundleID->getCStringNoCopy()));
1252 if (myKext) {
1253 myResult = myKext->isLoaded();
1254 }
1255
1256 return myResult;
1257 }
1258
1259
1260 #if PRAGMA_MARK
1261 #pragma mark Obsolete Kext Loading Stuff
1262 #endif
1263 /*********************************************************************
1264 **********************************************************************
1265 *** BINARY COMPATIBILITY SECTION ***
1266 **********************************************************************
1267 **********************************************************************
1268 * These functions are no longer used are necessary for C++ binary
1269 * compatibility on i386.
1270 **********************************************************************/