-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexe_macho.c
More file actions
1844 lines (1619 loc) · 72.6 KB
/
Copy pathexe_macho.c
File metadata and controls
1844 lines (1619 loc) · 72.6 KB
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
/* SPDX-License-Identifier: MIT
* Copyright (c) 2021-2026 Chris Dragan
*/
#include "exe_macho.h"
#include "buffer.h"
#include "load_file.h"
#include "lza_compress.h"
#include "lza_decompress.h"
#include "macho_common.h"
#include "macho_sign.h"
#include "map_exe.h"
#include "map_macho.h"
#include "static_assert.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if !defined(_WIN32)
#include <sys/stat.h>
#endif
/*
* Two address spaces matter to this packer and are diagrammed below: the
* output FILE layout (what the kernel maps from disk) and the runtime VM
* layout (where dyld places each segment, sorted by vmaddr). The loader
* locates everything at decompression time through MACHO_LIVE_LAYOUT (see
* macho_common.h), whose pointer fields are offsets from the runtime image
* base.
*
* Runtime sequence: dyld maps the file, binds the __DATA_CONST GOT from the
* trimmed chained fixups, and jumps to the loader (LC_MAIN). The loader
* gathers the compressed payload from its scattered file ranges into __SCRATCH,
* decompresses it into __UNPACK (splitting the trailing __DATA bytes back out
* when folded), mprotects __UNPACK to RX, self-rebases a folded __DATA, and
* jumps to the original entry point.
*
* Output FILE layout (ascending file offset). The compressed payload is split
* across three ranges so no file space is wasted. The alignment gap and the
* __DATA_CONST page padding are reused without enlarging the file, so they
* are filled first; only the __TEXT tail can grow the file, so it is grown
* last:
*
* 0 ------------------> +------------------+ <- Mach-O header + load commands, including the two
* | header + cmds | inserted __UNPACK / __SCRATCH segment commands
* cmds_end_offs ------> +------------------+ <- Alignment gap before the loader holds payload
* | payload range 1 | slice 1 (payload_gap); does not grow the file
* loader_offs --------> +------------------+ <- Loader stub, placed so its low 12 file-offset bits
* | loader | match the compile-time __TEXT (PC-relative refs work)
* payload_offs -------> +------------------+ <- __TEXT tail holds payload slice 2 (payload_tail);
* | payload range 2 | this is the only slice that extends __TEXT
* out_text_filesize --> +------------------+ <- __TEXT.filesize, page aligned (rest is zero-fill)
* data_const_fileoff -> +------------------+ <- __DATA_CONST copied verbatim (dyld binds its GOT)
* | __DATA_CONST |
* | . . . . . . . . .| <- __DATA_CONST page padding holds payload slice 3
* | payload range 3 | (payload_data_const); that page is mandatory anyway
* data_fileoff -------> +------------------+ <- __DATA verbatim, ONLY when not folded; a folded
* | __DATA verbatim | __DATA has no file bytes (loader rebuilds it)
* linkedit_fileoff ---> +------------------+ <- Trimmed __LINKEDIT: just the chained fixups dyld
* | chained fixups | needs for the GOT (symtab/exports/etc. dropped)
* code_limit ---------> +------------------+ <- Ad-hoc code signature; CodeDirectory hashes
* | signature | [0, code_limit)
* +------------------+
*
* Runtime VM layout (ascending vmaddr; dyld requires segments sorted this
* way). __DATA_CONST, __DATA and __LINKEDIT are each shifted up by vm_shift
* (== the original __TEXT.vmsize) to make room for __UNPACK right after
* __TEXT:
*
* 0 ------------------> +------------------+ <- __PAGEZERO (unmapped)
* image_base ---------> +------------------+ <- __TEXT maps here from file offset 0. vmsize is kept
* | __TEXT | at the ORIGINAL value (codesign requires the section
* | header, cmds, | table to stay within segment bounds). Holds the
* | loader, payload | header+cmds, the loader and payload slice 2
* +vm_shift ----------> +------------------+ <- __UNPACK: zero-fill RW the size of the original
* | __UNPACK | __TEXT. Loader decompresses __TEXT here, then
* | (decomp __TEXT) | mprotects it RX before jumping to the entry point
* data_const_vmaddr --> +------------------+ <- __DATA_CONST verbatim (GOT page)
* | __DATA_CONST |
* data_vmaddr --------> +------------------+ <- __DATA: verbatim, or (folded) anonymous zero-fill RW
* | __DATA | that the loader reconstructs and self-rebases
* linkedit_vmaddr ----> +------------------+ <- __LINKEDIT (chained fixups + signature)
* | __LINKEDIT |
* scratch_vmaddr -----> +------------------+ <- __SCRATCH: zero-fill RW work area, placed past
* | __SCRATCH | __LINKEDIT (+1 MB) so it does not perturb vm_shift.
* | gather buffer, | Holds the gathered compressed payload and the
* | raw output | decompressed raw [__TEXT][rebases][__data]
* +------------------+
*/
/* Mach-O on-disk structures. Only what we touch is declared here. */
#define MH_MAGIC_64 0xFEEDFACFU
#define MH_CIGAM_64 0xCFFAEDFEU
#define CPU_TYPE_ARM64 0x0100000CU
#define MH_EXECUTE 0x2U
#define MH_PIE 0x00200000U
#define LC_REQ_DYLD 0x80000000U
#define LC_SEGMENT_64 0x19U
#define LC_SYMTAB 0x02U
#define LC_DYSYMTAB 0x0BU
#define LC_FUNCTION_STARTS 0x26U
#define LC_DATA_IN_CODE 0x29U
#define LC_DYLD_EXPORTS_TRIE (0x33U | LC_REQ_DYLD)
#define LC_DYLD_CHAINED_FIXUPS (0x34U | LC_REQ_DYLD)
#define LC_MAIN (0x28U | LC_REQ_DYLD)
#define LC_CODE_SIGNATURE 0x1DU
#define VM_PROT_READ 0x1U
#define VM_PROT_WRITE 0x2U
#define VM_PROT_EXECUTE 0x4U
#define VM_PROT_RX (VM_PROT_READ | VM_PROT_EXECUTE)
#define VM_PROT_RW (VM_PROT_READ | VM_PROT_WRITE)
#define MACOS_ARM64_PAGE 0x4000U
#define ARM64_ADRP_PAGE 0x1000U
/* Section type byte (low 8 bits of SECTION_64.flags) values that make dyld
* call into the section at load time. Neutralized to S_REGULAR (0) in the
* packed output, since dyld would otherwise invoke shifted/compressed code.
*/
#define SECTION_TYPE_MASK 0xFFU
#define S_MOD_INIT_FUNC_POINTERS 0x09U
#define S_MOD_TERM_FUNC_POINTERS 0x0AU
#define S_INIT_FUNC_OFFSETS 0x16U
/* Chained-fixups format identifiers we need to handle on arm64. Other
* formats exist (arm64e, 32-bit) but are not part of our target set.
*/
#define DYLD_CHAINED_PTR_64 2U
#define DYLD_CHAINED_PTR_64_OFFSET 6U
typedef struct {
uint32_t magic;
uint32_t cputype;
uint32_t cpusubtype;
uint32_t filetype;
uint32_t ncmds;
uint32_t sizeofcmds;
uint32_t flags;
uint32_t reserved;
} MACHO_HEADER_64;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
} LOAD_COMMAND;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
char segname[16];
uint64_t vmaddr;
uint64_t vmsize;
uint64_t fileoff;
uint64_t filesize;
uint32_t maxprot;
uint32_t initprot;
uint32_t nsects;
uint32_t flags;
} SEGMENT_COMMAND_64;
typedef struct {
char sectname[16];
char segname[16];
uint64_t addr;
uint64_t size;
uint32_t offset;
uint32_t align;
uint32_t reloff;
uint32_t nreloc;
uint32_t flags;
uint32_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
} SECTION_64;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
uint64_t entryoff;
uint64_t stacksize;
} ENTRY_POINT_COMMAND;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
uint32_t dataoff;
uint32_t datasize;
} LINKEDIT_DATA_COMMAND;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
uint32_t symoff;
uint32_t nsyms;
uint32_t stroff;
uint32_t strsize;
} SYMTAB_COMMAND;
typedef struct {
uint32_t cmd;
uint32_t cmdsize;
uint32_t ilocalsym;
uint32_t nlocalsym;
uint32_t iextdefsym;
uint32_t nextdefsym;
uint32_t iundefsym;
uint32_t nundefsym;
uint32_t tocoff;
uint32_t ntoc;
uint32_t modtaboff;
uint32_t nmodtab;
uint32_t extrefsymoff;
uint32_t nextrefsyms;
uint32_t indirectsymoff;
uint32_t nindirectsyms;
uint32_t extreloff;
uint32_t nextrel;
uint32_t locreloff;
uint32_t nlocrel;
} DYSYMTAB_COMMAND;
/* dyld chained-fixups header (LC_DYLD_CHAINED_FIXUPS dataoff -> this). */
typedef struct {
uint32_t fixups_version;
uint32_t starts_offset;
uint32_t imports_offset;
uint32_t symbols_offset;
uint32_t imports_count;
uint32_t imports_format;
uint32_t symbols_format;
} DYLD_CHAINED_FIXUPS_HEADER;
typedef struct {
uint32_t seg_count;
uint32_t seg_info_offset[1];
} DYLD_CHAINED_STARTS_IN_IMAGE;
typedef struct {
uint32_t size;
uint16_t page_size;
uint16_t pointer_format;
uint64_t segment_offset;
uint32_t max_valid_pointer;
uint16_t page_count;
uint16_t page_start[1];
} DYLD_CHAINED_STARTS_IN_SEGMENT;
#define DYLD_CHAINED_PTR_START_NONE 0xFFFFU
#define DYLD_CHAINED_PTR_START_MULTI 0x8000U
STATIC_ASSERT(sizeof(MACHO_HEADER_64) == 32, "MACHO_HEADER_64 layout changed");
STATIC_ASSERT(sizeof(LOAD_COMMAND) == 8, "LOAD_COMMAND layout changed");
STATIC_ASSERT(sizeof(SEGMENT_COMMAND_64) == 72, "SEGMENT_COMMAND_64 layout changed");
STATIC_ASSERT(sizeof(SECTION_64) == 80, "SECTION_64 layout changed");
STATIC_ASSERT(sizeof(ENTRY_POINT_COMMAND) == 24, "ENTRY_POINT_COMMAND layout changed");
STATIC_ASSERT(sizeof(LINKEDIT_DATA_COMMAND) == 16, "LINKEDIT_DATA_COMMAND layout changed");
STATIC_ASSERT(sizeof(SYMTAB_COMMAND) == 24, "SYMTAB_COMMAND layout changed");
STATIC_ASSERT(sizeof(DYSYMTAB_COMMAND) == 80, "DYSYMTAB_COMMAND layout changed");
typedef struct {
const MACHO_HEADER_64 *header;
const SEGMENT_COMMAND_64 *text_seg;
const SEGMENT_COMMAND_64 *data_const_seg;
const SEGMENT_COMMAND_64 *data_seg;
const SEGMENT_COMMAND_64 *linkedit_seg;
const SEGMENT_COMMAND_64 *page_zero_seg;
const ENTRY_POINT_COMMAND *entry_point;
const LINKEDIT_DATA_COMMAND *chained_fixups_cmd;
const LINKEDIT_DATA_COMMAND *code_sig_cmd;
uint64_t image_base;
} MACHO_INPUT;
typedef struct {
BUFFER bytes;
uint64_t text_vmaddr;
uint32_t layout_offs;
uint32_t entry_offs;
} LOADER_BLOB;
int is_macho_file(const void *buf, size_t size)
{
uint32_t magic;
if (size < sizeof(uint32_t)) {
return 0;
}
memcpy(&magic, buf, sizeof(magic));
return magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
}
static uint64_t align_up_u64(uint64_t value, uint64_t align)
{
assert(align > 0U && (align & (align - 1U)) == 0U);
return (value + align - 1U) & ~(align - 1U);
}
static int seg_name_equals(const SEGMENT_COMMAND_64 *seg, const char *name)
{
const size_t name_len = strlen(name);
return name_len < sizeof(seg->segname) &&
memcmp(seg->segname, name, name_len) == 0 &&
seg->segname[name_len] == 0;
}
/* Unlike segment names, a section name may fill all 16 bytes with no NUL
* terminator, so a name whose length equals sizeof(sectname) is accepted as an
* exact match (seg_name_equals requires the name to be strictly shorter).
*/
static int sect_name_equals(const SECTION_64 *sect, const char *name)
{
const size_t name_len = strlen(name);
return name_len <= sizeof(sect->sectname) &&
memcmp(sect->sectname, name, name_len) == 0 &&
(name_len == sizeof(sect->sectname) || sect->sectname[name_len] == 0);
}
static const SECTION_64 *find_section(const SEGMENT_COMMAND_64 *seg, const char *sectname)
{
const SECTION_64 *sect = (const SECTION_64 *)(seg + 1);
uint32_t i;
for (i = 0; i < seg->nsects; i++) {
if (sect_name_equals(§[i], sectname)) {
return §[i];
}
}
return NULL;
}
/* Extent of a segment's real (section-described) content, in bytes from the
* segment start. The trailing space up to filesize is padding we can reuse.
*/
static uint64_t segment_content_size(const SEGMENT_COMMAND_64 *seg)
{
const SECTION_64 *sect = (const SECTION_64 *)(seg + 1);
uint64_t max_end = 0;
uint32_t i;
for (i = 0; i < seg->nsects; i++) {
const uint64_t end = (sect[i].addr - seg->vmaddr) + sect[i].size;
if (end > max_end) {
max_end = end;
}
}
return max_end;
}
/* True if any section in `seg` has a name starting with `prefix`. */
static int segment_has_section_prefix(const SEGMENT_COMMAND_64 *seg, const char *prefix)
{
const SECTION_64 *sect;
const size_t prefix_len = strlen(prefix);
uint32_t i;
if ( ! seg) {
return 0;
}
sect = (const SECTION_64 *)(seg + 1);
for (i = 0; i < seg->nsects; i++) {
if (memcmp(sect[i].sectname, prefix, prefix_len) == 0) {
return 1;
}
}
return 0;
}
/* Objective-C / Swift metadata sections require load-time runtime
* registration (class realization, selector/category registration) that we
* do not replay, so a binary carrying them is not eligible for __DATA
* compression -- the caller falls back to copying __DATA verbatim.
*/
static int macho_has_objc_or_swift(const MACHO_INPUT *input)
{
const SEGMENT_COMMAND_64 *segs[3];
size_t i;
segs[0] = input->text_seg;
segs[1] = input->data_const_seg;
segs[2] = input->data_seg;
for (i = 0; i < 3; i++) {
if (segment_has_section_prefix(segs[i], "__objc") ||
segment_has_section_prefix(segs[i], "__swift")) {
return 1;
}
}
return 0;
}
/* Walk __DATA's chained-fixup chain in the input image and collect its rebase
* targets. When `out` is NULL only *count is produced (counting pass).
*
* Sets *eligible to 0 (and returns 0) if __DATA cannot be self-rebased -- a
* bind link, an unsupported pointer format, a multi-start page, or no __DATA
* chain at all -- so the caller copies __DATA verbatim instead. Returns
* non-zero only on a malformed chain (hard error).
*/
static int walk_data_chain(const uint8_t *input_bytes,
const MACHO_INPUT *input,
uint64_t vm_shift,
MACHO_DATA_REBASE *out,
uint32_t *count,
int *eligible)
{
const DYLD_CHAINED_FIXUPS_HEADER *hdr;
const DYLD_CHAINED_STARTS_IN_IMAGE *image_starts;
const uint8_t *fixups_data;
const uint8_t *data_bytes;
uint64_t data_voff;
uint32_t seg_idx;
*count = 0;
*eligible = 1;
if ( ! input->chained_fixups_cmd || ! input->data_seg ||
input->data_seg->filesize == 0U) {
*eligible = 0;
return 0;
}
fixups_data = input_bytes + input->chained_fixups_cmd->dataoff;
hdr = (const DYLD_CHAINED_FIXUPS_HEADER *)fixups_data;
if (hdr->fixups_version != 0U) {
*eligible = 0;
return 0;
}
image_starts = (const DYLD_CHAINED_STARTS_IN_IMAGE *)(fixups_data + hdr->starts_offset);
data_bytes = input_bytes + input->data_seg->fileoff;
data_voff = input->data_seg->vmaddr - input->image_base;
for (seg_idx = 0; seg_idx < image_starts->seg_count; seg_idx++) {
const uint32_t seg_info_offs = image_starts->seg_info_offset[seg_idx];
const DYLD_CHAINED_STARTS_IN_SEGMENT *seg_starts;
uint32_t page_idx;
if (seg_info_offs == 0U) {
continue;
}
seg_starts = (const DYLD_CHAINED_STARTS_IN_SEGMENT *)((const uint8_t *)image_starts + seg_info_offs);
if (seg_starts->segment_offset != data_voff) {
continue;
}
if (seg_starts->pointer_format != DYLD_CHAINED_PTR_64_OFFSET) {
*eligible = 0;
return 0;
}
for (page_idx = 0; page_idx < seg_starts->page_count; page_idx++) {
const uint16_t page_start = seg_starts->page_start[page_idx];
uint64_t chain_offs;
if (page_start == DYLD_CHAINED_PTR_START_NONE) {
continue;
}
if (page_start & DYLD_CHAINED_PTR_START_MULTI) {
*eligible = 0;
return 0;
}
chain_offs = (uint64_t)page_idx * seg_starts->page_size + page_start;
for (;;) {
uint64_t raw;
uint64_t next;
if (chain_offs + sizeof(uint64_t) > input->data_seg->filesize) {
fprintf(stderr, "Error: __DATA chain link out of bounds\n");
return 1;
}
memcpy(&raw, data_bytes + chain_offs, sizeof(raw));
next = (raw >> 51) & 0xFFFU;
if ((raw >> 63) & 1U) {
/* Bind: we have no symbol resolver in the loader. */
*eligible = 0;
return 0;
}
if (out) {
out[*count].slot_offs = data_voff + chain_offs + vm_shift;
out[*count].target_offs = (raw & 0xFFFFFFFFFULL) + vm_shift;
}
(*count)++;
if (next == 0U) {
break;
}
chain_offs += next * 4U;
}
}
break;
}
return 0;
}
static int parse_macho_input(const void *buf, size_t size, MACHO_INPUT *out)
{
const uint8_t *cursor;
const uint8_t *cmds_end;
const LOAD_COMMAND *load_cmd;
uint32_t ncmds;
uint32_t i;
memset(out, 0, sizeof(*out));
if (size < sizeof(MACHO_HEADER_64)) {
fprintf(stderr, "Error: file is too small to contain a Mach-O header\n");
return 1;
}
out->header = (const MACHO_HEADER_64 *)buf;
if (out->header->magic != MH_MAGIC_64) {
fprintf(stderr, "Error: unsupported Mach-O magic 0x%08x\n", out->header->magic);
return 1;
}
if (out->header->cputype != CPU_TYPE_ARM64) {
fprintf(stderr, "Error: only arm64 supported (cputype=0x%08x)\n", out->header->cputype);
return 1;
}
if (out->header->filetype != MH_EXECUTE) {
fprintf(stderr, "Error: only EXECUTE filetype supported (filetype=0x%x)\n",
out->header->filetype);
return 1;
}
if ((out->header->flags & MH_PIE) == 0) {
fprintf(stderr, "Error: input must be PIE\n");
return 1;
}
if (size < sizeof(MACHO_HEADER_64) + out->header->sizeofcmds) {
fprintf(stderr, "Error: file too small for declared load commands\n");
return 1;
}
cursor = (const uint8_t *)buf + sizeof(MACHO_HEADER_64);
cmds_end = cursor + out->header->sizeofcmds;
ncmds = out->header->ncmds;
for (i = 0; i < ncmds; i++) {
if ((size_t)(cmds_end - cursor) < sizeof(LOAD_COMMAND)) {
fprintf(stderr, "Error: load command %u truncated\n", i);
return 1;
}
load_cmd = (const LOAD_COMMAND *)cursor;
if (load_cmd->cmdsize < sizeof(LOAD_COMMAND) ||
(size_t)(cmds_end - cursor) < load_cmd->cmdsize) {
fprintf(stderr, "Error: load command %u invalid cmdsize %u\n", i, load_cmd->cmdsize);
return 1;
}
switch (load_cmd->cmd) {
case LC_SEGMENT_64: {
const SEGMENT_COMMAND_64 *seg = (const SEGMENT_COMMAND_64 *)cursor;
if (load_cmd->cmdsize < sizeof(SEGMENT_COMMAND_64)) {
fprintf(stderr, "Error: LC_SEGMENT_64 invalid cmdsize\n");
return 1;
}
if (seg_name_equals(seg, "__PAGEZERO")) {
out->page_zero_seg = seg;
}
else if (seg_name_equals(seg, "__TEXT")) {
out->text_seg = seg;
out->image_base = seg->vmaddr;
}
else if (seg_name_equals(seg, "__DATA_CONST")) {
out->data_const_seg = seg;
}
else if (seg_name_equals(seg, "__DATA")) {
out->data_seg = seg;
}
else if (seg_name_equals(seg, "__LINKEDIT")) {
out->linkedit_seg = seg;
}
else {
fprintf(stderr, "Error: unsupported segment '%.16s'\n", seg->segname);
return 1;
}
break;
}
case LC_MAIN:
if (load_cmd->cmdsize < sizeof(ENTRY_POINT_COMMAND)) {
fprintf(stderr, "Error: LC_MAIN invalid cmdsize\n");
return 1;
}
out->entry_point = (const ENTRY_POINT_COMMAND *)cursor;
break;
case LC_DYLD_CHAINED_FIXUPS:
out->chained_fixups_cmd = (const LINKEDIT_DATA_COMMAND *)cursor;
break;
case LC_CODE_SIGNATURE:
out->code_sig_cmd = (const LINKEDIT_DATA_COMMAND *)cursor;
break;
default:
break;
}
cursor += load_cmd->cmdsize;
}
if ( ! out->text_seg) {
fprintf(stderr, "Error: no __TEXT segment\n");
return 1;
}
if ( ! out->linkedit_seg) {
fprintf(stderr, "Error: no __LINKEDIT segment\n");
return 1;
}
if ( ! out->entry_point) {
fprintf(stderr, "Error: no LC_MAIN\n");
return 1;
}
if ( ! out->code_sig_cmd) {
fprintf(stderr, "Error: no LC_CODE_SIGNATURE (input must be signed)\n");
return 1;
}
return 0;
}
static int load_loader(LOADER_BLOB *out, const char *loader_name)
{
char filename[1088];
BUFFER file_buf;
const MACHO_HEADER_64 *header;
const uint8_t *cursor;
const LOAD_COMMAND *load_cmd;
const SEGMENT_COMMAND_64 *text_seg = NULL;
const SECTION_64 *text_section = NULL;
const SECTION_64 *layout_section = NULL;
const ENTRY_POINT_COMMAND *loader_entry = NULL;
uint32_t i;
uint64_t blob_start;
uint64_t blob_end;
BUFFER blob;
int error = 1;
out->bytes.buf = NULL;
out->bytes.size = 0;
file_buf.buf = NULL;
file_buf.size = 0;
snprintf(filename, sizeof(filename), "%s/%s", get_exe_dir(), loader_name);
file_buf = load_file(filename, file_mandatory);
if ( ! file_buf.buf) {
fprintf(stderr, "Error: failed to load loader '%s'\n", loader_name);
return 1;
}
if (file_buf.size < sizeof(MACHO_HEADER_64)) {
fprintf(stderr, "Error: loader '%s' too small\n", loader_name);
goto cleanup;
}
header = (const MACHO_HEADER_64 *)file_buf.buf;
if (header->magic != MH_MAGIC_64 || header->cputype != CPU_TYPE_ARM64) {
fprintf(stderr, "Error: loader '%s' not arm64 Mach-O\n", loader_name);
goto cleanup;
}
cursor = (const uint8_t *)file_buf.buf + sizeof(MACHO_HEADER_64);
for (i = 0; i < header->ncmds; i++) {
load_cmd = (const LOAD_COMMAND *)cursor;
if (load_cmd->cmd == LC_SEGMENT_64) {
const SEGMENT_COMMAND_64 *seg = (const SEGMENT_COMMAND_64 *)cursor;
if (seg_name_equals(seg, "__TEXT")) {
text_seg = seg;
text_section = find_section(seg, "__text");
layout_section = find_section(seg, "__layout");
}
}
else if (load_cmd->cmd == LC_MAIN) {
loader_entry = (const ENTRY_POINT_COMMAND *)cursor;
}
cursor += load_cmd->cmdsize;
}
if ( ! text_section || ! layout_section || ! loader_entry) {
fprintf(stderr, "Error: loader '%s' missing __text/__layout/LC_MAIN\n", loader_name);
goto cleanup;
}
/* LC_MAIN.entryoff is a file offset (segment-relative for __TEXT
* starting at fileoff 0). Convert to an offset within our extracted
* blob (which starts at __text.offset).
*/
if (loader_entry->entryoff < text_section->offset) {
fprintf(stderr, "Error: loader '%s' entry %llu before __text offset %u\n",
loader_name, (unsigned long long)loader_entry->entryoff, text_section->offset);
goto cleanup;
}
if (layout_section->size != sizeof(MACHO_LIVE_LAYOUT)) {
fprintf(stderr, "Error: loader '%s' __layout size mismatch\n", loader_name);
goto cleanup;
}
/* The blob is anchored at __text and copied verbatim, so PC-relative
* references inside it stay valid once relocated. The loader's code may
* reach beyond __text and __layout: -Oz pools constants (e.g. a 16-byte
* vector literal) into __TEXT,__const, loaded with a PC-relative LDR.
* Such sections must travel with the blob at their original offsets.
* Cover every __TEXT section except the unwind metadata, which the
* running loader never reads and which ld64 places after the code/const
* sections; including it would just bloat the embedded blob.
*/
blob_start = text_section->offset;
blob_end = (uint64_t)layout_section->offset + layout_section->size;
{
const SECTION_64 *sect = (const SECTION_64 *)(text_seg + 1);
for (i = 0; i < text_seg->nsects; i++) {
uint64_t sect_end;
if (sect_name_equals(§[i], "__unwind_info") ||
sect_name_equals(§[i], "__eh_frame")) {
continue;
}
if (sect[i].offset < blob_start) {
fprintf(stderr, "Error: loader '%s' __TEXT section '%.16s' before __text\n",
loader_name, sect[i].sectname);
goto cleanup;
}
sect_end = (uint64_t)sect[i].offset + sect[i].size;
if (sect_end > blob_end) {
blob_end = sect_end;
}
}
}
if (blob_start >= blob_end || blob_end > file_buf.size) {
fprintf(stderr, "Error: loader '%s' __text/__layout outside file\n", loader_name);
goto cleanup;
}
blob = buf_alloc((size_t)(blob_end - blob_start));
if ( ! blob.buf) {
fprintf(stderr, "Error: OOM extracting loader '%s'\n", loader_name);
goto cleanup;
}
memcpy(blob.buf, (const uint8_t *)file_buf.buf + blob_start, blob.size);
out->bytes = blob;
out->text_vmaddr = text_section->addr;
out->layout_offs = (uint32_t)(layout_section->addr - text_section->addr);
out->entry_offs = (uint32_t)(loader_entry->entryoff - text_section->offset);
error = 0;
cleanup:
free(file_buf.buf);
return error;
}
/* Align a file/vmaddr offset so that its low 12 bits equal `target_low12`.
* Used to place a loader blob at a position where its compile-time
* PC-relative ADRP+ADD pairs into __layout still resolve correctly.
*/
static uint64_t align_to_low12(uint64_t min_offs, uint64_t target_low12)
{
uint64_t base = (min_offs & ~(uint64_t)(ARM64_ADRP_PAGE - 1U)) + target_low12;
if (base < min_offs) {
base += ARM64_ADRP_PAGE;
}
return base;
}
/* The output is already ad-hoc signed in the buffer (macho_adhoc_sign), which
* is sufficient to run on macOS arm64. All that remains for a runnable file
* is the executable permission bit, which save_file does not set.
*/
int macho_set_executable(const char *path)
{
#if !defined(_WIN32)
if (chmod(path, 0755) != 0) {
perror("chmod");
return 1;
}
#else
(void)path;
#endif
return 0;
}
/* Walk the chained-fixups stream and add `vm_shift` to every rebase
* chain link's target offset. Bind chain links (which reference dylib
* imports by ordinal) are not touched.
*/
static int shift_chained_fixups(uint8_t *linkedit_buf,
uint64_t linkedit_fileoff,
uint32_t fixups_dataoff,
uint32_t fixups_datasize,
uint8_t *data_const_seg_bytes,
uint64_t data_const_seg_vmaddr_offs,
uint64_t data_const_seg_size,
uint8_t *data_seg_bytes,
uint64_t data_seg_vmaddr_offs,
uint64_t data_seg_size,
uint64_t vm_shift,
int data_folded)
{
DYLD_CHAINED_FIXUPS_HEADER *hdr;
DYLD_CHAINED_STARTS_IN_IMAGE *image_starts;
uint8_t *fixups_data;
uint32_t seg_idx;
if (fixups_dataoff < linkedit_fileoff ||
fixups_dataoff - linkedit_fileoff + fixups_datasize < fixups_datasize) {
fprintf(stderr, "Error: chained-fixups dataoff out of __LINKEDIT\n");
return 1;
}
fixups_data = linkedit_buf + (fixups_dataoff - linkedit_fileoff);
hdr = (DYLD_CHAINED_FIXUPS_HEADER *)fixups_data;
if (hdr->fixups_version != 0U) {
fprintf(stderr, "Error: unsupported chained-fixups version %u\n", hdr->fixups_version);
return 1;
}
image_starts = (DYLD_CHAINED_STARTS_IN_IMAGE *)(fixups_data + hdr->starts_offset);
for (seg_idx = 0; seg_idx < image_starts->seg_count; seg_idx++) {
const uint32_t seg_info_offs = image_starts->seg_info_offset[seg_idx];
DYLD_CHAINED_STARTS_IN_SEGMENT *seg_starts;
uint8_t *seg_bytes;
uint64_t seg_size;
uint32_t page_idx;
if (seg_info_offs == 0U) {
continue;
}
seg_starts = (DYLD_CHAINED_STARTS_IN_SEGMENT *)((uint8_t *)image_starts + seg_info_offs);
/* When __DATA was folded into the compressed payload its bytes are
* zero at load time, so dyld must not walk its chain (it would
* dereference zero links). Neutralize the entry; the LZ decompressor
* self-applies these rebases after it reconstructs __DATA.
*/
if (data_folded && seg_starts->segment_offset == data_seg_vmaddr_offs) {
image_starts->seg_info_offset[seg_idx] = 0U;
continue;
}
if (seg_starts->page_count == 0U) {
continue;
}
if (seg_starts->pointer_format != DYLD_CHAINED_PTR_64 &&
seg_starts->pointer_format != DYLD_CHAINED_PTR_64_OFFSET) {
fprintf(stderr, "Error: unsupported chain pointer_format %u in seg %u\n",
seg_starts->pointer_format, seg_idx);
return 1;
}
/* Identify which output segment buffer holds this chain. */
if (seg_starts->segment_offset == data_const_seg_vmaddr_offs) {
seg_bytes = data_const_seg_bytes;
seg_size = data_const_seg_size;
}
else if (seg_starts->segment_offset == data_seg_vmaddr_offs) {
seg_bytes = data_seg_bytes;
seg_size = data_seg_size;
}
else {
/* Segment we do not have buffered and do not shift (e.g. __TEXT).
* Leave its links and segment_offset untouched.
*/
seg_bytes = NULL;
seg_size = 0;
}
/* Walk each page chain and rewrite rebase targets. */
if (seg_bytes) {
for (page_idx = 0; page_idx < seg_starts->page_count; page_idx++) {
const uint16_t page_start = seg_starts->page_start[page_idx];
uint64_t chain_offs;
uint64_t page_offs_in_seg;
if (page_start == DYLD_CHAINED_PTR_START_NONE) {
continue;
}
if (page_start & DYLD_CHAINED_PTR_START_MULTI) {
fprintf(stderr, "Error: multi-start chains not supported\n");
return 1;
}
page_offs_in_seg = (uint64_t)page_idx * seg_starts->page_size;
chain_offs = page_offs_in_seg + page_start;
for (;;) {
uint64_t *slot;
uint64_t raw;
uint64_t next;
int is_bind;
if (chain_offs + sizeof(uint64_t) > seg_size) {
fprintf(stderr, "Error: chain link out of segment bounds\n");
return 1;
}
slot = (uint64_t *)(seg_bytes + chain_offs);
raw = *slot;
is_bind = (int)((raw >> 63) & 1U);
next = (raw >> 51) & 0xFFFU;
if ( ! is_bind) {
/* Rebase: bits 0-35 = target, bits 36-43 = high8.
* Add vm_shift to the target field.
*/
const uint64_t target = raw & 0xFFFFFFFFFULL;
const uint64_t high8 = (raw >> 36) & 0xFFULL;
const uint64_t reserved = (raw >> 44) & 0x7FULL;
const uint64_t new_target = target + vm_shift;
if (new_target >> 36) {
fprintf(stderr, "Error: rebase target overflow after shift\n");
return 1;
}
*slot = (uint64_t)new_target |
(high8 << 36) |
(reserved << 44) |
(next << 51) |
((uint64_t)is_bind << 63);
}
if (next == 0U) {
break;
}
chain_offs += next * 4U;
}
}
}
/* Update segment_offset for shifted segments. */
if (seg_starts->segment_offset == data_const_seg_vmaddr_offs && data_const_seg_bytes) {
seg_starts->segment_offset = data_const_seg_vmaddr_offs + vm_shift;
}
else if (seg_starts->segment_offset == data_seg_vmaddr_offs && data_seg_bytes) {
seg_starts->segment_offset = data_seg_vmaddr_offs + vm_shift;
}
}
/* seg_info_offset[] is indexed by LC segment index. Inserting __UNPACK
* at LC index 2 pushed __DATA_CONST / __DATA down by one slot, so the
* blob's index array needs the same shift. Drop the original final
* entry (which must be 0 -- typically __LINKEDIT with no fixups) and
* insert a 0 at index 2 for __UNPACK. seg_count stays put.
*/
if (image_starts->seg_count >= 3U) {
uint32_t shuffle_idx;
if (image_starts->seg_info_offset[image_starts->seg_count - 1U] != 0U) {
fprintf(stderr, "Error: chained-fixups last entry non-zero - cannot reindex for __UNPACK\n");
return 1;
}
for (shuffle_idx = image_starts->seg_count - 1U; shuffle_idx >= 3U; shuffle_idx--) {
image_starts->seg_info_offset[shuffle_idx] = image_starts->seg_info_offset[shuffle_idx - 1U];
}
image_starts->seg_info_offset[2] = 0U;
}
return 0;
}
/* dyld scans every section's type byte for initializer and terminator hooks
* (__mod_init_func, __mod_term_func, __init_offsets ...) and calls into the
* addresses they encode. Those sections now live inside the zero-fill gap of
* our compressed __TEXT or reference shifted code pages that dyld cannot
* recover until the loader runs, so we neutralize their type byte to S_REGULAR
* to keep dyld from invoking garbage at startup.
*/
static void neutralize_init_term_sections(SEGMENT_COMMAND_64 *seg)
{
SECTION_64 *sect = (SECTION_64 *)(seg + 1);
uint32_t sect_idx;
for (sect_idx = 0; sect_idx < seg->nsects; sect_idx++) {
const uint32_t sect_type = sect[sect_idx].flags & SECTION_TYPE_MASK;