This repository was archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathOSKext.cpp
11886 lines (10213 loc) · 389 KB
/
OSKext.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2008-2016 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
extern "C" {
#include <string.h>
#include <kern/clock.h>
#include <kern/host.h>
#include <kern/kext_alloc.h>
#include <firehose/tracepoint_private.h>
#include <firehose/chunk_private.h>
#include <os/firehose_buffer_private.h>
#include <vm/vm_kern.h>
#include <kextd/kextd_mach.h>
#include <libkern/kernel_mach_header.h>
#include <libkern/kext_panic_report.h>
#include <libkern/kext_request_keys.h>
#include <libkern/mkext.h>
#include <libkern/prelink.h>
#include <libkern/version.h>
#include <libkern/zlib.h>
#include <mach/host_special_ports.h>
#include <mach/mach_vm.h>
#include <mach/mach_time.h>
#include <sys/sysctl.h>
#include <uuid/uuid.h>
// 04/18/11 - gab: <rdar://problem/9236163>
#include <sys/random.h>
#include <sys/pgo.h>
#if CONFIG_MACF
#include <sys/kauth.h>
#include <security/mac_framework.h>
#endif
};
#include <libkern/OSKextLibPrivate.h>
#include <libkern/c++/OSKext.h>
#include <libkern/c++/OSLib.h>
#include <IOKit/IOLib.h>
#include <IOKit/IOCatalogue.h>
#include <IOKit/IORegistryEntry.h>
#include <IOKit/IOService.h>
#include <IOKit/IOStatisticsPrivate.h>
#include <IOKit/IOBSD.h>
#include <san/kasan.h>
#if PRAGMA_MARK
#pragma mark External & Internal Function Protos
#endif
/*********************************************************************
*********************************************************************/
extern "C" {
extern int IODTGetLoaderInfo(const char * key, void ** infoAddr, int * infoSize);
extern void IODTFreeLoaderInfo(const char * key, void * infoAddr, int infoSize);
extern void OSRuntimeUnloadCPPForSegment(kernel_segment_command_t * segment);
extern void OSRuntimeUnloadCPP(kmod_info_t * ki, void * data);
extern ppnum_t pmap_find_phys(pmap_t pmap, addr64_t va); /* osfmk/machine/pmap.h */
}
static OSReturn _OSKextCreateRequest(
const char * predicate,
OSDictionary ** requestP);
static OSString * _OSKextGetRequestPredicate(OSDictionary * requestDict);
static OSObject * _OSKextGetRequestArgument(
OSDictionary * requestDict,
const char * argName);
static bool _OSKextSetRequestArgument(
OSDictionary * requestDict,
const char * argName,
OSObject * value);
static void * _OSKextExtractPointer(OSData * wrapper);
static OSReturn _OSDictionarySetCStringValue(
OSDictionary * dict,
const char * key,
const char * value);
static bool _OSKextInPrelinkRebuildWindow(void);
static bool _OSKextInUnloadedPrelinkedKexts(const OSSymbol * theBundleID);
// We really should add containsObject() & containsCString to OSCollection & subclasses.
// So few pad slots, though....
static bool _OSArrayContainsCString(OSArray * array, const char * cString);
#if CONFIG_KEC_FIPS
static void * GetAppleTEXTHashForKext(OSKext * theKext, OSDictionary *theInfoDict);
#endif // CONFIG_KEC_FIPS
/* Prelinked arm kexts do not have VM entries because the method we use to
* fake an entry (see libsa/bootstrap.cpp:readPrelinkedExtensions()) does
* not work on ARM. To get around that, we must free prelinked kext
* executables with ml_static_mfree() instead of kext_free().
*/
#if __i386__ || __x86_64__
#define VM_MAPPED_KEXTS 1
#define KASLR_KEXT_DEBUG 0
#define KASLR_IOREG_DEBUG 0
#elif __arm__ || __arm64__
#define VM_MAPPED_KEXTS 0
#define KASLR_KEXT_DEBUG 0
#else
#error Unsupported architecture
#endif
#if PRAGMA_MARK
#pragma mark Constants & Macros
#endif
/*********************************************************************
* Constants & Macros
*********************************************************************/
/* Use this number to create containers.
*/
#define kOSKextTypicalLoadCount (150)
/* Any kext will have at least 1 retain for the internal lookup-by-ID dict.
* A loaded kext will no dependents or external retains will have 2 retains.
*/
#define kOSKextMinRetainCount (1)
#define kOSKextMinLoadedRetainCount (2)
/**********
* Strings and substrings used in dependency resolution.
*/
#define APPLE_KEXT_PREFIX "com.apple."
#define KERNEL_LIB "com.apple.kernel"
#define PRIVATE_KPI "com.apple.kpi.private"
/* Version for compatbility pseudokexts (com.apple.kernel.*),
* compatible back to v6.0.
*/
#define KERNEL6_LIB "com.apple.kernel.6.0"
#define KERNEL6_VERSION "7.9.9"
#define KERNEL_LIB_PREFIX "com.apple.kernel."
#define KPI_LIB_PREFIX "com.apple.kpi."
#define STRING_HAS_PREFIX(s, p) (strncmp((s), (p), strlen(p)) == 0)
#define REBUILD_MAX_TIME (60 * 5) // 5 minutes
#define MINIMUM_WAKEUP_SECONDS (30)
/*********************************************************************
* infoDict keys for internally-stored data. Saves on ivar slots for
* objects we don't keep around past boot time or during active load.
*********************************************************************/
/* A usable, uncompressed file is stored under this key.
*/
#define _kOSKextExecutableKey "_OSKextExecutable"
/* An indirect reference to the executable file from an mkext
* is stored under this key.
*/
#define _kOSKextMkextExecutableReferenceKey "_OSKextMkextExecutableReference"
/* If the file is contained in a larger buffer laid down by the booter or
* sent from user space, the OSKext stores that OSData under this key so that
* references are properly tracked. This is always an mkext, right now.
*/
#define _kOSKextExecutableExternalDataKey "_OSKextExecutableExternalData"
#define OS_LOG_HDR_VERSION 1
#define NUM_OS_LOG_SECTIONS 2
#define OS_LOG_SECT_IDX 0
#define CSTRING_SECT_IDX 1
#if PRAGMA_MARK
#pragma mark Typedefs
#endif
/*********************************************************************
* Typedefs
*********************************************************************/
/*********************************************************************
* osLogDataHeaderRef describes the header information of an OSData
* object that is returned when querying for kOSBundleLogStringsKey.
* We currently return information regarding 2 sections - os_log and
* cstring. In the case that the os_log section doesn't exist, we just
* return an offset and length of 0 for that section.
*********************************************************************/
typedef struct osLogDataHeader {
uint32_t version;
uint32_t sect_count;
struct {
uint32_t sect_offset;
uint32_t sect_size;
} sections[0];
} osLogDataHeaderRef;
/*********************************************************************
* MkextEntryRef describes the contents of an OSData object
* referencing a file entry from an mkext so that we can uncompress
* (if necessary) and extract it on demand.
*
* It contains the mkextVersion in case we ever wind up supporting
* multiple mkext formats. Mkext format 1 is officially retired as of
* Snow Leopard.
*********************************************************************/
typedef struct MkextEntryRef {
mkext_basic_header * mkext; // beginning of whole mkext file
void * fileinfo; // mkext2_file_entry or equiv; see mkext.h
} MkextEntryRef;
#if PRAGMA_MARK
#pragma mark Global and static Module Variables
#endif
/*********************************************************************
* Global & static variables, used to keep track of kexts.
*********************************************************************/
static bool sPrelinkBoot = false;
static bool sSafeBoot = false;
static bool sKeepSymbols = false;
/*********************************************************************
* sKextLock is the principal lock for OSKext, and guards all static
* and global variables not owned by other locks (declared further
* below). It must be taken by any entry-point method or function,
* including internal functions called on scheduled threads.
*
* sKextLock and sKextInnerLock are recursive due to multiple functions
* that are called both externally and internally. The other locks are
* nonrecursive.
*
* Which locks are taken depends on what they protect, but if more than
* one must be taken, they must always be locked in this order
* (and unlocked in reverse order) to prevent deadlocks:
*
* 1. sKextLock
* 2. sKextInnerLock
* 3. sKextSummariesLock
* 4. sKextLoggingLock
*/
static IORecursiveLock * sKextLock = NULL;
static OSDictionary * sKextsByID = NULL;
static OSDictionary * sExcludeListByID = NULL;
static OSArray * sLoadedKexts = NULL;
static OSArray * sUnloadedPrelinkedKexts = NULL;
// Requests to kextd waiting to be picked up.
static OSArray * sKernelRequests = NULL;
// Identifier of kext load requests in sKernelRequests
static OSSet * sPostedKextLoadIdentifiers = NULL;
static OSArray * sRequestCallbackRecords = NULL;
// Identifiers of all kexts ever requested in kernel; used for prelinked kernel
static OSSet * sAllKextLoadIdentifiers = NULL;
static KXLDContext * sKxldContext = NULL;
static uint32_t sNextLoadTag = 0;
static uint32_t sNextRequestTag = 0;
static bool sUserLoadsActive = false;
static bool sKextdActive = false;
static bool sDeferredLoadSucceeded = false;
static bool sConsiderUnloadsExecuted = false;
#if NO_KEXTD
static bool sKernelRequestsEnabled = false;
#else
static bool sKernelRequestsEnabled = true;
#endif
static bool sLoadEnabled = true;
static bool sUnloadEnabled = true;
/*********************************************************************
* Stuff for the OSKext representing the kernel itself.
**********/
static OSKext * sKernelKext = NULL;
/* Set up a fake kmod_info struct for the kernel.
* It's used in OSRuntime.cpp to call OSRuntimeInitializeCPP()
* before OSKext is initialized; that call only needs the name
* and address to be set correctly.
*
* We don't do much else with the kerne's kmod_info; we never
* put it into the kmod list, never adjust the reference count,
* and never have kernel components reference it.
* For that matter, we don't do much with kmod_info structs
* at all anymore! We just keep them filled in for gdb and
* binary compability.
*/
kmod_info_t g_kernel_kmod_info = {
/* next */ 0,
/* info_version */ KMOD_INFO_VERSION,
/* id */ 0, // loadTag: kernel is always 0
/* name */ kOSKextKernelIdentifier, // bundle identifier
/* version */ "0", // filled in in OSKext::initialize()
/* reference_count */ -1, // never adjusted; kernel never unloads
/* reference_list */ NULL,
/* address */ 0,
/* size */ 0, // filled in in OSKext::initialize()
/* hdr_size */ 0,
/* start */ 0,
/* stop */ 0
};
extern "C" {
// symbol 'kmod' referenced in: model_dep.c, db_trace.c, symbols.c, db_low_trace.c,
// dtrace.c, dtrace_glue.h, OSKext.cpp, locore.s, lowmem_vectors.s,
// misc_protos.h, db_low_trace.c, kgmacros
// 'kmod' is a holdover from the old kmod system, we can't rename it.
kmod_info_t * kmod = NULL;
#define KEXT_PANICLIST_SIZE (2 * PAGE_SIZE)
static char * loaded_kext_paniclist = NULL;
static uint32_t loaded_kext_paniclist_size = 0;
AbsoluteTime last_loaded_timestamp;
static char last_loaded_str_buf[2*KMOD_MAX_NAME];
static u_long last_loaded_strlen = 0;
static void * last_loaded_address = NULL;
static u_long last_loaded_size = 0;
AbsoluteTime last_unloaded_timestamp;
static char last_unloaded_str_buf[2*KMOD_MAX_NAME];
static u_long last_unloaded_strlen = 0;
static void * last_unloaded_address = NULL;
static u_long last_unloaded_size = 0;
/*********************************************************************
* sKextInnerLock protects against cross-calls with IOService and
* IOCatalogue, and owns the variables declared immediately below.
*
* Note that sConsiderUnloadsExecuted above belongs to sKextLock!
*
* When both sKextLock and sKextInnerLock need to be taken,
* always lock sKextLock first and unlock it second. Never take both
* locks in an entry point to OSKext; if you need to do so, you must
* spawn an independent thread to avoid potential deadlocks for threads
* calling into OSKext.
**********/
static IORecursiveLock * sKextInnerLock = NULL;
static bool sAutounloadEnabled = true;
static bool sConsiderUnloadsCalled = false;
static bool sConsiderUnloadsPending = false;
static unsigned int sConsiderUnloadDelay = 60; // seconds
static thread_call_t sUnloadCallout = 0;
static thread_call_t sDestroyLinkContextThread = 0; // one-shot, one-at-a-time thread
static bool sSystemSleep = false; // true when system going to sleep
static AbsoluteTime sLastWakeTime; // last time we woke up
/*********************************************************************
* Backtraces can be printed at various times so we need a tight lock
* on data used for that. sKextSummariesLock protects the variables
* declared immediately below.
*
* gLoadedKextSummaries is accessed by other modules, but only during
* a panic so the lock isn't needed then.
*
* gLoadedKextSummaries has the "used" attribute in order to ensure
* that it remains visible even when we are performing extremely
* aggressive optimizations, as it is needed to allow the debugger
* to automatically parse the list of loaded kexts.
**********/
static IOLock * sKextSummariesLock = NULL;
extern "C" lck_spin_t vm_allocation_sites_lock;
static IOSimpleLock * sKextAccountsLock = &vm_allocation_sites_lock;
void (*sLoadedKextSummariesUpdated)(void) = OSKextLoadedKextSummariesUpdated;
OSKextLoadedKextSummaryHeader * gLoadedKextSummaries __attribute__((used)) = NULL;
uint64_t gLoadedKextSummariesTimestamp __attribute__((used)) = 0;
static size_t sLoadedKextSummariesAllocSize = 0;
static OSKextActiveAccount * sKextAccounts;
static uint32_t sKextAccountsCount;
};
/*********************************************************************
* sKextLoggingLock protects the logging variables declared immediately below.
**********/
static IOLock * sKextLoggingLock = NULL;
static const OSKextLogSpec kDefaultKernelLogFilter = kOSKextLogBasicLevel |
kOSKextLogVerboseFlagsMask;
static OSKextLogSpec sKernelLogFilter = kDefaultKernelLogFilter;
static bool sBootArgLogFilterFound = false;
SYSCTL_UINT(_debug, OID_AUTO, kextlog, CTLFLAG_RW | CTLFLAG_LOCKED, &sKernelLogFilter,
0, "kernel kext logging");
static OSKextLogSpec sUserSpaceKextLogFilter = kOSKextLogSilentFilter;
static OSArray * sUserSpaceLogSpecArray = NULL;
static OSArray * sUserSpaceLogMessageArray = NULL;
/*********
* End scope for sKextInnerLock-protected variables.
*********************************************************************/
/*********************************************************************
helper function used for collecting PGO data upon unload of a kext
*/
static int OSKextGrabPgoDataLocked(OSKext *kext,
bool metadata,
uuid_t instance_uuid,
uint64_t *pSize,
char *pBuffer,
uint64_t bufferSize);
/**********************************************************************/
#if PRAGMA_MARK
#pragma mark OSData callbacks (need to move to OSData)
#endif
/*********************************************************************
* C functions used for callbacks.
*********************************************************************/
extern "C" {
void osdata_kmem_free(void * ptr, unsigned int length) {
kmem_free(kernel_map, (vm_address_t)ptr, length);
return;
}
void osdata_phys_free(void * ptr, unsigned int length) {
ml_static_mfree((vm_offset_t)ptr, length);
return;
}
void osdata_vm_deallocate(void * ptr, unsigned int length)
{
(void)vm_deallocate(kernel_map, (vm_offset_t)ptr, length);
return;
}
void osdata_kext_free(void * ptr, unsigned int length)
{
(void)kext_free((vm_offset_t)ptr, length);
}
};
#if PRAGMA_MARK
#pragma mark KXLD Allocation Callback
#endif
/*********************************************************************
* KXLD Allocation Callback
*********************************************************************/
kxld_addr_t
kern_allocate(
u_long size,
KXLDAllocateFlags * flags,
void * user_data)
{
vm_address_t result = 0; // returned
kern_return_t mach_result = KERN_FAILURE;
bool success = false;
OSKext * theKext = (OSKext *)user_data;
u_long roundSize = round_page(size);
OSData * linkBuffer = NULL; // must release
mach_result = kext_alloc(&result, roundSize, /* fixed */ FALSE);
if (mach_result != KERN_SUCCESS) {
OSKextLog(theKext,
kOSKextLogErrorLevel |
kOSKextLogGeneralFlag,
"Can't allocate kernel memory to link %s.",
theKext->getIdentifierCString());
goto finish;
}
/* Create an OSData wrapper for the allocated buffer.
*/
linkBuffer = OSData::withBytesNoCopy((void *)result, roundSize);
if (!linkBuffer) {
OSKextLog(theKext,
kOSKextLogErrorLevel |
kOSKextLogGeneralFlag,
"Can't allocate linked executable wrapper for %s.",
theKext->getIdentifierCString());
goto finish;
}
linkBuffer->setDeallocFunction(osdata_kext_free);
OSKextLog(theKext,
kOSKextLogProgressLevel |
kOSKextLogLoadFlag | kOSKextLogLinkFlag,
"Allocated link buffer for kext %s at %p (%lu bytes).",
theKext->getIdentifierCString(),
(void *)result, (unsigned long)roundSize);
theKext->setLinkedExecutable(linkBuffer);
*flags = kKxldAllocateWritable;
success = true;
finish:
if (!success && result) {
kext_free(result, roundSize);
result = 0;
}
OSSafeReleaseNULL(linkBuffer);
return (kxld_addr_t)result;
}
/*********************************************************************
*********************************************************************/
void
kxld_log_callback(
KXLDLogSubsystem subsystem,
KXLDLogLevel level,
const char * format,
va_list argList,
void * user_data)
{
OSKext *theKext = (OSKext *) user_data;
OSKextLogSpec logSpec = 0;
switch (subsystem) {
case kKxldLogLinking:
logSpec |= kOSKextLogLinkFlag;
break;
case kKxldLogPatching:
logSpec |= kOSKextLogPatchFlag;
break;
}
switch (level) {
case kKxldLogExplicit:
logSpec |= kOSKextLogExplicitLevel;
break;
case kKxldLogErr:
logSpec |= kOSKextLogErrorLevel;
break;
case kKxldLogWarn:
logSpec |= kOSKextLogWarningLevel;
break;
case kKxldLogBasic:
logSpec |= kOSKextLogProgressLevel;
break;
case kKxldLogDetail:
logSpec |= kOSKextLogDetailLevel;
break;
case kKxldLogDebug:
logSpec |= kOSKextLogDebugLevel;
break;
}
OSKextVLog(theKext, logSpec, format, argList);
}
#if PRAGMA_MARK
#pragma mark IOStatistics defines
#endif
#if IOKITSTATS
#define notifyKextLoadObservers(kext, kmod_info) \
do { \
IOStatistics::onKextLoad(kext, kmod_info); \
} while (0)
#define notifyKextUnloadObservers(kext) \
do { \
IOStatistics::onKextUnload(kext); \
} while (0)
#define notifyAddClassObservers(kext, addedClass, flags) \
do { \
IOStatistics::onClassAdded(kext, addedClass); \
} while (0)
#define notifyRemoveClassObservers(kext, removedClass, flags) \
do { \
IOStatistics::onClassRemoved(kext, removedClass); \
} while (0)
#else
#define notifyKextLoadObservers(kext, kmod_info)
#define notifyKextUnloadObservers(kext)
#define notifyAddClassObservers(kext, addedClass, flags)
#define notifyRemoveClassObservers(kext, removedClass, flags)
#endif /* IOKITSTATS */
#if PRAGMA_MARK
#pragma mark Module Config (Startup & Shutdown)
#endif
/*********************************************************************
* Module Config (Class Definition & Class Methods)
*********************************************************************/
#define super OSObject
OSDefineMetaClassAndStructors(OSKext, OSObject)
/*********************************************************************
*********************************************************************/
/* static */
void
OSKext::initialize(void)
{
OSData * kernelExecutable = NULL; // do not release
u_char * kernelStart = NULL; // do not free
size_t kernelLength = 0;
OSString * scratchString = NULL; // must release
IORegistryEntry * registryRoot = NULL; // do not release
OSNumber * kernelCPUType = NULL; // must release
OSNumber * kernelCPUSubtype = NULL; // must release
OSKextLogSpec bootLogFilter = kOSKextLogSilentFilter;
bool setResult = false;
uint64_t * timestamp = 0;
char bootArgBuffer[16]; // for PE_parse_boot_argn w/strings
/* This must be the first thing allocated. Everything else grabs this lock.
*/
sKextLock = IORecursiveLockAlloc();
sKextInnerLock = IORecursiveLockAlloc();
sKextSummariesLock = IOLockAlloc();
sKextLoggingLock = IOLockAlloc();
assert(sKextLock);
assert(sKextInnerLock);
assert(sKextSummariesLock);
assert(sKextLoggingLock);
sKextsByID = OSDictionary::withCapacity(kOSKextTypicalLoadCount);
sLoadedKexts = OSArray::withCapacity(kOSKextTypicalLoadCount);
sUnloadedPrelinkedKexts = OSArray::withCapacity(kOSKextTypicalLoadCount / 10);
sKernelRequests = OSArray::withCapacity(0);
sPostedKextLoadIdentifiers = OSSet::withCapacity(0);
sAllKextLoadIdentifiers = OSSet::withCapacity(kOSKextTypicalLoadCount);
sRequestCallbackRecords = OSArray::withCapacity(0);
assert(sKextsByID && sLoadedKexts && sKernelRequests &&
sPostedKextLoadIdentifiers && sAllKextLoadIdentifiers &&
sRequestCallbackRecords && sUnloadedPrelinkedKexts);
/* Read the log flag boot-args and set the log flags.
*/
if (PE_parse_boot_argn("kextlog", &bootLogFilter, sizeof(bootLogFilter))) {
sBootArgLogFilterFound = true;
sKernelLogFilter = bootLogFilter;
// log this if any flags are set
OSKextLog(/* kext */ NULL,
kOSKextLogBasicLevel |
kOSKextLogFlagsMask,
"Kernel kext log filter 0x%x per kextlog boot arg.",
(unsigned)sKernelLogFilter);
}
sSafeBoot = PE_parse_boot_argn("-x", bootArgBuffer,
sizeof(bootArgBuffer)) ? true : false;
if (sSafeBoot) {
OSKextLog(/* kext */ NULL,
kOSKextLogWarningLevel |
kOSKextLogGeneralFlag,
"SAFE BOOT DETECTED - "
"only valid OSBundleRequired kexts will be loaded.");
}
PE_parse_boot_argn("keepsyms", &sKeepSymbols, sizeof(sKeepSymbols));
#if KASAN_DYNAMIC_BLACKLIST
/* needed for function lookup */
sKeepSymbols = true;
#endif
/* Set up an OSKext instance to represent the kernel itself.
*/
sKernelKext = new OSKext;
assert(sKernelKext);
kernelStart = (u_char *)&_mh_execute_header;
kernelLength = getlastaddr() - (vm_offset_t)kernelStart;
kernelExecutable = OSData::withBytesNoCopy(
kernelStart, kernelLength);
assert(kernelExecutable);
#if KASLR_KEXT_DEBUG
IOLog("kaslr: kernel start 0x%lx end 0x%lx length %lu vm_kernel_slide %llu (0x%016lx) \n",
(unsigned long)kernelStart,
(unsigned long)getlastaddr(),
kernelLength,
vm_kernel_slide, vm_kernel_slide);
#endif
sKernelKext->loadTag = sNextLoadTag++; // the kernel is load tag 0
sKernelKext->bundleID = OSSymbol::withCString(kOSKextKernelIdentifier);
sKernelKext->version = OSKextParseVersionString(osrelease);
sKernelKext->compatibleVersion = sKernelKext->version;
sKernelKext->linkedExecutable = kernelExecutable;
sKernelKext->flags.hasAllDependencies = 1;
sKernelKext->flags.kernelComponent = 1;
sKernelKext->flags.prelinked = 0;
sKernelKext->flags.loaded = 1;
sKernelKext->flags.started = 1;
sKernelKext->flags.CPPInitialized = 0;
sKernelKext->flags.jettisonLinkeditSeg = 0;
sKernelKext->kmod_info = &g_kernel_kmod_info;
strlcpy(g_kernel_kmod_info.version, osrelease,
sizeof(g_kernel_kmod_info.version));
g_kernel_kmod_info.size = kernelLength;
g_kernel_kmod_info.id = sKernelKext->loadTag;
/* Cons up an info dict, so we don't have to have special-case
* checking all over.
*/
sKernelKext->infoDict = OSDictionary::withCapacity(5);
assert(sKernelKext->infoDict);
setResult = sKernelKext->infoDict->setObject(kCFBundleIdentifierKey,
sKernelKext->bundleID);
assert(setResult);
setResult = sKernelKext->infoDict->setObject(kOSKernelResourceKey,
kOSBooleanTrue);
assert(setResult);
scratchString = OSString::withCStringNoCopy(osrelease);
assert(scratchString);
setResult = sKernelKext->infoDict->setObject(kCFBundleVersionKey,
scratchString);
assert(setResult);
OSSafeReleaseNULL(scratchString);
scratchString = OSString::withCStringNoCopy("mach_kernel");
assert(scratchString);
setResult = sKernelKext->infoDict->setObject(kCFBundleNameKey,
scratchString);
assert(setResult);
OSSafeReleaseNULL(scratchString);
/* Add the kernel kext to the bookkeeping dictionaries. Note that
* the kernel kext doesn't have a kmod_info struct. copyInfo()
* gathers info from other places anyhow.
*/
setResult = sKextsByID->setObject(sKernelKext->bundleID, sKernelKext);
assert(setResult);
setResult = sLoadedKexts->setObject(sKernelKext);
assert(setResult);
sKernelKext->release();
registryRoot = IORegistryEntry::getRegistryRoot();
kernelCPUType = OSNumber::withNumber(
(long long unsigned int)_mh_execute_header.cputype,
8 * sizeof(_mh_execute_header.cputype));
kernelCPUSubtype = OSNumber::withNumber(
(long long unsigned int)_mh_execute_header.cpusubtype,
8 * sizeof(_mh_execute_header.cpusubtype));
assert(registryRoot && kernelCPUSubtype && kernelCPUType);
registryRoot->setProperty(kOSKernelCPUTypeKey, kernelCPUType);
registryRoot->setProperty(kOSKernelCPUSubtypeKey, kernelCPUSubtype);
OSSafeReleaseNULL(kernelCPUType);
OSSafeReleaseNULL(kernelCPUSubtype);
timestamp = __OSAbsoluteTimePtr(&last_loaded_timestamp);
*timestamp = 0;
timestamp = __OSAbsoluteTimePtr(&last_unloaded_timestamp);
*timestamp = 0;
timestamp = __OSAbsoluteTimePtr(&sLastWakeTime);
*timestamp = 0;
OSKextLog(/* kext */ NULL,
kOSKextLogProgressLevel |
kOSKextLogGeneralFlag,
"Kext system initialized.");
notifyKextLoadObservers(sKernelKext, sKernelKext->kmod_info);
return;
}
/*********************************************************************
* This could be in OSKextLib.cpp but we need to hold a lock
* while removing all the segments and sKextLock will do.
*********************************************************************/
/* static */
OSReturn
OSKext::removeKextBootstrap(void)
{
OSReturn result = kOSReturnError;
static bool alreadyDone = false;
const char * dt_kernel_header_name = "Kernel-__HEADER";
const char * dt_kernel_symtab_name = "Kernel-__SYMTAB";
kernel_mach_header_t * dt_mach_header = NULL;
int dt_mach_header_size = 0;
struct symtab_command * dt_symtab = NULL;
int dt_symtab_size = 0;
int dt_result = 0;
kernel_segment_command_t * seg_to_remove = NULL;
#if __arm__ || __arm64__
const char * dt_segment_name = NULL;
void * segment_paddress = NULL;
int segment_size = 0;
#endif
/* This must be the very first thing done by this function.
*/
IORecursiveLockLock(sKextLock);
/* If we already did this, it's a success.
*/
if (alreadyDone) {
result = kOSReturnSuccess;
goto finish;
}
OSKextLog(/* kext */ NULL,
kOSKextLogProgressLevel |
kOSKextLogGeneralFlag,
"Jettisoning kext bootstrap segments.");
/*****
* Dispose of unnecessary stuff that the booter didn't need to load.
*/
dt_result = IODTGetLoaderInfo(dt_kernel_header_name,
(void **)&dt_mach_header, &dt_mach_header_size);
if (dt_result == 0 && dt_mach_header) {
IODTFreeLoaderInfo(dt_kernel_header_name, (void *)dt_mach_header,
round_page_32(dt_mach_header_size));
}
dt_result = IODTGetLoaderInfo(dt_kernel_symtab_name,
(void **)&dt_symtab, &dt_symtab_size);
if (dt_result == 0 && dt_symtab) {
IODTFreeLoaderInfo(dt_kernel_symtab_name, (void *)dt_symtab,
round_page_32(dt_symtab_size));
}
/*****
* KLD bootstrap segment.
*/
// xxx - should rename KLD segment
seg_to_remove = getsegbyname("__KLD");
if (seg_to_remove) {
OSRuntimeUnloadCPPForSegment(seg_to_remove);
}
#if __arm__ || __arm64__
#if !(defined(KERNEL_INTEGRITY_KTRR))
/* Free the memory that was set up by bootx.
*/
dt_segment_name = "Kernel-__KLD";
if (0 == IODTGetLoaderInfo(dt_segment_name, &segment_paddress, &segment_size)) {
/* We cannot free this with KTRR enabled, as we cannot
* update the permissions on the KLD range this late
* in the boot process.
*/
IODTFreeLoaderInfo(dt_segment_name, (void *)segment_paddress,
(int)segment_size);
}
#endif /* !(defined(KERNEL_INTEGRITY_KTRR)) */
#elif __i386__ || __x86_64__
/* On x86, use the mapping data from the segment load command to
* unload KLD directly.
* This may invalidate any assumptions about "avail_start"
* defining the lower bound for valid physical addresses.
*/
if (seg_to_remove && seg_to_remove->vmaddr && seg_to_remove->vmsize) {
// 04/18/11 - gab: <rdar://problem/9236163>
// overwrite memory occupied by KLD segment with random data before
// releasing it.
read_frandom((void *) seg_to_remove->vmaddr, seg_to_remove->vmsize);
ml_static_mfree(seg_to_remove->vmaddr, seg_to_remove->vmsize);
}
#else
#error arch
#endif
seg_to_remove = NULL;
/*****
* Prelinked kernel's symtab (if there is one).
*/
kernel_section_t * sect;
sect = getsectbyname("__PRELINK", "__symtab");
if (sect && sect->addr && sect->size) {
ml_static_mfree(sect->addr, sect->size);
}
seg_to_remove = (kernel_segment_command_t *)getsegbyname("__LINKEDIT");
/* kxld always needs the kernel's __LINKEDIT segment, but we can make it
* pageable, unless keepsyms is set. To do that, we have to copy it from
* its booter-allocated memory, free the booter memory, reallocate proper
* managed memory, then copy the segment back in.
*/
#if CONFIG_KXLD
#if (__arm__ || __arm64__)
#error CONFIG_KXLD not expected for this arch
#endif
if (!sKeepSymbols) {
kern_return_t mem_result;
void *seg_copy = NULL;
void *seg_data = NULL;
vm_map_offset_t seg_offset = 0;
vm_map_offset_t seg_copy_offset = 0;
vm_map_size_t seg_length = 0;
seg_data = (void *) seg_to_remove->vmaddr;
seg_offset = (vm_map_offset_t) seg_to_remove->vmaddr;
seg_length = (vm_map_size_t) seg_to_remove->vmsize;
/* Allocate space for the LINKEDIT copy.
*/
mem_result = kmem_alloc(kernel_map, (vm_offset_t *) &seg_copy,
seg_length, VM_KERN_MEMORY_KEXT);
if (mem_result != KERN_SUCCESS) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel |
kOSKextLogGeneralFlag | kOSKextLogArchiveFlag,
"Can't copy __LINKEDIT segment for VM reassign.");
goto finish;
}
seg_copy_offset = (vm_map_offset_t) seg_copy;
/* Copy it out.
*/
memcpy(seg_copy, seg_data, seg_length);
/* Dump the booter memory.
*/
ml_static_mfree(seg_offset, seg_length);
/* Set up the VM region.
*/
mem_result = vm_map_enter_mem_object(
kernel_map,
&seg_offset,
seg_length, /* mask */ 0,
VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
VM_MAP_KERNEL_FLAGS_NONE,
VM_KERN_MEMORY_NONE,
(ipc_port_t)NULL,
(vm_object_offset_t) 0,
/* copy */ FALSE,
/* cur_protection */ VM_PROT_READ | VM_PROT_WRITE,
/* max_protection */ VM_PROT_ALL,
/* inheritance */ VM_INHERIT_DEFAULT);
if ((mem_result != KERN_SUCCESS) ||
(seg_offset != (vm_map_offset_t) seg_data))
{
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel |
kOSKextLogGeneralFlag | kOSKextLogArchiveFlag,
"Can't create __LINKEDIT VM entry at %p, length 0x%llx (error 0x%x).",
seg_data, seg_length, mem_result);
goto finish;
}
/* And copy it back.
*/
memcpy(seg_data, seg_copy, seg_length);
/* Free the copy.
*/
kmem_free(kernel_map, seg_copy_offset, seg_length);
}
#else /* we are not CONFIG_KXLD */
#if !(__arm__ || __arm64__)
#error CONFIG_KXLD is expected for this arch
#endif
/*****
* Dump the LINKEDIT segment, unless keepsyms is set.
*/
if (!sKeepSymbols) {
dt_segment_name = "Kernel-__LINKEDIT";