Repository navigation
Expand file tree
/
Copy pathapelink.c
More file actions
2234 lines (2095 loc) · 80.9 KB
/
Copy pathapelink.c
File metadata and controls
2234 lines (2095 loc) · 80.9 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
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2023 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "ape/ape.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/dos.internal.h"
#include "libc/elf/def.h"
#include "libc/elf/elf.h"
#include "libc/elf/scalar.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/elf/struct/phdr.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/limits.h"
#include "libc/macho.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/pedef.internal.h"
#include "libc/nt/struct/imageimportbyname.internal.h"
#include "libc/nt/struct/imageimportdescriptor.internal.h"
#include "libc/nt/struct/imagentheaders.internal.h"
#include "libc/nt/struct/imagesectionheader.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.internal.h"
#include "libc/stdalign.internal.h"
#include "libc/stdckdint.h"
#include "libc/stdio/stdio.h"
#include "libc/str/blake2.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/zip.internal.h"
#include "third_party/getopt/getopt.internal.h"
#include "third_party/zlib/zlib.h"
#include "tool/build/lib/lib.h"
#define VERSION \
"apelink v0.1\n" \
"copyright 2023 justine tunney\n" \
"https://github.com/jart/cosmopolitan\n"
#define MANUAL \
" -o OUTPUT INPUT...\n" \
"\n" \
"DESCRIPTION\n" \
"\n" \
" actually portable executable linker\n" \
"\n" \
" this program may be used to turn elf executables into\n" \
" ape executables. it's useful for creating fat binaries\n" \
" that run on multiple architectures.\n" \
"\n" \
"FLAGS\n" \
"\n" \
" -h show usage\n" \
"\n" \
" -v show version\n" \
"\n" \
" -o OUTPUT set output path\n" \
"\n" \
" -s never embed symbol table\n" \
"\n" \
" -l PATH bundle ape loader executable [repeatable]\n" \
" if no ape loaders are specified then your\n" \
" executable will self-modify its header on\n" \
" the first run, to use the platform format\n" \
"\n" \
" -M PATH bundle ape loader source code file for m1\n" \
" processors running the xnu kernel so that\n" \
" it can be compiled on the fly by xcode\n" \
"\n" \
" -V BITS set OS support vector\n" \
"\n" \
" the default value is -1 which sets the bits\n" \
" for all supported operating systems to true\n" \
" of which the following are defined:\n" \
"\n" \
" - 1: linux\n" \
" - 2: metal\n" \
" - 4: windows\n" \
" - 8: xnu\n" \
" - 16: openbsd\n" \
" - 32: freebsd\n" \
" - 64: netbsd\n" \
"\n" \
" for example, `-s 0b1110001` may be used to\n" \
" produce ELF binaries that only support the\n" \
" truly open unix systems. in this case when\n" \
" a single input executable is supplied, the\n" \
" output file will end up being portable elf\n" \
"\n" \
" when the default of -1 is supplied, certain\n" \
" operating systems can have support detected\n" \
" by examining your symbols and sections. for\n" \
" example, xnu is detected by looking for the\n" \
" _apple() entrypoint which is defined on elf\n" \
" platforms as being e_entry. if only the XNU\n" \
" platform is supported then e_entry is used.\n" \
"\n" \
" in addition to accepting numbers, you could\n" \
" also pass strings in a variety of intuitive\n" \
" supported representations. for example, bsd\n" \
" will enable freebsd+netbsd+openbsd and that\n" \
" string too is a legal input. the -s flag is\n" \
" also repeatable, e.g. `-s nt -s xnu` to use\n" \
" the union of the two.\n" \
"\n" \
" since the support vector controls the file\n" \
" format that's outputted too you can supply\n" \
" the keywords `pe`, `elf`, & 'macho' to use\n" \
" a support vector targetting whichever OSes\n" \
" use it as a native format.\n" \
"\n" \
" -g generate a debugging friendly ape binary\n" \
"\n" \
" -G don't $PATH lookup systemwide ape loader\n" \
"\n" \
" -S CODE add custom code to start of shell script\n" \
" for example you can use `-S 'set -ex' to\n" \
" troubleshoot any issues with your script\n" \
"\n" \
" -B force bypassing of any binfmt_misc loader\n" \
" by using alternative 'APEDBG=' file magic\n" \
"\n" \
"ARGUMENTS\n" \
"\n" \
" OUTPUT is your ape executable\n" \
" INPUT specifies multiple ELF builds of the same\n" \
" program, for different architectures that\n" \
" shall be merged into a single output file\n" \
"\n"
#define ALIGN(p, a) (char *)ROUNDUP((uintptr_t)(p), (a))
enum Strategy {
kElf,
kApe,
kMacho,
kPe,
};
struct MachoLoadThread64 {
struct MachoLoadThreadCommand thread;
uint64_t regs[21];
};
struct OffsetRelocs {
int n;
uint64_t *p[64];
};
struct Input {
union {
char *map;
Elf64_Ehdr *elf;
unsigned char *umap;
};
size_t size;
const char *path;
Elf64_Off machoff;
Elf64_Off minload;
Elf64_Off maxload;
char *printf_phoff;
char *printf_phnum;
char *ddarg_macho_skip;
char *ddarg_macho_count;
int pe_offset;
int pe_e_lfanew;
int pe_SizeOfHeaders;
int size_of_pe_headers;
bool we_are_generating_pe;
bool we_must_skew_pe_vaspace;
struct NtImageNtHeaders *pe;
struct OffsetRelocs offsetrelocs;
struct MachoLoadSegment *first_macho_load;
};
struct Inputs {
int n;
struct Input p[16];
};
struct Loader {
int os;
int machine;
bool used;
void *map;
size_t size;
const char *path;
int macho_offset;
int macho_length;
char *ddarg_skip1;
char *ddarg_size1;
char *ddarg_skip2;
char *ddarg_size2;
};
struct Loaders {
int n;
struct Loader p[16];
};
struct Asset {
unsigned char *cfile;
unsigned char *lfile;
};
struct Assets {
int n;
struct Asset *p;
size_t total_centraldir_bytes;
size_t total_local_file_bytes;
};
static int outfd;
static int hashes;
static const char *prog;
static bool want_stripped;
static int support_vector;
static int macholoadcount;
static const char *outpath;
static struct Assets assets;
static struct Inputs inputs;
static char ape_heredoc[15];
static enum Strategy strategy;
static struct Loaders loaders;
static const char *custom_sh_code;
static bool force_bypass_binfmt_misc;
static bool generate_debuggable_binary;
static bool dont_path_lookup_ape_loader;
_Alignas(4096) static char prologue[1048576];
static uint8_t hashpool[BLAKE2B256_DIGEST_LENGTH];
static const char *macos_silicon_loader_source_path;
static const char *macos_silicon_loader_source_text;
static char *macos_silicon_loader_source_ddarg_skip;
static char *macos_silicon_loader_source_ddarg_size;
static Elf64_Off noteoff;
static Elf64_Xword notesize;
static char *r_off32_e_lfanew;
static wontreturn void Die(const char *thing, const char *reason) {
tinyprint(2, thing, ": ", reason, "\n", NULL);
exit(1);
}
static wontreturn void DieSys(const char *thing) {
perror(thing);
exit(1);
}
static wontreturn void ShowUsage(int rc, int fd) {
tinyprint(fd, "USAGE\n\n ", prog, MANUAL, NULL);
exit(rc);
}
static wontreturn void DieOom(void) {
Die("apelink", "out of memory");
}
static void *Malloc(size_t n) {
void *p;
if (!(p = malloc(n))) DieOom();
return p;
}
static void *Realloc(void *p, size_t n) {
if (!(p = realloc(p, n))) DieOom();
return p;
}
// By convention, Cosmopolitan's GetSymbolTable() function will inspect
// its own executable image to see if it's also a zip archive, in which
// case it tries to load the symbol table from an architecture-specific
// filename below, and falls back to the ".symtab" when it isn't found.
// the file format for these symbol files is unique to cosmopiltan libc
static const char *ConvertElfMachineToSymtabName(Elf64_Ehdr *e) {
switch (e->e_machine) {
case EM_NEXGEN32E:
return ".symtab.amd64";
case EM_AARCH64:
return ".symtab.arm64";
case EM_PPC64:
return ".symtab.ppc64";
case EM_S390:
return ".symtab.s390x";
case EM_RISCV:
return ".symtab.riscv";
default:
Die(prog, "unsupported architecture");
}
}
static const char *DescribePhdrType(Elf64_Word p_type) {
static char buf[12];
switch (p_type) {
case PT_LOAD:
return "LOAD";
case PT_TLS:
return "TLS";
case PT_PHDR:
return "PHDR";
case PT_NOTE:
return "NOTE";
case PT_INTERP:
return "INTERP";
case PT_DYNAMIC:
return "DYNAMIC";
case PT_GNU_STACK:
return "GNU_STACK";
default:
FormatInt32(buf, p_type);
return buf;
}
}
static bool IsBinary(const char *p, size_t n) {
size_t i;
for (i = 0; i < n; ++i) {
if ((p[i] & 255) < '\t') {
return true;
}
}
return false;
}
static void BlendHashes(uint8_t out[static BLAKE2B256_DIGEST_LENGTH],
uint8_t inp[static BLAKE2B256_DIGEST_LENGTH]) {
int i;
for (i = 0; i < BLAKE2B256_DIGEST_LENGTH; ++i) {
out[i] ^= inp[i];
}
}
static void HashInput(const void *data, size_t size) {
uint8_t digest[BLAKE2B256_DIGEST_LENGTH];
uint32_t hash = crc32_z(hashes, data, size); // 30 GB/s
BLAKE2B256(&hash, sizeof(hash), digest); // .6 GB/s
BlendHashes(hashpool, digest);
++hashes;
}
static void HashInputString(const char *str) {
HashInput(str, strlen(str));
}
static char *LoadSourceCode(const char *path) {
int fd;
size_t i;
char *text;
ssize_t rc, size;
if ((fd = open(path, O_RDONLY)) == -1) DieSys(path);
if ((size = lseek(fd, 0, SEEK_END)) == -1) DieSys(path);
text = Malloc(size + 1);
text[size] = 0;
for (i = 0; i < size; i += rc) {
if ((rc = pread(fd, text, size - i, i)) <= 0) {
DieSys(path);
}
if (IsBinary(text, rc)) {
Die(path, "source code contains binary data");
}
}
if (close(fd)) DieSys(path);
HashInput(text, size);
return text;
}
static void Pwrite(const void *data, size_t size, uint64_t offset) {
ssize_t rc;
const char *p, *e;
for (p = data, e = p + size; p < e; p += (size_t)rc, offset += (size_t)rc) {
if ((rc = pwrite(outfd, p, e - p, offset)) == -1) {
DieSys(outpath);
}
}
}
static void LogElfPhdrs(FILE *f, Elf64_Phdr *p, size_t n) {
size_t i;
fprintf(f, "Type "
"Offset "
"VirtAddr "
"PhysAddr "
"FileSiz "
"MemSiz "
"Flg Align\n");
for (i = 0; i < n; ++i) {
fprintf(f,
"%-14s 0x%06lx 0x%016lx 0x%016lx 0x%06lx 0x%06lx %c%c%c 0x%04lx\n",
DescribePhdrType(p[i].p_type), p[i].p_offset, p[i].p_vaddr,
p[i].p_paddr, p[i].p_filesz, p[i].p_memsz,
p[i].p_flags & PF_R ? 'R' : ' ', p[i].p_flags & PF_W ? 'W' : ' ',
p[i].p_flags & PF_X ? 'E' : ' ', p[i].p_align);
}
}
static void LogPeSections(FILE *f, struct NtImageSectionHeader *p, size_t n) {
size_t i;
fprintf(f, "Name "
"Offset "
"RelativeVirtAddr "
"PhysAddr "
"FileSiz "
"MemSiz "
"Flg\n");
for (i = 0; i < n; ++i) {
fprintf(f, "%-14.8s 0x%06lx 0x%016lx 0x%016lx 0x%06lx 0x%06lx %c%c%c\n",
p[i].Name, p[i].PointerToRawData, p[i].VirtualAddress,
p[i].VirtualAddress, p[i].SizeOfRawData, p[i].Misc.VirtualSize,
p[i].Characteristics & kNtPeSectionMemRead ? 'R' : ' ',
p[i].Characteristics & kNtPeSectionMemWrite ? 'W' : ' ',
p[i].Characteristics & kNtPeSectionMemExecute ? 'E' : ' ');
}
}
static void ValidateElfImage(Elf64_Ehdr *e, Elf64_Off esize, //
const char *epath, bool isloader) {
// validate elf header
if (e->e_type != ET_EXEC && e->e_type != ET_DYN)
Die(epath, "elf binary isn't an executable");
if (!e->e_phnum)
Die(epath, "elf executable needs at least one program header");
if (e->e_phnum > 65534)
Die(epath, "elf with more than 65534 phdrs not supported");
if (e->e_phentsize != sizeof(Elf64_Phdr))
Die(epath, "elf e_phentsize isn't sizeof(Elf64_Phdr)");
if (e->e_phoff > esize)
Die(epath, "elf program header offset points past image eof");
if (e->e_phoff & 7)
Die(epath, "elf e_phoff must be aligned on an 8-byte boundary");
if (e->e_phoff + e->e_phoff + e->e_phnum * sizeof(Elf64_Phdr) > esize)
Die(epath, "elf program header array overlaps image eof");
// determine microprocessor page size requirement
//
// even though operating systems (windows) and c libraries (cosmo)
// sometimes impose a larger page size requirement than the actual
// microprocessor itself, the cpu page size is still the only page
// size that actually matters when it comes to executable loading.
unsigned long pagesz;
if (e->e_machine == EM_AARCH64) {
pagesz = 16384; // apple m1 (xnu, linux)
} else { //
pagesz = 4096; // x86-64, raspberry pi
}
// remove empty segment loads
// empty loads should be inconsequential; linux ignores them
// however they tend to trip up many systems such as openbsd
int i, j;
Elf64_Phdr *p = (Elf64_Phdr *)((char *)e + e->e_phoff);
for (i = 0; i < e->e_phnum;) {
if (p[i].p_type == PT_LOAD && !p[i].p_memsz) {
if (i + 1 < e->e_phnum) {
memmove(p + i, p + i + 1, (e->e_phnum - (i + 1)) * sizeof(*p));
}
--e->e_phnum;
} else {
++i;
}
}
// oracle says loadable segment entries in the program header table
// appear in ascending order, sorted on the p_vaddr member.
int found_load = 0;
Elf64_Addr last_vaddr = 0;
for (i = 0; i < e->e_phnum; ++i) {
if (p[i].p_type != PT_LOAD) continue;
if (found_load && p[i].p_vaddr <= last_vaddr) {
Die(epath, "ELF PT_LOAD segments must be ordered by p_vaddr");
}
last_vaddr = p[i].p_vaddr;
found_load = 1;
}
if (!found_load) {
Die(epath, "ELF must have at least one PT_LOAD segment");
}
// merge adjacent loads that are contiguous with equal protection
for (i = 0; i + 1 < e->e_phnum;) {
if (p[i].p_type == PT_LOAD && p[i + 1].p_type == PT_LOAD &&
((p[i].p_flags & (PF_R | PF_W | PF_X)) ==
(p[i + 1].p_flags & (PF_R | PF_W | PF_X))) &&
((p[i].p_offset + p[i].p_filesz + (pagesz - 1)) & -pagesz) -
(p[i + 1].p_offset & -pagesz) <=
pagesz &&
((p[i].p_vaddr + p[i].p_memsz + (pagesz - 1)) & -pagesz) -
(p[i + 1].p_vaddr & -pagesz) <=
pagesz) {
p[i].p_memsz = (p[i + 1].p_vaddr + p[i + 1].p_memsz) - p[i].p_vaddr;
p[i].p_filesz = (p[i + 1].p_offset + p[i + 1].p_filesz) - p[i].p_offset;
if (i + 2 < e->e_phnum) {
memmove(p + i + 1, p + i + 2, (e->e_phnum - (i + 2)) * sizeof(*p));
}
--e->e_phnum;
} else {
++i;
}
}
// validate program headers
bool found_entry = false;
for (i = 0; i < e->e_phnum; ++i) {
if (!isloader && p[i].p_type == PT_INTERP) {
Die(epath, "ELF has PT_INTERP which isn't supported");
}
if (!isloader && p[i].p_type == PT_DYNAMIC) {
Die(epath, "ELF has PT_DYNAMIC which isn't supported");
}
if (p[i].p_type != PT_LOAD) {
continue;
}
if (!p[i].p_memsz) {
Die(epath, "ELF PT_LOAD p_memsz was zero");
}
if (p[i].p_offset > esize) {
Die(epath, "ELF PT_LOAD p_offset points past EOF");
}
if (p[i].p_filesz > p[i].p_memsz) {
Die(epath, "ELF PT_LOAD p_filesz exceeds p_memsz");
}
if (p[i].p_align > 1 && (p[i].p_align & (p[i].p_align - 1))) {
Die(epath, "ELF PT_LOAD p_align must be two power");
}
if (p[i].p_vaddr + p[i].p_memsz < p[i].p_vaddr ||
p[i].p_vaddr + p[i].p_memsz + (pagesz - 1) < p[i].p_vaddr) {
Die(epath, "ELF PT_LOAD p_vaddr + p_memsz overflow");
}
if (p[i].p_offset + p[i].p_filesz < p[i].p_offset ||
p[i].p_offset + p[i].p_filesz + (pagesz - 1) < p[i].p_offset) {
Die(epath, "ELF PT_LOAD p_offset + p_filesz overflow");
}
if (p[i].p_align > 1 && ((p[i].p_vaddr & (p[i].p_align - 1)) !=
(p[i].p_offset & (p[i].p_align - 1)))) {
Die(epath, "ELF p_vaddr incongruent w/ p_offset modulo p_align");
}
if ((p[i].p_vaddr & (pagesz - 1)) != (p[i].p_offset & (pagesz - 1))) {
Die(epath, "ELF p_vaddr incongruent w/ p_offset modulo AT_PAGESZ");
}
if (p[i].p_offset + p[i].p_filesz > esize) {
Die(epath, "ELF PT_LOAD p_offset and p_filesz overlaps image EOF");
}
Elf64_Off a = p[i].p_vaddr & -pagesz;
Elf64_Off b = (p[i].p_vaddr + p[i].p_memsz + (pagesz - 1)) & -pagesz;
for (j = i + 1; j < e->e_phnum; ++j) {
if (p[j].p_type != PT_LOAD) continue;
Elf64_Off c = p[j].p_vaddr & -pagesz;
Elf64_Off d = (p[j].p_vaddr + p[j].p_memsz + (pagesz - 1)) & -pagesz;
if (MAX(a, c) < MIN(b, d)) {
Die(epath,
"ELF PT_LOAD phdrs %d and %d overlap each others virtual memory");
}
}
if (e->e_machine == EM_AARCH64 &&
p[i].p_vaddr + p[i].p_memsz > 0x0001000000000000) {
Die(epath, "this is an ARM ELF program but it loads to virtual"
" memory addresses outside the legal range [0,2^48)");
}
if (e->e_machine == EM_NEXGEN32E &&
!(-140737488355328 <= (Elf64_Sxword)p[i].p_vaddr &&
(Elf64_Sxword)(p[i].p_vaddr + p[i].p_memsz) <= 140737488355328)) {
Die(epath, "this is an x86-64 ELF program, but it loads to virtual"
" memory addresses outside the legal range [-2^47,2^47)");
}
if (e->e_type == ET_EXEC && //
(support_vector & _HOSTMETAL) && //
(Elf64_Sxword)p[i].p_vaddr < 0x200000) {
Die(epath, "ELF program header loads to address less than 2mb even"
" though you have userspace OSes in your support vector");
}
if (!isloader && //
e->e_type == ET_EXEC && //
!(p[i].p_vaddr >> 32) && //
e->e_machine == EM_AARCH64 && //
(support_vector & _HOSTXNU)) {
Die(epath, "ELF program header loads to address less than 4gb even"
" though you have XNU on AARCH64 in your support vector"
" which forbids 32-bit pointers without any compromises");
}
if ((p[i].p_flags & (PF_W | PF_X)) == (PF_W | PF_X)) {
if (support_vector & _HOSTOPENBSD) {
Die(epath, "found RWX ELF program segment, but you have OpenBSD in"
" your support vector, which totally forbids RWX memory");
}
if (e->e_machine == EM_AARCH64 && (support_vector & _HOSTXNU)) {
Die(epath, "found RWX ELF program segment on an AARCH64 executable"
" with XNU support, which completely forbids RWX memory");
}
}
if ((p[i].p_flags & PF_X) && //
p[i].p_vaddr <= e->e_entry &&
e->e_entry < p[i].p_vaddr + p[i].p_memsz) {
found_entry = 1;
}
}
if (!found_entry) {
Die(epath, "ELF entrypoint not found in PT_LOAD with PF_X");
}
}
static bool IsSymbolWorthyOfSymtab(Elf64_Sym *sym) {
return sym->st_size > 0 && (ELF64_ST_TYPE(sym->st_info) == STT_FUNC ||
ELF64_ST_TYPE(sym->st_info) == STT_OBJECT);
}
static void AppendZipAsset(unsigned char *lfile, unsigned char *cfile) {
if (assets.n == 65534) Die(outpath, "fat binary has >65534 zip assets");
assets.p = Realloc(assets.p, (assets.n + 1) * sizeof(*assets.p));
assets.p[assets.n].cfile = cfile;
assets.p[assets.n].lfile = lfile;
assets.total_local_file_bytes += ZIP_LFILE_SIZE(lfile);
assets.total_centraldir_bytes += ZIP_CFILE_HDRSIZE(cfile);
++assets.n;
}
static void *Compress(const void *data, size_t size, size_t *out_size, int wb) {
void *res;
z_stream zs;
zs.zfree = 0;
zs.zalloc = 0;
zs.opaque = 0;
unassert(deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, wb, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY) == Z_OK);
zs.next_in = data;
zs.avail_in = size;
zs.avail_out = compressBound(size);
zs.next_out = res = Malloc(zs.avail_out);
unassert(deflate(&zs, Z_FINISH) == Z_STREAM_END);
unassert(deflateEnd(&zs) == Z_OK);
*out_size = zs.total_out;
return res;
}
static void *Deflate(const void *data, size_t size, size_t *out_size) {
return Compress(data, size, out_size, -MAX_WBITS);
}
static void *Gzip(const void *data, size_t size, size_t *out_size) {
return Compress(data, size, out_size, MAX_WBITS + 16);
}
static void LoadSymbols(Elf64_Ehdr *e, Elf64_Off size, const char *path) {
const char *name = ConvertElfMachineToSymtabName(e);
size_t name_size = strlen(name);
struct SymbolTable *st = OpenSymbolTable(path);
if (!st) Die(path, "could not load elf symbol table");
size_t data_size;
void *data = Deflate(st, st->size, &data_size);
uint32_t crc = crc32_z(0, st, st->size);
size_t cfile_size = kZipCfileHdrMinSize + name_size;
unsigned char *cfile = Malloc(cfile_size);
bzero(cfile, cfile_size);
WRITE32LE(cfile, kZipCfileHdrMagic);
cfile[4] = kZipCosmopolitanVersion;
cfile[5] = kZipOsUnix;
cfile[6] = kZipEra1993;
WRITE16LE(cfile + kZipCfileOffsetCompressionmethod, kZipCompressionDeflate);
WRITE16LE(cfile + kZipCfileOffsetLastmodifieddate, DOS_DATE(2023, 7, 29));
WRITE16LE(cfile + kZipCfileOffsetLastmodifiedtime, DOS_TIME(0, 0, 0));
WRITE32LE(cfile + kZipCfileOffsetCompressedsize, data_size);
WRITE32LE(cfile + kZipCfileOffsetUncompressedsize, st->size);
WRITE32LE(cfile + kZipCfileOffsetCrc32, crc);
WRITE16LE(cfile + kZipCfileOffsetNamesize, name_size);
memcpy(cfile + kZipCfileHdrMinSize, name, name_size);
unassert(ZIP_CFILE_HDRSIZE(cfile) == cfile_size);
size_t lfile_size = kZipLfileHdrMinSize + name_size + data_size;
unsigned char *lfile = Malloc(lfile_size);
bzero(lfile, lfile_size);
WRITE32LE(lfile, kZipLfileHdrMagic);
cfile[4] = kZipEra1993;
cfile[5] = kZipOsDos;
WRITE16LE(lfile + kZipLfileOffsetCompressionmethod, kZipCompressionDeflate);
WRITE16LE(lfile + kZipLfileOffsetLastmodifieddate, DOS_DATE(2023, 7, 29));
WRITE16LE(lfile + kZipLfileOffsetLastmodifiedtime, DOS_TIME(0, 0, 0));
WRITE32LE(lfile + kZipLfileOffsetCompressedsize, data_size);
WRITE32LE(lfile + kZipLfileOffsetUncompressedsize, st->size);
WRITE32LE(lfile + kZipLfileOffsetCrc32, crc);
WRITE16LE(lfile + kZipLfileOffsetNamesize, name_size);
memcpy(lfile + kZipLfileHdrMinSize, name, name_size);
memcpy(lfile + kZipLfileHdrMinSize + name_size, data, data_size);
unassert(ZIP_LFILE_SIZE(lfile) == lfile_size);
free(data);
AppendZipAsset(lfile, cfile);
}
// resolves portable executable relative virtual address
//
// this is a trivial process when an executable has been loaded properly
// i.e. a separate mmap() call was made for each individual section; but
// we've only mapped the executable file itself into memory; thus, we'll
// need to remap a virtual address into a file offset to get the pointer
//
// returns pointer to image data, or null on error
static void *GetPeRva(char *map, struct NtImageNtHeaders *pe, uint32_t rva) {
struct NtImageSectionHeader *sections =
(struct NtImageSectionHeader *)((char *)&pe->OptionalHeader +
pe->FileHeader.SizeOfOptionalHeader);
for (int i = 0; i < pe->FileHeader.NumberOfSections; ++i) {
if (sections[i].VirtualAddress <= rva &&
rva < sections[i].VirtualAddress + sections[i].Misc.VirtualSize) {
return map + sections[i].PointerToRawData +
(rva - sections[i].VirtualAddress);
}
}
return 0;
}
static int ValidatePeImage(char *img, size_t imgsize, //
struct NtImageNtHeaders *pe, //
const char *path) {
int pagesz = 4096;
// sanity check pe header
if (pe->Signature != ('P' | 'E' << 8))
Die(path, "PE Signature must be 0x00004550");
if (!(pe->FileHeader.Characteristics & kNtPeFileExecutableImage))
Die(path, "PE Characteristics must have executable bit set");
if (pe->FileHeader.Characteristics & kNtPeFileDll)
Die(path, "PE Characteristics can't have DLL bit set");
if (pe->FileHeader.NumberOfSections < 1)
Die(path, "PE NumberOfSections >= 1 must be the case");
if (pe->OptionalHeader.Magic != kNtPe64bit)
Die(path, "PE OptionalHeader Magic must be 0x020b");
if (pe->OptionalHeader.FileAlignment < 512)
Die(path, "PE FileAlignment must be at least 512");
if (pe->OptionalHeader.FileAlignment > 65536)
Die(path, "PE FileAlignment can't exceed 65536");
if (pe->OptionalHeader.FileAlignment & (pe->OptionalHeader.FileAlignment - 1))
Die(path, "PE FileAlignment must be a two power");
if (pe->OptionalHeader.SectionAlignment &
(pe->OptionalHeader.SectionAlignment - 1))
Die(path, "PE SectionAlignment must be a two power");
if (pe->OptionalHeader.SectionAlignment < pe->OptionalHeader.FileAlignment)
Die(path, "PE SectionAlignment >= FileAlignment must be the case");
if (pe->OptionalHeader.SectionAlignment < pagesz &&
pe->OptionalHeader.SectionAlignment != pe->OptionalHeader.FileAlignment)
Die(path, "PE SectionAlignment must equal FileAlignment if it's less than "
"the microprocessor architecture's page size");
if (pe->OptionalHeader.ImageBase & 65535)
Die(path, "PE ImageBase must be multiple of 65536");
if (pe->OptionalHeader.ImageBase > INT_MAX &&
!(pe->FileHeader.Characteristics & kNtImageFileLargeAddressAware))
Die(path, "PE FileHeader.Characteristics needs "
"IMAGE_FILE_LARGE_ADDRESS_AWARE if ImageBase > INT_MAX");
if (!(support_vector & _HOSTMETAL) &&
pe->OptionalHeader.Subsystem == kNtImageSubsystemEfiApplication)
Die(path, "PE Subsystem is EFI but Metal wasn't in support_vector");
if (!(support_vector & _HOSTWINDOWS) &&
(pe->OptionalHeader.Subsystem == kNtImageSubsystemWindowsCui ||
pe->OptionalHeader.Subsystem == kNtImageSubsystemWindowsGui))
Die(path, "PE Subsystem is Windows but Windows wasn't in support_vector");
// fixup pe header
int len;
if (ckd_mul(&len, pe->OptionalHeader.NumberOfRvaAndSizes, 8) ||
ckd_add(&len, len, sizeof(struct NtImageOptionalHeader)) ||
pe->FileHeader.SizeOfOptionalHeader < len)
Die(path, "PE SizeOfOptionalHeader too small");
if (len > imgsize || (char *)&pe->OptionalHeader + len > img + imgsize)
Die(path, "PE OptionalHeader overflows image");
// perform even more pe validation
if (pe->OptionalHeader.SizeOfImage &
(pe->OptionalHeader.SectionAlignment - 1))
Die(path, "PE SizeOfImage must be multiple of SectionAlignment");
if (pe->OptionalHeader.SizeOfHeaders & (pe->OptionalHeader.FileAlignment - 1))
Die(path, "PE SizeOfHeaders must be multiple of FileAlignment");
if (pe->OptionalHeader.SizeOfHeaders > pe->OptionalHeader.AddressOfEntryPoint)
Die(path, "PE SizeOfHeaders <= AddressOfEntryPoint must be the case");
if (pe->OptionalHeader.SizeOfHeaders >= pe->OptionalHeader.SizeOfImage)
Die(path, "PE SizeOfHeaders < SizeOfImage must be the case");
if (pe->OptionalHeader.SizeOfStackCommit >> 32)
Die(path, "PE SizeOfStackCommit can't exceed 4GB");
if (pe->OptionalHeader.SizeOfStackReserve >> 32)
Die(path, "PE SizeOfStackReserve can't exceed 4GB");
if (pe->OptionalHeader.SizeOfHeapCommit >> 32)
Die(path, "PE SizeOfHeapCommit can't exceed 4GB");
if (pe->OptionalHeader.SizeOfHeapReserve >> 32)
Die(path, "PE SizeOfHeapReserve can't exceed 4GB");
// check pe section headers
struct NtImageSectionHeader *sections =
(struct NtImageSectionHeader *)((char *)&pe->OptionalHeader +
pe->FileHeader.SizeOfOptionalHeader);
for (int i = 0; i < pe->FileHeader.NumberOfSections; ++i) {
if (sections[i].SizeOfRawData & (pe->OptionalHeader.FileAlignment - 1))
Die(path, "PE SizeOfRawData should be multiple of FileAlignment");
if (sections[i].PointerToRawData & (pe->OptionalHeader.FileAlignment - 1))
Die(path, "PE PointerToRawData must be multiple of FileAlignment");
if (img + sections[i].PointerToRawData >= img + imgsize)
Die(path, "PE PointerToRawData points outside image");
if (img + sections[i].PointerToRawData + sections[i].SizeOfRawData >
img + imgsize)
Die(path, "PE SizeOfRawData overlaps end of image");
if (!sections[i].VirtualAddress)
Die(path, "PE VirtualAddress shouldn't be zero");
if (sections[i].VirtualAddress & (pe->OptionalHeader.SectionAlignment - 1))
Die(path, "PE VirtualAddress must be multiple of SectionAlignment");
if ((sections[i].Characteristics &
(kNtPeSectionCntCode | kNtPeSectionCntInitializedData |
kNtPeSectionCntUninitializedData)) ==
kNtPeSectionCntUninitializedData) {
if (sections[i].SizeOfRawData)
Die(path, "PE SizeOfRawData should be zero for pure BSS section");
if (sections[i].PointerToRawData)
Die(path, "PE PointerToRawData should be zero for pure BSS section");
}
if (!i) {
if (sections[i].VirtualAddress !=
((pe->OptionalHeader.SizeOfHeaders +
(pe->OptionalHeader.SectionAlignment - 1)) &
-pe->OptionalHeader.SectionAlignment))
Die(path, "PE VirtualAddress of first section must be SizeOfHeaders "
"rounded up to SectionAlignment");
} else {
if (sections[i].VirtualAddress !=
sections[i - 1].VirtualAddress +
((sections[i - 1].Misc.VirtualSize +
(pe->OptionalHeader.SectionAlignment - 1)) &
-pe->OptionalHeader.SectionAlignment))
Die(path, "PE sections must be in ascending order and the virtual "
"memory they define must be adjacent after VirtualSize is "
"rounded up to the SectionAlignment");
}
}
int size_of_pe_headers =
(char *)(sections + pe->FileHeader.NumberOfSections) -
(char *)&pe->Signature;
return size_of_pe_headers;
}
void FixupPeImage(char *map, size_t size, //
struct NtImageNtHeaders *pe, //
const char *path, //
Elf64_Sxword rva_skew, //
Elf64_Sxword off_skew) {
assert(!(rva_skew & 65535));
// fixup pe header
if (ckd_sub(&pe->OptionalHeader.ImageBase, //
pe->OptionalHeader.ImageBase, rva_skew))
Die(path, "skewing PE ImageBase VA overflowed");
if (ckd_add(&pe->OptionalHeader.AddressOfEntryPoint,
pe->OptionalHeader.AddressOfEntryPoint, rva_skew))
Die(path, "skewing PE AddressOfEntryPoint RVA overflowed");
if (ckd_add(&pe->OptionalHeader.SizeOfImage, //
pe->OptionalHeader.SizeOfImage, rva_skew))
Die(path, "skewing PE SizeOfImage VSZ overflowed");
if (ckd_add(&pe->OptionalHeader.SizeOfHeaders, //
pe->OptionalHeader.SizeOfHeaders, off_skew))
Die(path, "skewing PE SizeOfHeaders FSZ overflowed");
// fixup dll imports
//
// this implementation currently only works on simple pe file layouts
// where relative virtual addresses are equivalent to file offsets
struct NtImageDataDirectory *ddImports =
pe->OptionalHeader.DataDirectory + kNtImageDirectoryEntryImport;
if (pe->OptionalHeader.NumberOfRvaAndSizes >= 2 && ddImports->Size) {
struct NtImageImportDescriptor *idt;
if (!(idt = GetPeRva(map, pe, ddImports->VirtualAddress)))
Die(path, "couldn't resolve VirtualAddress/Size RVA of PE Import "
"Directory Table to within a defined PE section");
for (int i = 0; idt[i].ImportLookupTable; ++i) {
uint64_t *ilt, *iat;
if (!(ilt = GetPeRva(map, pe, idt[i].ImportLookupTable)))
Die(path, "PE ImportLookupTable RVA didn't resolve to a section");
for (int j = 0; ilt[j]; ++j) {
if (ckd_add(&ilt[j], ilt[j], rva_skew))
Die(path, "skewing PE Import Lookup Table RVA overflowed");
}
if (!(iat = GetPeRva(map, pe, idt[i].ImportAddressTable)))
Die(path, "PE ImportAddressTable RVA didn't resolve to a section");
for (int j = 0; iat[j]; ++j) {
if (ckd_add(&iat[j], iat[j], rva_skew))
Die(path, "skewing PE Import Lookup Table RVA overflowed");
}
if (ckd_add(&idt[i].DllNameRva, idt[i].DllNameRva, rva_skew))
Die(path, "skewing PE IDT DllNameRva RVA overflowed");
if (ckd_add(&idt[i].ImportLookupTable, idt[i].ImportLookupTable,
rva_skew))
Die(path, "skewing PE IDT ImportLookupTable RVA overflowed");
if (ckd_add(&idt[i].ImportAddressTable, idt[i].ImportAddressTable,
rva_skew))
Die(path, "skewing PE IDT ImportAddressTable RVA overflowed");
}
if (ckd_add(&ddImports->VirtualAddress, ddImports->VirtualAddress,
rva_skew))
Die(path, "skewing PE IMAGE_DIRECTORY_ENTRY_IMPORT RVA overflowed");
}
// fixup pe segments table
struct NtImageSectionHeader *sections =
(struct NtImageSectionHeader *)((char *)&pe->OptionalHeader +
pe->FileHeader.SizeOfOptionalHeader);
for (int i = 0; i < pe->FileHeader.NumberOfSections; ++i) {
if (ckd_add(§ions[i].VirtualAddress, sections[i].VirtualAddress,
rva_skew))
Die(path, "skewing PE section VirtualAddress overflowed");
if (ckd_add(§ions[i].PointerToRawData, sections[i].PointerToRawData,
off_skew))
Die(path, "skewing PE section PointerToRawData overflowed");
}
}
static bool FindLoaderEmbeddedMachoHeader(struct Loader *ape) {
size_t i;
struct MachoHeader *macho;
for (i = 0; i + sizeof(struct MachoHeader) < ape->size; i += 64) {
if (READ32LE((char *)ape->map + i) == 0xFEEDFACE + 1) {
macho = (struct MachoHeader *)((char *)ape->map + i);
ape->macho_offset = i;
ape->macho_length = sizeof(*macho) + macho->loadsize;
return true;
}
}
return false;
}
static struct Input *GetInput(int machine) {
int i;
for (i = 0; i < inputs.n; ++i) {
if (inputs.p[i].elf->e_machine == machine) {
return inputs.p + i;
}
}
return 0;
}
static struct Loader *GetLoader(int machine, int os) {
int i;
for (i = 0; i < loaders.n; ++i) {
if ((loaders.p[i].os & os) && loaders.p[i].machine == machine) {
return loaders.p + i;
}
}
return 0;
}
static void AddLoader(const char *path) {
if (loaders.n == ARRAYLEN(loaders.p)) {
Die(prog, "too many loaders");
}
loaders.p[loaders.n++].path = path;
}
static void GetOpts(int argc, char *argv[]) {
int opt, bits;
bool got_support_vector = false;
while ((opt = getopt(argc, argv, "hvgsGBo:l:S:M:V:")) != -1) {
switch (opt) {
case 'o':
outpath = optarg;
break;
case 's':
HashInputString("-s");
want_stripped = true;
break;
case 'V':
HashInputString("-V");
HashInputString(optarg);
if (ParseSupportVector(optarg, &bits)) {
support_vector |= bits;
} else {
Die(prog, "unrecognized token passed to -s support vector flag");
exit(1);
}
got_support_vector = true;
break;
case 'l':
HashInputString("-l");
AddLoader(optarg);
break;
case 'S':
HashInputString("-S");