-
Notifications
You must be signed in to change notification settings - Fork 0
/
kernelcache.c
1100 lines (915 loc) · 33.4 KB
/
kernelcache.c
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
/*
* kernelcache.c
* kext_tools
*
* Created by Nik Gervae on 2010 10 04.
* Copyright 2010, 2012 Apple Computer, Inc. All rights reserved.
*
*/
#include "kernelcache.h"
#include "compression.h"
#if EMBEDDED_HOST
size_t lzvn_encode(void * dst,
size_t dst_size,
const void * src,
size_t src_size,
void * work);
size_t lzvn_decode(void * dst,
size_t dst_size,
const void * src,
size_t src_size);
size_t lzvn_encode_work_size(void);
#else
#include <FastCompression.h>
#endif
#include <mach-o/arch.h>
#include <mach-o/fat.h>
#include <mach-o/swap.h>
#include <sys/mman.h>
#include <IOKit/kext/OSKext.h>
#include <IOKit/kext/OSKextPrivate.h>
/*******************************************************************************
*******************************************************************************/
ExitStatus
writeFatFile(
const char * filePath,
CFArrayRef fileSlices,
CFArrayRef fileArchs,
mode_t fileMode,
const struct timeval fileTimes[2])
{
ExitStatus result = EX_SOFTWARE;
char tmpPath[PATH_MAX];
struct fat_header fatHeader;
struct fat_arch fatArch;
CFDataRef sliceData = NULL; // do not release
const uint8_t * sliceDataPtr = NULL; // do not free
const char * tmpPathPtr = tmpPath; // must unlink
const NXArchInfo * targetArch = NULL; // do not free
mode_t procMode = 0;
uint32_t fatOffset = 0;
uint32_t sliceLength = 0;
int fileDescriptor = -1; // must close
int numArchs = 0;
int i = 0;
/* Make the temporary file */
strlcpy(tmpPath, filePath, sizeof(tmpPath));
if (strlcat(tmpPath, ".XXXX", sizeof(tmpPath)) >= sizeof(tmpPath)) {
OSKextLogStringError(/* kext */ NULL);
goto finish;
}
fileDescriptor = mkstemp(tmpPath);
if (-1 == fileDescriptor) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Can't create %s - %s.",
tmpPath, strerror(errno));
goto finish;
}
/* Set the file's permissions */
/* Set the umask to get it, then set it back to iself. Wish there were a
* better way to query it.
*/
procMode = umask(0);
umask(procMode);
if (-1 == fchmod(fileDescriptor, fileMode & ~procMode)) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Can't set permissions on %s - %s.",
tmpPathPtr, strerror(errno));
}
/* Write out the fat headers even if there's only one arch so we know what
* arch a compressed prelinked kernel belongs to.
*/
numArchs = (int)CFArrayGetCount(fileArchs);
fatHeader.magic = OSSwapHostToBigInt32(FAT_MAGIC);
fatHeader.nfat_arch = OSSwapHostToBigInt32(numArchs);
result = writeToFile(fileDescriptor, (const UInt8 *)&fatHeader,
sizeof(fatHeader));
if (result != EX_OK) {
goto finish;
}
fatOffset = sizeof(struct fat_header) +
(sizeof(struct fat_arch) * numArchs);
for (i = 0; i < numArchs; i++) {
targetArch = CFArrayGetValueAtIndex(fileArchs, i);
sliceData = CFArrayGetValueAtIndex(fileSlices, i);
sliceLength = (uint32_t)CFDataGetLength(sliceData);
fatArch.cputype = OSSwapHostToBigInt32(targetArch->cputype);
fatArch.cpusubtype = OSSwapHostToBigInt32(targetArch->cpusubtype);
fatArch.offset = OSSwapHostToBigInt32(fatOffset);
fatArch.size = OSSwapHostToBigInt32(sliceLength);
fatArch.align = OSSwapHostToBigInt32(0);
result = writeToFile(fileDescriptor,
(UInt8 *)&fatArch, sizeof(fatArch));
if (result != EX_OK) {
goto finish;
}
fatOffset += sliceLength;
}
/* Write out the file slices */
for (i = 0; i < numArchs; i++) {
sliceData = CFArrayGetValueAtIndex(fileSlices, i);
sliceDataPtr = CFDataGetBytePtr(sliceData);
sliceLength = (uint32_t)CFDataGetLength(sliceData);
result = writeToFile(fileDescriptor, sliceDataPtr, sliceLength);
if (result != EX_OK) {
goto finish;
}
}
OSKextLog(/* kext */ NULL,
kOSKextLogDebugLevel | kOSKextLogFileAccessFlag,
"Renaming temp file to %s.",
filePath);
/* Move the file to its final path */
if (rename(tmpPathPtr, filePath) != 0) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Can't rename temporary file %s to %s - %s.",
tmpPathPtr, filePath, strerror(errno));
result = EX_OSERR;
goto finish;
}
tmpPathPtr = NULL;
/* Update the file's mod time if necessary */
if (utimes(filePath, fileTimes)) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Can't update mod time of %s - %s.", filePath, strerror(errno));
}
finish:
if (fileDescriptor >= 0) (void)close(fileDescriptor);
if (tmpPathPtr) unlink(tmpPathPtr);
return result;
}
/*******************************************************************************
*******************************************************************************/
void *
mapAndSwapFatHeaderPage(
int fileDescriptor)
{
void * result = NULL;
void * headerPage = NULL; // must unmapFatHeaderPage()
struct fat_header * fatHeader = NULL; // do not free
struct fat_arch * fatArch = NULL; // do not free
/* Map the first page to read the fat headers. */
headerPage = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
if (MAP_FAILED == headerPage) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Failed to map file header page.");
goto finish;
}
/* Make sure that the fat header, if any, is swapped to the host's byte
* order.
*/
fatHeader = (struct fat_header *) headerPage;
fatArch = (struct fat_arch *) (&fatHeader[1]);
if (fatHeader->magic == FAT_CIGAM) {
swap_fat_header(fatHeader, NXHostByteOrder());
swap_fat_arch(fatArch, fatHeader->nfat_arch, NXHostByteOrder());
}
result = headerPage;
headerPage = NULL;
finish:
if (headerPage) unmapFatHeaderPage(headerPage);
return result;
}
/*******************************************************************************
*******************************************************************************/
void
unmapFatHeaderPage(
void *headerPage)
{
munmap(headerPage, PAGE_SIZE);
}
/*******************************************************************************
*******************************************************************************/
struct fat_arch *
getFirstFatArch(
u_char *headerPage)
{
struct fat_header * fatHeader = NULL;
struct fat_arch * fatArch = NULL;
fatHeader = (struct fat_header *) headerPage;
if (fatHeader->magic != FAT_MAGIC || !fatHeader->nfat_arch) {
goto finish;
}
fatArch = (struct fat_arch *) (&fatHeader[1]);
finish:
return fatArch;
}
/*******************************************************************************
*******************************************************************************/
struct fat_arch *
getNextFatArch(
u_char *headerPage,
struct fat_arch *prevArch)
{
struct fat_header * fatHeader = NULL;
struct fat_arch * firstArch = NULL;
struct fat_arch * nextArch = NULL;
unsigned int numArchs;
fatHeader = (struct fat_header *) headerPage;
if (fatHeader->magic != FAT_MAGIC) {
goto finish;
}
firstArch = (struct fat_arch *) (&fatHeader[1]);
nextArch = &prevArch[1];
numArchs = (unsigned int)(nextArch - firstArch);
if (numArchs >= fatHeader->nfat_arch) {
nextArch = NULL;
goto finish;
}
finish:
return nextArch;
}
/*******************************************************************************
*******************************************************************************/
struct fat_arch *
getFatArchForArchInfo(
u_char *headerPage,
const NXArchInfo *archInfo)
{
struct fat_header * fatHeader = NULL;
struct fat_arch * fatArch = NULL;
fatHeader = (struct fat_header *)headerPage;
if (fatHeader->magic != FAT_MAGIC) {
goto finish;
}
fatArch = (struct fat_arch *)(&fatHeader[1]);
fatArch = NXFindBestFatArch(archInfo->cputype, archInfo->cpusubtype,
fatArch, fatHeader->nfat_arch);
finish:
return fatArch;
}
/*******************************************************************************
*******************************************************************************/
const NXArchInfo *
getThinHeaderPageArch(
const void *headerPage)
{
const NXArchInfo * result = NULL;
struct mach_header * machHdr = NULL;
struct mach_header_64 * machHdr64 = NULL;
Boolean is32Bit = true;
machHdr = (struct mach_header *) headerPage;
machHdr64 = (struct mach_header_64 *) headerPage;
switch (machHdr->magic) {
case MH_MAGIC:
break;
case MH_MAGIC_64:
is32Bit = false;
break;
case MH_CIGAM:
swap_mach_header(machHdr, NXHostByteOrder());
break;
case MH_CIGAM_64:
swap_mach_header_64(machHdr64, NXHostByteOrder());
is32Bit = false;
break;
default:
goto finish;
}
if (is32Bit) {
machHdr64 = NULL;
result = NXGetArchInfoFromCpuType(machHdr->cputype,
machHdr->cpusubtype);
} else {
machHdr = NULL;
result = NXGetArchInfoFromCpuType(machHdr64->cputype,
machHdr64->cpusubtype);
}
finish:
return result;
}
/*******************************************************************************
*******************************************************************************/
ExitStatus
readFatFileArchsWithPath(
const char * filePath,
CFMutableArrayRef * archsOut)
{
ExitStatus result = EX_SOFTWARE;
void * headerPage = NULL; // must unmapFatHeaderPage()
int fileDescriptor = 0; // must close()
/* Open the file. */
fileDescriptor = open(filePath, O_RDONLY);
if (fileDescriptor < 0) {
goto finish;
}
/* Map the fat headers in */
headerPage = mapAndSwapFatHeaderPage(fileDescriptor);
if (!headerPage) {
goto finish;
}
result = readFatFileArchsWithHeader(headerPage, archsOut);
finish:
if (fileDescriptor >= 0) close(fileDescriptor);
if (headerPage) unmapFatHeaderPage(headerPage);
return result;
}
/*******************************************************************************
*******************************************************************************/
Boolean archInfoEqualityCallback(const void *v1, const void *v2)
{
const NXArchInfo *a1 = (const NXArchInfo *)v1;
const NXArchInfo *a2 = (const NXArchInfo *)v2;
return ((a1->cputype == a2->cputype) && (a1->cpusubtype == a2->cpusubtype));
}
/*******************************************************************************
*******************************************************************************/
ExitStatus
readFatFileArchsWithHeader(
u_char * headerPage,
CFMutableArrayRef * archsOut)
{
ExitStatus result = EX_SOFTWARE;
CFMutableArrayRef fileArchs = NULL; // must release
struct fat_arch * fatArch = NULL; // do not free
const NXArchInfo * archInfo = NULL; // do not free
CFArrayCallBacks callbacks = { 0, NULL, NULL, NULL, archInfoEqualityCallback };
/* Create an array to hold the fat archs */
if (!createCFMutableArray(&fileArchs, &callbacks))
{
OSKextLogMemError();
result = EX_OSERR;
goto finish;
}
/* Read the archs */
fatArch = getFirstFatArch(headerPage);
if (fatArch) {
while (fatArch) {
archInfo = NXGetArchInfoFromCpuType(fatArch->cputype,
fatArch->cpusubtype);
CFArrayAppendValue(fileArchs, archInfo);
fatArch = getNextFatArch(headerPage, fatArch);
}
} else {
archInfo = getThinHeaderPageArch(headerPage);
if (archInfo) {
CFArrayAppendValue(fileArchs, archInfo);
} else {
// We can't determine the arch information, so don't return any
archsOut = NULL;
}
}
if (archsOut) *archsOut = (CFMutableArrayRef) CFRetain(fileArchs);
result = EX_OK;
finish:
SAFE_RELEASE(fileArchs);
return result;
}
/*******************************************************************************
*******************************************************************************/
ExitStatus
readMachOSlices(
const char * filePath,
CFMutableArrayRef * slicesOut,
CFMutableArrayRef * archsOut,
mode_t * modeOut,
struct timeval machOTimesOut[2])
{
struct stat statBuf;
ExitStatus result = EX_SOFTWARE;
CFMutableArrayRef fileSlices = NULL; // release
CFMutableArrayRef fileArchs = NULL; // release
CFDataRef sliceData = NULL; // release
u_char * fileBuf = NULL; // must free
void * headerPage = NULL; // must unmapFatHeaderPage()
struct fat_arch * fatArch = NULL; // do not free
int fileDescriptor = 0; // must close()
/* Create an array to hold the fat slices */
if (!createCFMutableArray(&fileSlices, &kCFTypeArrayCallBacks))
{
OSKextLogMemError();
result = EX_OSERR;
goto finish;
}
/* Open the file. */
fileDescriptor = open(filePath, O_RDONLY);
if (fileDescriptor < 0) {
goto finish;
}
if (fstat(fileDescriptor, &statBuf)) {
goto finish;
}
/* Map the fat headers in */
headerPage = mapAndSwapFatHeaderPage(fileDescriptor);
if (!headerPage) {
goto finish;
}
/* If the file is fat, read the slices into separate objects. If not,
* read the whole file into one large slice.
*/
fatArch = getFirstFatArch(headerPage);
if (fatArch) {
while (fatArch) {
sliceData = readMachOSlice(fileDescriptor,
fatArch->offset, fatArch->size);
if (!sliceData) goto finish;
CFArrayAppendValue(fileSlices, sliceData);
fatArch = getNextFatArch(headerPage, fatArch);
CFRelease(sliceData); // drop ref from readMachOSlice()
sliceData = NULL;
}
} else {
sliceData = readMachOSlice(fileDescriptor, 0, (size_t)statBuf.st_size);
if (!sliceData) goto finish;
CFArrayAppendValue(fileSlices, sliceData);
}
if (archsOut) {
result = readFatFileArchsWithHeader(headerPage, &fileArchs);
if (result != EX_OK) {
goto finish;
}
if (!fileArchs) archsOut = NULL;
}
result = EX_OK;
if (slicesOut) *slicesOut = (CFMutableArrayRef) CFRetain(fileSlices);
if (archsOut) *archsOut = (CFMutableArrayRef) CFRetain(fileArchs);
if (modeOut) *modeOut = statBuf.st_mode;
if (machOTimesOut) {
TIMESPEC_TO_TIMEVAL(&machOTimesOut[0], &statBuf.st_atimespec);
TIMESPEC_TO_TIMEVAL(&machOTimesOut[1], &statBuf.st_mtimespec);
}
finish:
SAFE_RELEASE(fileSlices);
SAFE_RELEASE(fileArchs);
SAFE_RELEASE(sliceData);
SAFE_FREE(fileBuf);
if (fileDescriptor >= 0) close(fileDescriptor);
if (headerPage) unmapFatHeaderPage(headerPage);
return result;
}
/*******************************************************************************
*******************************************************************************/
CFDataRef
readMachOSliceForArch(
const char * filePath,
const NXArchInfo * archInfo,
Boolean checkArch)
{
CFDataRef result = NULL; // must release
CFDataRef fileData = NULL; // must release
void * headerPage = NULL; // must unmapFatHeaderPage()
struct fat_header * fatHeader = NULL; // do not free
struct fat_arch * fatArch = NULL; // do not free
int fileDescriptor = 0; // must close()
off_t fileSliceOffset = 0;
size_t fileSliceSize = 0;
struct stat statBuf;
/* Open the file */
fileDescriptor = open(filePath, O_RDONLY);
if (fileDescriptor < 0) {
goto finish;
}
/* Map the fat headers in */
headerPage = mapAndSwapFatHeaderPage(fileDescriptor);
if (!headerPage) {
goto finish;
}
/* Find the slice for the target architecture */
fatHeader = (struct fat_header *)headerPage;
if (archInfo && fatHeader->magic == FAT_MAGIC) {
fatArch = NXFindBestFatArch(archInfo->cputype, archInfo->cpusubtype,
(struct fat_arch *)(&fatHeader[1]), fatHeader->nfat_arch);
if (!fatArch) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"Fat file does not contain requested architecture %s.",
archInfo->name);
goto finish;
}
fileSliceOffset = fatArch->offset;
fileSliceSize = fatArch->size;
} else {
if (fstat(fileDescriptor, &statBuf)) {
goto finish;
}
fileSliceOffset = 0;
fileSliceSize = (size_t)statBuf.st_size;
}
/* Read the file */
fileData = readMachOSlice(fileDescriptor, fileSliceOffset,
fileSliceSize);
if (!fileData) {
goto finish;
}
/* Verify that the file is of the right architecture */
if (checkArch) {
if (verifyMachOIsArch(CFDataGetBytePtr(fileData),
fileSliceSize, archInfo))
{
goto finish;
}
}
result = CFRetain(fileData);
finish:
SAFE_RELEASE(fileData);
if (fileDescriptor >= 0) close(fileDescriptor);
if (headerPage) unmapFatHeaderPage(headerPage);
return result;
}
/*******************************************************************************
*******************************************************************************/
CFDataRef
readMachOSlice(
int fileDescriptor,
off_t fileOffset,
size_t fileSliceSize)
{
CFDataRef fileData = NULL; // do not release
u_char * fileBuf = NULL; // must free
off_t seekedBytes = 0;
ssize_t readBytes = 0;
size_t totalReadBytes = 0;
/* Allocate a buffer for the file */
fileBuf = malloc(fileSliceSize);
if (!fileBuf) {
OSKextLogMemError();
goto finish;
}
/* Seek to the specified file offset */
seekedBytes = lseek(fileDescriptor, fileOffset, SEEK_SET);
if (seekedBytes != fileOffset) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Failed to seek in file."); // xxx - which file is that?
goto finish;
}
/* Read the file's bytes into the buffer */
while (totalReadBytes < fileSliceSize) {
readBytes = read(fileDescriptor, fileBuf + totalReadBytes,
fileSliceSize - totalReadBytes);
if (readBytes < 0) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogFileAccessFlag,
"Failed to read file.");
goto finish;
}
totalReadBytes += (size_t) readBytes;
}
/* Wrap the file slice in a CFData object */
fileData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
(UInt8 *) fileBuf, fileSliceSize, kCFAllocatorMalloc);
if (!fileData) {
goto finish;
}
fileBuf = NULL;
finish:
SAFE_FREE(fileBuf);
return fileData;
}
/*******************************************************************************
*******************************************************************************/
int
verifyMachOIsArch(
const UInt8 * fileBuf,
size_t size,
const NXArchInfo * archInfo)
{
int result = -1;
cpu_type_t cputype = 0;
struct mach_header *checkHeader = (struct mach_header *)fileBuf;
if (!archInfo) {
result = 0;
goto finish;
}
/* Get the cputype from the mach header */
if (size < sizeof(uint32_t)) {
goto finish;
}
if (checkHeader->magic == MH_MAGIC_64 || checkHeader->magic == MH_CIGAM_64) {
struct mach_header_64 *machHeader =
(struct mach_header_64 *) fileBuf;
if (size < sizeof(*machHeader)) {
goto finish;
}
cputype = machHeader->cputype;
if (checkHeader->magic == MH_CIGAM_64) cputype = OSSwapInt32(cputype);
} else if (checkHeader->magic == MH_MAGIC || checkHeader->magic == MH_CIGAM) {
struct mach_header *machHeader =
(struct mach_header *) fileBuf;
if (size < sizeof(*machHeader)) {
goto finish;
}
cputype = machHeader->cputype;
if (checkHeader->magic == MH_CIGAM) cputype = OSSwapInt32(cputype);
}
/* Make sure the file's cputype matches the host's.
*/
if (result == 0 && cputype != archInfo->cputype) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
"File is not of expected architecture %s.", archInfo->name);
goto finish;
}
result = 0;
finish:
return result;
}
/*********************************************************************
*********************************************************************/
CFDataRef
uncompressPrelinkedSlice(
CFDataRef prelinkImage)
{
CFDataRef result = NULL;
CFMutableDataRef uncompressedImage = NULL; // must release
const PrelinkedKernelHeader * prelinkHeader = NULL; // do not free
unsigned char * buf = NULL; // do not free
vm_size_t bufsize = 0;
vm_size_t uncompsize = 0;
uint32_t adler32 = 0;
prelinkHeader = (PrelinkedKernelHeader *) CFDataGetBytePtr(prelinkImage);
/* Verify the header information.
*/
if (prelinkHeader->signature != OSSwapHostToBigInt32('comp')) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Compressed prelinked kernel has invalid signature: 0x%x.",
prelinkHeader->signature);
goto finish;
}
if ( !(prelinkHeader->compressType == OSSwapHostToBigInt32(COMP_TYPE_LZSS) ||
prelinkHeader->compressType == OSSwapHostToBigInt32(COMP_TYPE_FASTLIB)) ) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Compressed prelinked kernel has invalid compressType: 0x%x.",
prelinkHeader->compressType);
goto finish;
}
/* Create a buffer to hold the uncompressed kernel.
*/
bufsize = OSSwapBigToHostInt32(prelinkHeader->uncompressedSize);
uncompressedImage = CFDataCreateMutable(kCFAllocatorDefault, bufsize);
if (!uncompressedImage) {
goto finish;
}
/* We have to call CFDataSetLength explicitly to get CFData to allocate
* its internal buffer.
*/
CFDataSetLength(uncompressedImage, bufsize);
buf = CFDataGetMutableBytePtr(uncompressedImage);
if (!buf) {
OSKextLogMemError();
goto finish;
}
/* Uncompress the kernel.
*/
if (prelinkHeader->compressType == OSSwapHostToBigInt32(COMP_TYPE_LZSS)) {
uncompsize = decompress_lzss(buf, (u_int32_t)bufsize,
((u_int8_t *)(CFDataGetBytePtr(prelinkImage))) + sizeof(*prelinkHeader),
(u_int32_t)(CFDataGetLength(prelinkImage) - sizeof(*prelinkHeader)));
}
else if (prelinkHeader->compressType == OSSwapHostToBigInt32(COMP_TYPE_FASTLIB)) {
uncompsize = lzvn_decode(buf,
bufsize,
((u_int8_t *)(CFDataGetBytePtr(prelinkImage))) + sizeof(*prelinkHeader),
(CFDataGetLength(prelinkImage) - sizeof(*prelinkHeader)));
}
else {
goto finish;
}
if (uncompsize != bufsize) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Compressed prelinked kernel uncompressed to an unexpected size: %u.",
(unsigned)uncompsize);
goto finish;
}
/* Verify the adler32.
*/
adler32 = local_adler32((u_int8_t *) buf, (int)bufsize);
if (prelinkHeader->adler32 != OSSwapHostToBigInt32(adler32)) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Checksum error for compressed prelinked kernel.");
goto finish;
}
result = CFRetain(uncompressedImage);
finish:
SAFE_RELEASE(uncompressedImage);
return result;
}
/*********************************************************************
*********************************************************************/
CFDataRef
compressPrelinkedSlice(
uint32_t compressionType,
CFDataRef prelinkImage,
Boolean hasRelocs)
{
CFDataRef result = NULL;
CFMutableDataRef compressedImage = NULL; // must release
PrelinkedKernelHeader * kernelHeader = NULL; // do not free
const PrelinkedKernelHeader * kernelHeaderIn = NULL; // do not free
unsigned char * buf = NULL; // do not free
unsigned char * bufend = NULL; // do not free
u_long offset = 0;
vm_size_t bufsize = 0;
vm_size_t compsize = 0;
uint32_t adler32 = 0;
/* Check that the kernel is not already compressed */
kernelHeaderIn = (const PrelinkedKernelHeader *)
CFDataGetBytePtr(prelinkImage);
if (kernelHeaderIn->signature == OSSwapHostToBigInt('comp')) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Prelinked kernel is already compressed.");
goto finish;
}
/* Create a buffer to hold the compressed kernel */
offset = sizeof(*kernelHeader);
bufsize = CFDataGetLength(prelinkImage) + offset;
compressedImage = CFDataCreateMutable(kCFAllocatorDefault, bufsize);
if (!compressedImage) {
goto finish;
}
/* We have to call CFDataSetLength explicitly to get CFData to allocate
* its internal buffer.
*/
CFDataSetLength(compressedImage, bufsize);
buf = CFDataGetMutableBytePtr(compressedImage);
if (!buf) {
OSKextLogMemError();
goto finish;
}
kernelHeader = (PrelinkedKernelHeader *) buf;
bzero(kernelHeader, sizeof(*kernelHeader));
kernelHeader->prelinkVersion = OSSwapHostToBigInt32(hasRelocs ? 1 : 0);
/* Fill in the compression information */
kernelHeader->signature = OSSwapHostToBigInt32('comp');
adler32 = local_adler32((u_int8_t *)CFDataGetBytePtr(prelinkImage),
(int)CFDataGetLength(prelinkImage));
kernelHeader->adler32 = OSSwapHostToBigInt32(adler32);
kernelHeader->uncompressedSize =
OSSwapHostToBigInt32(CFDataGetLength(prelinkImage));
/* Compress the kernel */
if (compressionType == COMP_TYPE_FASTLIB) {
size_t outSize = 0;
void * work_space = malloc(lzvn_encode_work_size());
if (work_space != NULL) {
kernelHeader->compressType = OSSwapHostToBigInt32(COMP_TYPE_FASTLIB);
outSize = lzvn_encode(buf + offset,
bufsize,
(u_int8_t *)CFDataGetBytePtr(prelinkImage),
CFDataGetLength(prelinkImage),
work_space);
free(work_space);
if (outSize != 0) {
bufend = buf + offset + outSize;
}
}
}
else if (compressionType == COMP_TYPE_LZSS) {
kernelHeader->compressType = OSSwapHostToBigInt32(COMP_TYPE_LZSS);
bufend = compress_lzss(buf + offset, (u_int32_t)bufsize,
(u_int8_t *)CFDataGetBytePtr(prelinkImage),
(u_int32_t)CFDataGetLength(prelinkImage));
}
else {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Unrecognized compression algorithm.");
goto finish;
}
if (!bufend) {
OSKextLog(/* kext */ NULL,
kOSKextLogErrorLevel | kOSKextLogArchiveFlag,
"Failed to compress prelinked kernel.");
goto finish;
}
compsize = bufend - (buf + offset);
kernelHeader->compressedSize = OSSwapHostToBigInt32(compsize);
CFDataSetLength(compressedImage, bufend - buf);
result = CFRetain(compressedImage);
finish:
SAFE_RELEASE(compressedImage);
return result;
}
/*******************************************************************************
*******************************************************************************/
ExitStatus
writePrelinkedSymbols(
CFURLRef symbolDirURL,
CFArrayRef prelinkSymbols,
CFArrayRef prelinkArchs)
{
SaveFileContext saveFileContext;
ExitStatus result = EX_SOFTWARE;
CFDictionaryRef sliceSymbols = NULL; // do not release
CFURLRef saveDirURL = NULL; // must release
const NXArchInfo * archInfo = NULL; // do not free
CFIndex numArchs = 0;
CFIndex i = 0;
saveFileContext.overwrite = true;
saveFileContext.fatal = false;
numArchs = CFArrayGetCount(prelinkArchs);
for (i = 0; i < numArchs; ++i) {
archInfo = CFArrayGetValueAtIndex(prelinkArchs, i);
sliceSymbols = CFArrayGetValueAtIndex(prelinkSymbols, i);
SAFE_RELEASE_NULL(saveDirURL);
/* We don't need arch-specific directories if there's only one arch */
if (numArchs == 1) {
saveDirURL = CFRetain(symbolDirURL);
} else {
saveDirURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(
kCFAllocatorDefault, (const UInt8 *) archInfo->name,
strlen(archInfo->name), /* isDirectory */ true, symbolDirURL);
if (!saveDirURL) {
goto finish;
}
}
result = makeDirectoryWithURL(saveDirURL);
if (result != EX_OK) {
goto finish;
}
saveFileContext.saveDirURL = saveDirURL;
CFDictionaryApplyFunction(sliceSymbols, &saveFile,
&saveFileContext);
if (saveFileContext.fatal) {
goto finish;