xref: /xnu-8796.101.5/libkern/libkern/c++/OSKext.h (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
1 /*
2  * Copyright (c) 2008-2019 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 #ifndef _LIBKERN_OSKEXT_H
30 #define _LIBKERN_OSKEXT_H
31 
32 extern "C" {
33 #include <kern/thread_call.h>
34 #include <libkern/OSKextLibPrivate.h>
35 #include <libkern/kernel_mach_header.h>
36 #include <libkern/kxld.h>
37 #include <mach/kmod.h>
38 
39 #ifdef XNU_KERNEL_PRIVATE
40 #include <kern/thread_call.h>
41 #endif /* XNU_KERNEL_PRIVATE */
42 }
43 
44 
45 #include <libkern/OSKextLib.h>
46 #include <libkern/OSKextLibPrivate.h>
47 #include <libkern/c++/OSObject.h>
48 #include <libkern/c++/OSContainers.h>
49 
50 #include <libkern/c++/OSPtr.h>
51 #include <IOKit/IOLocks.h>
52 
53 /*********************************************************************
54 * C functions used for callbacks.
55 *********************************************************************/
56 #ifdef XNU_KERNEL_PRIVATE
57 extern "C" {
58 void osdata_kmem_free(void * ptr, unsigned int length);
59 void osdata_phys_free(void * ptr, unsigned int length);
60 void osdata_vm_deallocate(void * ptr, unsigned int length);
61 void osdata_kext_free(void * ptr, unsigned int length);
62 void kxld_log_callback(
63 	KXLDLogSubsystem    subsystem,
64 	KXLDLogLevel        level,
65 	const char        * format,
66 	va_list             argList,
67 	void              * user_data);
68 };
69 #endif /* XNU_KERNEL_PRIVATE */
70 
71 /*********************************************************************
72 * C Function Prototypes for Friend Declarations.
73 *********************************************************************/
74 class OSKext;
75 class OSDextStatistics;
76 
77 extern "C" {
78 void OSKextLog(
79 	OSKext         * aKext,
80 	OSKextLogSpec    msgLogSpec,
81 	const char     * format, ...) __printflike(3, 4);
82 
83 void OSKextVLog(
84 	OSKext         * aKext,
85 	OSKextLogSpec    msgLogSpec,
86 	const char     * format,
87 	va_list          srcArgList) __printflike(3, 0);;
88 
89 #ifdef XNU_KERNEL_PRIVATE
90 void OSKextRemoveKextBootstrap(void);
91 
92 kern_return_t OSRuntimeInitializeCPP(
93 	OSKext * kext);
94 kern_return_t OSRuntimeFinalizeCPP(
95 	OSKext * kext);
96 void OSRuntimeUnloadCPPForSegment(
97 	kernel_segment_command_t * segment);
98 void
99 OSRuntimeSignStructors(
100 	kernel_mach_header_t * header);
101 void
102 OSRuntimeSignStructorsInFileset(
103 	kernel_mach_header_t * fileset_header);
104 
105 kern_return_t is_io_catalog_send_data(
106 	mach_port_t              masterPort,
107 	uint32_t                 flag,
108 	io_buf_ptr_t             inData,
109 	mach_msg_type_number_t   inDataCount,
110 	kern_return_t          * result);
111 
112 void kmod_dump_log(vm_offset_t*, unsigned int, boolean_t);
113 void *OSKextKextForAddress(const void *addr);
114 
115 #endif /* XNU_KERNEL_PRIVATE */
116 };
117 
118 /********************************************************************/
119 #if PRAGMA_MARK
120 #pragma mark -
121 #endif
122 
123 struct list_head {
124 	struct list_head *prev;
125 	struct list_head *next;
126 };
127 
128 struct OSKextGrabPgoStruct {
129 	bool metadata;
130 	uint64_t *pSize;
131 	char *pBuffer;
132 	uint64_t bufferSize;
133 	int err;
134 	struct list_head list_head;
135 };
136 
137 #ifndef container_of
138 #define container_of(ptr, type, member) ((type*)(((uintptr_t)ptr) - offsetof(type, member)))
139 #endif
140 /********************************************************************/
141 
142 #if XNU_KERNEL_PRIVATE
143 
144 struct OSKextAccount {
145 	vm_allocation_site_t site;
146 
147 #if DEVELOPMENT || DEBUG
148 	struct os_refgrp     task_refgrp;
149 	/*
150 	 * '5' for the "task_" prefix. task_refgrp_name can be entirely dropped
151 	 * once we can directly flag the refgrp to be logged.
152 	 */
153 	char                 task_refgrp_name[5 + KMOD_MAX_NAME];
154 #endif /* DEVELOPMENT || DEBUG */
155 	uint32_t             loadTag;
156 	OSKext             * kext;
157 };
158 
159 struct OSKextActiveAccount {
160 	uintptr_t       address;
161 	uintptr_t       address_end;
162 	OSKextAccount * account;
163 };
164 typedef struct OSKextActiveAccount OSKextActiveAccount;
165 
166 class OSKextSavedMutableSegment : public OSObject {
167 	OSDeclareDefaultStructors(OSKextSavedMutableSegment);
168 public:
169 	static OSPtr<OSKextSavedMutableSegment> withSegment(kernel_segment_command_t *seg);
170 	OSReturn restoreContents(kernel_segment_command_t *seg);
171 	vm_offset_t getVMAddr() const;
172 	vm_size_t getVMSize() const;
173 	virtual void free(void) APPLE_KEXT_OVERRIDE;
174 private:
175 	bool initWithSegment(kernel_segment_command_t *seg);
176 	kernel_segment_command_t *savedSegment;
177 	vm_offset_t vmaddr;
178 	vm_size_t   vmsize;
179 	void      * data;
180 };
181 
182 typedef enum {
183 	kOSDextCrashPolicyNone,
184 	kOSDextCrashPolicyReboot,
185 } OSDextCrashPolicy;
186 
187 enum {
188 	kMaxDextCrashesInOneDayDefault = 3,
189 };
190 
191 class OSDextStatistics : public OSObject {
192 	OSDeclareDefaultStructors(OSDextStatistics);
193 public:
194 	static OSPtr<OSDextStatistics> create();
195 	virtual bool init() APPLE_KEXT_OVERRIDE;
196 	virtual void free() APPLE_KEXT_OVERRIDE;
197 
198 	OSDextCrashPolicy recordCrash();
199 	size_t getCrashCount();
200 
201 private:
202 	OSPtr<OSArray> crashes;
203 	IOLock * lock;
204 };
205 
206 __enum_closed_decl(OSKextInitResult, uint8_t, {
207 	kOSKextInitFailure = 0,
208 	kOSKextInitialized,
209 	kOSKextAlreadyExist,
210 });
211 
212 #endif /* XNU_KERNEL_PRIVATE */
213 
214 /*
215  * @class OSKext
216  */
217 /********************************************************************/
218 class OSKext : public OSObject
219 {
220 	OSDeclareDefaultStructors(OSKext);
221 
222 #if PRAGMA_MARK
223 /**************************************/
224 #pragma mark Friend Declarations
225 /**************************************/
226 #endif
227 	friend class IOCatalogue;
228 	friend class KLDBootstrap;
229 	friend class OSMetaClass;
230 
231 	friend int OSKextGrabPgoData(uuid_t uuid,
232 	    uint64_t *pSize,
233 	    char *pBuffer,
234 	    uint64_t bufferSize,
235 	    int wait_for_unload,
236 	    int metadata);
237 
238 #ifdef XNU_KERNEL_PRIVATE
239 	friend void OSKextVLog(
240 		OSKext         * aKext,
241 		OSKextLogSpec    msgLogSpec,
242 		const char     * format,
243 		va_list          srcArgList) __printflike(3, 0);
244 
245 	friend void OSKextRemoveKextBootstrap(void);
246 	friend OSReturn OSKextUnloadKextWithLoadTag(uint32_t);
247 
248 	friend kern_return_t kext_request(
249 		host_priv_t                             hostPriv,
250 		/* in only */ uint32_t                 clientLogSpec,
251 		/* in only */ vm_offset_t              requestIn,
252 		/* in only */ mach_msg_type_number_t   requestLengthIn,
253 		/* out only */ vm_offset_t            * responseOut,
254 		/* out only */ mach_msg_type_number_t * responseLengthOut,
255 		/* out only */ vm_offset_t            * logDataOut,
256 		/* out only */ mach_msg_type_number_t * logDataLengthOut,
257 		/* out only */ kern_return_t          * op_result);
258 
259 	friend kxld_addr_t kern_allocate(
260 		u_long              size,
261 		KXLDAllocateFlags * flags,
262 		void              * user_data);
263 
264 	friend void kxld_log_shim(
265 		KXLDLogSubsystem    subsystem,
266 		KXLDLogLevel        level,
267 		const char        * format,
268 		va_list             argList,
269 		void              * user_data);
270 
271 	friend void _OSKextConsiderUnloads(
272 		__unused thread_call_param_t p0,
273 		__unused thread_call_param_t p1);
274 
275 	friend kern_return_t OSRuntimeInitializeCPP(
276 		OSKext * kext);
277 	friend kern_return_t OSRuntimeFinalizeCPP(
278 		OSKext * kext);
279 	friend void OSRuntimeUnloadCPPForSegment(
280 		kernel_segment_command_t * segment);
281 
282 	friend kern_return_t is_io_catalog_send_data(
283 		mach_port_t              masterPort,
284 		uint32_t                 flag,
285 		io_buf_ptr_t             inData,
286 		mach_msg_type_number_t   inDataCount,
287 		kern_return_t          * result);
288 
289 	friend void kmod_panic_dump(vm_offset_t*, unsigned int);
290 	friend void kmod_dump_log(vm_offset_t*, unsigned int, boolean_t);
291 	friend void kext_dump_panic_lists(int (*printf_func)(const char * fmt, ...));
292 	friend void *OSKextKextForAddress(const void *addr);
293 
294 #endif /* XNU_KERNEL_PRIVATE */
295 
296 private:
297 
298 /*************************
299 * Instance variables
300 *************************/
301 	OSPtr<OSDictionary>  infoDict;
302 
303 	OSPtr<const OSSymbol>    bundleID;
304 	OSPtr<OSString>    path;           // not necessarily correct :-/
305 	OSPtr<OSString>    executableRelPath;// relative to bundle
306 	OSPtr<OSString>    userExecutableRelPath;// relative to bundle
307 
308 	OSKextVersion    version;        // parsed
309 	OSKextVersion    compatibleVersion;// parsed
310 
311 /* These fields are required for tracking loaded kexts and
312  * will always have values for a loaded kext.
313  */
314 	OSKextLoadTag    loadTag;        // 'id' from old kmod_info;
315 	                                 // kOSKextInvalidLoadTag invalid
316 	kmod_info_t    * kmod_info;      // address into linkedExec./alloced for interface
317 
318 	OSPtr<OSArray>     dependencies;   // kernel resource does not have any;
319 	// links directly to kernel
320 
321 /* Only real kexts have these; interface kexts do not.
322  */
323 	OSPtr<OSData>       linkedExecutable;
324 	OSPtr<OSSet>        metaClasses;       // for C++/OSMetaClass kexts
325 
326 /* Only interface kexts have these; non-interface kexts can get at them
327  * in the linked Executable.
328  */
329 	OSPtr<OSData>       interfaceUUID;
330 	OSPtr<OSData>       driverKitUUID;
331 
332 	struct {
333 		unsigned int loggingEnabled:1;
334 
335 		unsigned int hasAllDependencies:1;
336 		unsigned int hasBleedthrough:1;
337 
338 		unsigned int interface:1;
339 		unsigned int kernelComponent:1;
340 		unsigned int prelinked:1;
341 		unsigned int builtin:1;
342 		unsigned int loaded:1;
343 		unsigned int dtraceInitialized:1;
344 		unsigned int starting:1;
345 		unsigned int started:1;
346 		unsigned int stopping:1;
347 		unsigned int unloading:1;
348 		unsigned int resetSegmentsFromVnode:1;
349 
350 		unsigned int requireExplicitLoad:1;
351 		unsigned int autounloadEnabled:1;
352 		unsigned int delayAutounload:1; // for development
353 
354 		unsigned int CPPInitialized:1;
355 		unsigned int jettisonLinkeditSeg:1;
356 		unsigned int resetSegmentsFromImmutableCopy:1;
357 		unsigned int unloadUnsupported:1;
358 		unsigned int dextToReplace:1;
359 
360 		/* The Mach-O header contains segment addresses which are unslid. */
361 		unsigned int unslidMachO:1;
362 	} flags;
363 
364 	uint32_t matchingRefCount;
365 	kc_kind_t kc_type;
366 
367 	struct list_head pendingPgoHead;
368 	uuid_t instance_uuid;
369 	OSKextAccount * account;
370 	uint32_t builtinKmodIdx;
371 	OSPtr<OSArray> savedMutableSegments;
372 	OSPtr<OSDextStatistics> dextStatistics;
373 	OSPtr<OSData> dextUniqueID;
374 	uint32_t dextLaunchedCount;
375 
376 #if PRAGMA_MARK
377 /**************************************/
378 #pragma mark Private Functions
379 /**************************************/
380 #endif
381 
382 #ifdef XNU_KERNEL_PRIVATE
383 /* Startup/shutdown phases.
384  */
385 public:
386 	static void           initialize(void);
387 	static OSPtr<OSDictionary> copyKexts(void);
388 	static OSReturn       removeKextBootstrap(void);
389 	static void           willShutdown(void);// called by IOPMrootDomain on shutdown
390 	static void           willUserspaceReboot(void);
391 	static void           resetAfterUserspaceReboot(void);
392 	static  void reportOSMetaClassInstances(
393 		const char     * kextIdentifier,
394 		OSKextLogSpec    msgLogSpec);
395 	static void OSKextLogDriverKitInfoLoad(OSKext *kext);
396 	static bool iokitDaemonAvailable(void);
397 #endif /* XNU_KERNEL_PRIVATE */
398 
399 private:
400 /* Called by power management at sleep/shutdown.
401  */
402 	static bool setLoadEnabled(bool flag);
403 	static bool setUnloadEnabled(bool flag);
404 	static bool setAutounloadsEnabled(bool flag);
405 	static bool setKernelRequestsEnabled(bool flag);
406 
407 // all getters subject to race condition, caller beware
408 	static bool getLoadEnabled(void);
409 	static bool getUnloadEnabled(void);
410 	static bool getAutounloadEnabled(void);
411 	static bool getKernelRequestsEnabled(void);
412 
413 /* Instance life cycle.
414  */
415 	static OSData *parseDextUniqueID(
416 		OSDictionary * anInfoDict,
417 		const char *dextIDCS);
418 	static void setDextUniqueIDInPersonalities(
419 		OSDictionary * anInfoDict,
420 		OSData * dextUniqueID);
421 
422 	static OSPtr<OSKext> withBooterData(
423 		OSString * deviceTreeName,
424 		OSData   * booterData);
425 	virtual bool initWithBooterData(
426 		OSString * deviceTreeName,
427 		OSData   * booterData);
428 
429 	static OSPtr<OSKext> withPrelinkedInfoDict(
430 		OSDictionary * infoDict,
431 		bool doCoalesedSlides, kc_kind_t type);
432 	virtual bool initWithPrelinkedInfoDict(
433 		OSDictionary * infoDict,
434 		bool doCoalesedSlides, kc_kind_t type);
435 	static OSSharedPtr<OSKext> withCodelessInfo(
436 		OSDictionary * infoDict, OSKextInitResult *result);
437 
438 	virtual OSKextInitResult initWithCodelessInfo(
439 		OSDictionary * infoDict);
440 
441 	static void setAllVMAttributes(void);
442 
443 	virtual bool setInfoDictionaryAndPath(
444 		OSDictionary * aDictionary,
445 		OSString     * aPath);
446 	virtual bool setExecutable(
447 		OSData       * anExecutable,
448 		OSData       * externalData        = NULL,
449 		bool           externalDataIsMkext = false);
450 	virtual OSKextInitResult registerIdentifier(void);
451 
452 	virtual void free(void) APPLE_KEXT_OVERRIDE;
453 
454 	static OSReturn removeKext(
455 		OSKext * aKext,
456 		bool     terminateServicesAndRemovePersonalitiesFlag = false);
457 
458 	virtual bool isInExcludeList(void);
459 	virtual bool isLoadable(void);
460 
461 	static OSKext * allocAndInitFakeKext(
462 		kmod_info_t *kmod_info);
463 
464 /* Mkexts.
465  */
466 #if CONFIG_KXLD
467 	static OSPtr<OSKext> withMkext2Info(
468 		OSDictionary * anInfoDict,
469 		OSData       * mkextData);
470 	virtual bool initWithMkext2Info(
471 		OSDictionary * anInfoDict,
472 		OSData       * mkextData);
473 
474 	static OSReturn readMkextArchive(
475 		OSData   * mkextData,
476 		uint32_t * checksumPtr = NULL);
477 	static OSReturn readMkext2Archive(
478 		OSData * mkextData,
479 		OSDictionary ** mkextPlistOut,
480 		uint32_t * checksumPtr = NULL);
481 
482 	static OSReturn readMkext2Archive(
483 		OSData * mkextData,
484 		OSSharedPtr<OSDictionary> &mkextPlistOut,
485 		uint32_t * checksumPtr = NULL);
486 
487 	virtual OSPtr<OSData> createMkext2FileEntry(
488 		OSData * mkextData,
489 		OSNumber * offsetNum,
490 		const char * entryName);
491 	virtual OSPtr<OSData> extractMkext2FileData(
492 		UInt8      * data,
493 		const char * name,
494 		uint32_t     compressedSize,
495 		uint32_t     fullSize);
496 #endif // CONFIG_KXLD
497 
498 /* Dependencies.
499  */
500 	virtual bool resolveDependencies(
501 		OSArray * loopStack = NULL); // priv/prot
502 	virtual bool addBleedthroughDependencies(OSArray * anArray);
503 	virtual bool flushDependencies(bool forceFlag = false); // priv/prot
504 	virtual uint32_t  getNumDependencies(void);
505 	virtual OSArray * getDependencies(void);
506 
507 /* User-space requests (load/generic).
508  */
509 	static OSReturn loadFromMkext(
510 		OSKextLogSpec   clientLogSpec,
511 		char          * mkextBuffer,
512 		uint32_t        mkextBufferLength,
513 		char         ** logInfoOut,
514 		uint32_t      * logInfoLengthOut);
515 	static OSReturn handleRequest(
516 		host_priv_t     hostPriv,
517 		OSKextLogSpec   clientLogSpec,
518 		char          * requestBuffer,
519 		uint32_t        requestLength,
520 		char         ** responseOut,
521 		uint32_t      * responseLengthOut,
522 		char         ** logInfoOut,
523 		uint32_t      * logInfoLengthOut);
524 	static OSReturn loadCodelessKext(
525 		OSString      * kextIdentifier,
526 		OSDictionary  * requestDict);
527 	static OSReturn serializeLogInfo(
528 		OSArray   * logInfoArray,
529 		char     ** logInfoOut,
530 		uint32_t  * logInfoLengthOut);
531 
532 /* Loading.
533  */
534 	static bool addKextsFromKextCollection(kernel_mach_header_t *mh,
535 	    OSDictionary *infoDict, const char *text_seg_name,
536 	    OSData **kcUUID, kc_kind_t type);
537 
538 	static bool addKextsFromKextCollection(kernel_mach_header_t *mh,
539 	    OSDictionary *infoDict, const char *text_seg_name,
540 	    OSSharedPtr<OSData> &kcUUID, kc_kind_t type);
541 
542 	static bool registerDeferredKextCollection(kernel_mach_header_t *mh,
543 	    OSSharedPtr<OSObject> &parsedXML, kc_kind_t type);
544 	static OSSharedPtr<OSObject> consumeDeferredKextCollection(kc_kind_t type);
545 
546 	virtual OSReturn load(
547 		OSKextExcludeLevel   startOpt         = kOSKextExcludeNone,
548 		OSKextExcludeLevel   startMatchingOpt = kOSKextExcludeAll,
549 		OSArray            * personalityNames = NULL);// priv/prot
550 	virtual OSReturn unload(void);
551 	static OSReturn queueKextNotification(
552 		const char * notificationName,
553 		OSString   * kextIdentifier);
554 
555 	static void recordIdentifierRequest(
556 		OSString * kextIdentifier);
557 
558 	virtual OSReturn slidePrelinkedExecutable(bool doCoalesedSlides);
559 	virtual OSReturn loadExecutable(void);
560 	virtual void     jettisonLinkeditSegment(void);
561 	virtual void     jettisonDATASegmentPadding(void);
562 	static  void     considerDestroyingLinkContext(void);
563 	virtual OSData * getExecutable(void);
564 	virtual void     setLinkedExecutable(OSData * anExecutable);
565 
566 #if CONFIG_DTRACE
567 	friend  void OSKextRegisterKextsWithDTrace(void);
568 	static  void registerKextsWithDTrace(void);
569 	virtual void registerWithDTrace(void);
570 	virtual void unregisterWithDTrace(void);
571 #endif /* CONFIG_DTRACE */
572 
573 	virtual OSReturn start(bool startDependenciesFlag = true);
574 	virtual OSReturn stop(void);
575 	virtual OSReturn setVMAttributes(bool protect, bool wire);
576 	virtual boolean_t segmentShouldBeWired(kernel_segment_command_t *seg);
577 	virtual OSReturn validateKextMapping(bool startFlag);
578 	virtual boolean_t verifySegmentMapping(kernel_segment_command_t *seg);
579 
580 	static OSPtr<OSArray> copyAllKextPersonalities(
581 		bool filterSafeBootFlag = false);
582 
583 	static  void  setPrelinkedPersonalities(OSArray * personalitiesArray);
584 
585 	static  void  sendAllKextPersonalitiesToCatalog(
586 		bool startMatching = false);
587 	virtual OSReturn  sendPersonalitiesToCatalog(
588 		bool      startMatching    = false,
589 		OSArray * personalityNames = NULL);
590 
591 	static bool canUnloadKextWithIdentifier(
592 		OSString * kextIdentifier,
593 		bool       checkClassesFlag = true);
594 
595 	static OSReturn autounloadKext(OSKext * aKext);
596 
597 /* Sync with user space.
598  */
599 	static OSReturn pingIOKitDaemon(void);
600 
601 /* Getting info about loaded kexts (kextstat).
602  */
603 	static  OSPtr<OSDictionary> copyLoadedKextInfo(
604 		OSArray * kextIdentifiers = NULL,
605 		OSArray * keys = NULL);
606 	static  OSPtr<OSDictionary> copyLoadedKextInfoByUUID(
607 		OSArray * kextIdentifiers = NULL,
608 		OSArray * keys = NULL);
609 	static  OSPtr<OSDictionary> copyKextCollectionInfo(
610 		OSDictionary *requestDict,
611 		OSArray  *infoKeys = NULL);
612 	static OSPtr<OSData> copyKextUUIDForAddress(OSNumber *address = NULL);
613 	static OSPtr<OSArray> copyDextsInfo(
614 		OSArray * kextIdentifiers = NULL,
615 		OSArray * keys = NULL);
616 	virtual OSPtr<OSDictionary> copyInfo(OSArray * keys = NULL);
617 
618 /* Logging to user space.
619  */
620 	static OSKextLogSpec setUserSpaceLogFilter(
621 		OSKextLogSpec  userLogSpec,
622 		bool           captureFlag = false);
623 	static OSPtr<OSArray> clearUserSpaceLogFilter(void);
624 	static OSKextLogSpec getUserSpaceLogFilter(void);
625 
626 /* OSMetaClasses defined by kext.
627  */
628 	virtual OSReturn addClass(
629 		OSMetaClass * aClass,
630 		uint32_t     numClasses);
631 	virtual OSReturn removeClass(
632 		OSMetaClass * aClass);
633 	virtual bool    hasOSMetaClassInstances(void);
634 	virtual OSSet * getMetaClasses(void);
635 
636 	virtual void reportOSMetaClassInstances(
637 		OSKextLogSpec msgLogSpec);
638 
639 /* Resource requests and other callback stuff.
640  */
641 	static OSReturn loadFileSetKexts(OSDictionary * requestDict);
642 
643 	static OSReturn loadKCFileSet(const char *filepath, kc_kind_t type);
644 
645 #if defined(__x86_64__) || defined(__i386__)
646 	static OSReturn mapKCFileSet(
647 		void                 *control,
648 		vm_size_t            fsize,
649 		kernel_mach_header_t **mh,
650 		off_t                file_offset,
651 		uintptr_t            *slide,
652 		bool                 pageable,
653 		void                 *map_entry_buffer);
654 	static OSReturn protectKCFileSet(
655 		kernel_mach_header_t *mh,
656 		kc_kind_t            type);
657 	static OSReturn mapKCTextSegment(
658 		void                 *control,
659 		kernel_mach_header_t **mhp,
660 		off_t                file_offset,
661 		uintptr_t            *slide,
662 		void                 *map_entry_list);
663 	static void freeKCFileSetcontrol(void);
664 	OSReturn resetKCFileSetSegments(void);
665 #endif //(__x86_64__) || defined(__i386__)
666 
667 	static void jettisonFileSetLinkeditSegment(kernel_mach_header_t *mh);
668 	static OSReturn validateKCFileSetUUID(
669 		OSDictionary         *infoDict,
670 		kc_kind_t            type);
671 
672 	static OSReturn validateKCUUIDfromPrelinkInfo(
673 		uuid_t               *loaded_kcuuid,
674 		kc_kind_t             type,
675 		OSDictionary         *infoDict,
676 		const char           *uuid_key);
677 
678 	static OSReturn dispatchResource(OSDictionary * requestDict);
679 
680 	static OSReturn setMissingAuxKCBundles(OSDictionary * requestDict);
681 
682 	static OSReturn setAuxKCBundleAvailable(OSString *kextIdentifier,
683 	    OSDictionary *requestDict);
684 
685 	static OSReturn dequeueCallbackForRequestTag(
686 		OSKextRequestTag    requestTag,
687 		LIBKERN_RETURNS_RETAINED OSDictionary     ** callbackRecordOut);
688 	static OSReturn dequeueCallbackForRequestTag(
689 		OSNumber     *    requestTagNum,
690 		LIBKERN_RETURNS_RETAINED OSDictionary ** callbackRecordOut);
691 
692 	static OSReturn dequeueCallbackForRequestTag(
693 		OSKextRequestTag    requestTag,
694 		OSSharedPtr<OSDictionary> &callbackRecordOut);
695 	static OSReturn dequeueCallbackForRequestTag(
696 		OSNumber     *    requestTagNum,
697 		OSSharedPtr<OSDictionary> &callbackRecordOut);
698 
699 	static void invokeRequestCallback(
700 		OSDictionary * callbackRecord,
701 		OSReturn         requestResult);
702 	virtual void invokeOrCancelRequestCallbacks(
703 		OSReturn callbackResult,
704 		bool     invokeFlag = true);
705 	virtual uint32_t countRequestCallbacks(void);
706 	OSReturn resetMutableSegments(void);
707 	virtual OSData * getDextUniqueID(void);
708 
709 	static bool upgradeDext(
710 		OSKext * olddext,
711 		OSKext * newdext);
712 	static bool removeDext(OSKext * dext);
713 	static void replaceDextInternal(
714 		OSKext * olddext,
715 		OSKext * newdext);
716 /* panic() support.
717  */
718 public:
719 	enum {
720 		kPrintKextsLock    = 0x01,
721 		kPrintKextsUnslide = 0x02,
722 		kPrintKextsTerse   = 0x04
723 	};
724 	static void printKextsInBacktrace(
725 		vm_offset_t   * addr,
726 		unsigned int    cnt,
727 		int          (* printf_func)(const char *fmt, ...),
728 		uint32_t        flags);
729 	bool isDriverKit(void);
730 	bool isInFileset(void);
731 private:
732 	static OSKextLoadedKextSummary *summaryForAddress(const uintptr_t addr);
733 	static void *kextForAddress(const void *addr);
734 	static boolean_t summaryIsInBacktrace(
735 		OSKextLoadedKextSummary * summary,
736 		vm_offset_t             * addr,
737 		unsigned int              cnt);
738 	static void printSummary(
739 		OSKextLoadedKextSummary * summary,
740 		int                    (* printf_func)(const char *fmt, ...),
741 		uint32_t                  flags);
742 
743 	static int saveLoadedKextPanicListTyped(
744 		const char * prefix,
745 		int          invertFlag,
746 		int          libsFlag,
747 		char       * paniclist,
748 		uint32_t     list_size);
749 	static void saveLoadedKextPanicList(void);
750 	void savePanicString(bool isLoading);
751 	static void printKextPanicLists(int (*printf_func)(const char *fmt, ...));
752 
753 /* Kext summary support.
754  */
755 	static void updateLoadedKextSummaries(void);
756 	void updateLoadedKextSummary(OSKextLoadedKextSummary *summary);
757 	void updateActiveAccount(OSKextActiveAccount *accountp);
758 	static void removeDaemonExitRequests(void);
759 
760 #ifdef XNU_KERNEL_PRIVATE
761 public:
762 #endif /* XNU_KERNEL_PRIVATE */
763 
764 /* C++ Initialization.
765  */
766 	virtual void               setCPPInitialized(bool initialized = true);
767 
768 #if PRAGMA_MARK
769 /**************************************/
770 #pragma mark Public Functions
771 /**************************************/
772 #endif
773 public:
774 	// caller must release
775 	static OSPtr<OSKext> lookupKextWithIdentifier(const char * kextIdentifier);
776 	static OSPtr<OSKext> lookupKextWithIdentifier(OSString * kextIdentifier);
777 	static OSPtr<OSKext> lookupKextWithLoadTag(OSKextLoadTag aTag);
778 	static OSPtr<OSKext> lookupKextWithAddress(vm_address_t address);
779 	static OSPtr<OSKext> lookupKextWithUUID(uuid_t uuid);
780 	static OSPtr<OSKext> lookupDextWithIdentifier(OSString * dextIdentifier, OSData *dextUniqueIdentifier);
781 
782 	kernel_section_t *lookupSection(const char *segname, const char*secname);
783 
784 	static bool isKextWithIdentifierLoaded(const char * kextIdentifier);
785 
786 	static OSReturn loadKextWithIdentifier(
787 		const char       * kextIdentifier,
788 		Boolean            allowDeferFlag      = true,
789 		Boolean            delayAutounloadFlag = false,
790 		OSKextExcludeLevel startOpt            = kOSKextExcludeNone,
791 		OSKextExcludeLevel startMatchingOpt    = kOSKextExcludeAll,
792 		OSArray          * personalityNames    = NULL);
793 
794 	static OSReturn loadKextWithIdentifier(
795 		OSString         * kextIdentifier,
796 		LIBKERN_RETURNS_RETAINED_ON_ZERO OSObject        ** kextRef,
797 		Boolean            allowDeferFlag      = true,
798 		Boolean            delayAutounloadFlag = false,
799 		OSKextExcludeLevel startOpt            = kOSKextExcludeNone,
800 		OSKextExcludeLevel startMatchingOpt    = kOSKextExcludeAll,
801 		OSArray          * personalityNames    = NULL);
802 
803 	static OSReturn loadKextWithIdentifier(
804 		OSString         *    kextIdentifier,
805 		OSSharedPtr<OSObject> &kextRef,
806 		Boolean                allowDeferFlag      = true,
807 		Boolean                delayAutounloadFlag = false,
808 		OSKextExcludeLevel     startOpt            = kOSKextExcludeNone,
809 		OSKextExcludeLevel     startMatchingOpt    = kOSKextExcludeAll,
810 		OSArray              * personalityNames    = NULL);
811 
812 	static OSReturn loadKextFromKC(OSKext *theKext, OSDictionary *requestDict);
813 
814 	static void dropMatchingReferences(
815 		OSSet * kexts);
816 
817 	bool hasDependency(const OSSymbol * depID);
818 
819 	static OSReturn removeKextWithIdentifier(
820 		const char * kextIdentifier,
821 		bool         terminateServicesAndRemovePersonalitiesFlag = false);
822 	static OSReturn removeKextWithLoadTag(
823 		OSKextLoadTag loadTag,
824 		bool          terminateServicesAndRemovePersonalitiesFlag = false);
825 	static OSReturn requestDaemonLaunch(
826 		OSString        * kextIdentifier,
827 		OSString        * serverName,
828 		OSNumber        * serverTag,
829 		OSBoolean       * reslide,
830 		class IOUserServerCheckInToken * checkInToken,
831 			OSData *serverDUI);
832 	static OSReturn notifyDextUpgrade(
833 		OSString        * kextIdentifier,
834 		OSData          * dextUniqueIdentifier);
835 	static OSReturn requestResource(
836 		const char                    * kextIdentifier,
837 		const char                    * resourceName,
838 		OSKextRequestResourceCallback   callback,
839 		void                          * context,
840 		OSKextRequestTag              * requestTagOut);
841 	static OSReturn cancelRequest(
842 		OSKextRequestTag    requestTag,
843 		void             ** contextOut);
844 
845 	static void     considerUnloads(Boolean rescheduleOnlyFlag = false);
846 	static void     flushNonloadedKexts(Boolean flushPrelinkedKexts);
847 	static void     setIOKitDaemonActive(bool active = true);
848 	static void     setDeferredLoadSucceeded(Boolean succeeded = true);
849 	static void     considerRebuildOfPrelinkedKernel(void);
850 	static void     createExcludeListFromBooterData(
851 		OSDictionary * theDictionary,
852 		OSCollectionIterator * theIterator);
853 	static void     createExcludeListFromPrelinkInfo(OSArray * theInfoArray);
854 	static boolean_t updateExcludeList(OSDictionary * infoDict);
855 
856 	static bool     pendingIOKitDaemonRequests(void);
857 
858 	virtual bool    setAutounloadEnabled(bool flag);
859 
860 	virtual const OSObject   * getBundleExecutable(void);
861 	virtual const OSSymbol   * getIdentifier(void);
862 	virtual const char       * getIdentifierCString(void);
863 	virtual OSKextVersion      getVersion(void);
864 	virtual OSKextVersion      getCompatibleVersion(void);
865 	virtual bool               isLibrary(void);
866 	virtual bool               isCompatibleWithVersion(OSKextVersion aVersion);
867 	virtual OSObject         * getPropertyForHostArch(const char * key);
868 
869 	virtual OSKextLoadTag      getLoadTag(void);
870 	virtual void               getSizeInfo(uint32_t *loadSize, uint32_t *wiredSize);
871 	virtual OSPtr<OSData>          copyUUID(void);
872 	OSPtr<OSData>                  copyTextUUID(void);
873 	OSPtr<OSData>                  copyMachoUUID(const kernel_mach_header_t * header);
874 	OSPtr<OSDextStatistics>        copyDextStatistics();
875 	virtual OSPtr<OSArray>         copyPersonalitiesArray(void);
876 	static bool                copyUserExecutablePath(const OSSymbol * bundleID, char * pathResult, size_t pathSize);
877 	virtual void               setDriverKitUUID(LIBKERN_CONSUMED OSData *uuid);
878 	static  bool               incrementDextLaunchCount(OSKext *dext, OSData *dextUniqueIDToMatch);
879 	static  bool               decrementDextLaunchCount(OSString *bundleID);
880 
881 /* This removes personalities naming the kext (by CFBundleIdentifier),
882  * not all personalities defined by the kext (IOPersonalityPublisher or CFBundleIdentifier).
883  */
884 	virtual void               removePersonalitiesFromCatalog(void);
885 /*
886  * This removes the personalities naming the kext (by CFBundleIdentifier), and atomically adds
887  * the new personalities upgradedPersonalities.
888  */
889 	virtual void               updatePersonalitiesInCatalog(OSArray *upgradedPersonalities);
890 
891 /* Converts common string-valued properties to OSSymbols for lower memory consumption.
892  */
893 	static void uniquePersonalityProperties(OSDictionary * personalityDict);
894 #ifdef XNU_KERNEL_PRIVATE
895 	static void uniquePersonalityProperties(OSDictionary * personalityDict, bool defaultAddKernelBundleIdentifier);
896 #endif
897 
898 	static bool                iokitDaemonActive(void);
899 
900 	virtual bool               declaresExecutable(void); // might be missing
901 	virtual bool               isInterface(void);
902 	virtual bool               isKernel(void);
903 	virtual bool               isKernelComponent(void);
904 	virtual bool               isExecutable(void);
905 	virtual bool               isLoadableInSafeBoot(void);
906 	virtual bool               isPrelinked(void);
907 	virtual bool               isLoaded(void);
908 	virtual bool               isStarted(void);
909 	virtual bool               isCPPInitialized(void);
910 
911 	const char *
getKCTypeString(void)912 	getKCTypeString(void)
913 	{
914 		switch (kc_type) {
915 		case KCKindPrimary:
916 			return kKCTypePrimary;
917 		case KCKindPageable:
918 			return kKCTypeSystem;
919 		case KCKindAuxiliary:
920 			return kKCTypeAuxiliary;
921 		case KCKindNone:
922 			return kKCTypeCodeless;
923 		default:
924 			return "??";
925 		}
926 	}
927 };
928 
929 extern "C" void OSKextResetAfterUserspaceReboot(void);
930 
931 #endif /* !_LIBKERN_OSKEXT_H */
932