]> git.saurik.com Git - ldid.git/blame_incremental - ldid.cpp
Add a build environment for iOS+Cydia packaging.
[ldid.git] / ldid.cpp
... / ...
CommitLineData
1/* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2012 Jay Freeman (saurik)
3*/
4
5/* GNU Lesser General Public License, Version 3 {{{ */
6/* This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18**/
19/* }}} */
20
21#include "minimal/stdlib.h"
22#include "minimal/string.h"
23#include "minimal/mapping.h"
24
25#include "sha1.h"
26
27#include <cstring>
28#include <string>
29#include <vector>
30
31#include <sys/wait.h>
32#include <sys/types.h>
33#include <sys/stat.h>
34
35struct fat_header {
36 uint32_t magic;
37 uint32_t nfat_arch;
38} _packed;
39
40#define FAT_MAGIC 0xcafebabe
41#define FAT_CIGAM 0xbebafeca
42
43struct fat_arch {
44 uint32_t cputype;
45 uint32_t cpusubtype;
46 uint32_t offset;
47 uint32_t size;
48 uint32_t align;
49} _packed;
50
51struct mach_header {
52 uint32_t magic;
53 uint32_t cputype;
54 uint32_t cpusubtype;
55 uint32_t filetype;
56 uint32_t ncmds;
57 uint32_t sizeofcmds;
58 uint32_t flags;
59} _packed;
60
61#define MH_MAGIC 0xfeedface
62#define MH_CIGAM 0xcefaedfe
63
64#define MH_MAGIC_64 0xfeedfacf
65#define MH_CIGAM_64 0xcffaedfe
66
67#define MH_DYLDLINK 0x4
68
69#define MH_EXECUTE 0x2
70#define MH_DYLIB 0x6
71#define MH_BUNDLE 0x8
72#define MH_DYLIB_STUB 0x9
73
74struct load_command {
75 uint32_t cmd;
76 uint32_t cmdsize;
77} _packed;
78
79#define LC_REQ_DYLD uint32_t(0x80000000)
80
81#define LC_SEGMENT uint32_t(0x01)
82#define LC_SYMTAB uint32_t(0x02)
83#define LC_DYSYMTAB uint32_t(0x0b)
84#define LC_LOAD_DYLIB uint32_t(0x0c)
85#define LC_ID_DYLIB uint32_t(0x0d)
86#define LC_SEGMENT_64 uint32_t(0x19)
87#define LC_UUID uint32_t(0x1b)
88#define LC_CODE_SIGNATURE uint32_t(0x1d)
89#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
90#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
91#define LC_ENCRYPTION_INFO uint32_t(0x21)
92#define LC_DYLD_INFO uint32_t(0x22)
93#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
94
95struct dylib {
96 uint32_t name;
97 uint32_t timestamp;
98 uint32_t current_version;
99 uint32_t compatibility_version;
100} _packed;
101
102struct dylib_command {
103 uint32_t cmd;
104 uint32_t cmdsize;
105 struct dylib dylib;
106} _packed;
107
108struct uuid_command {
109 uint32_t cmd;
110 uint32_t cmdsize;
111 uint8_t uuid[16];
112} _packed;
113
114struct symtab_command {
115 uint32_t cmd;
116 uint32_t cmdsize;
117 uint32_t symoff;
118 uint32_t nsyms;
119 uint32_t stroff;
120 uint32_t strsize;
121} _packed;
122
123struct dyld_info_command {
124 uint32_t cmd;
125 uint32_t cmdsize;
126 uint32_t rebase_off;
127 uint32_t rebase_size;
128 uint32_t bind_off;
129 uint32_t bind_size;
130 uint32_t weak_bind_off;
131 uint32_t weak_bind_size;
132 uint32_t lazy_bind_off;
133 uint32_t lazy_bind_size;
134 uint32_t export_off;
135 uint32_t export_size;
136} _packed;
137
138struct dysymtab_command {
139 uint32_t cmd;
140 uint32_t cmdsize;
141 uint32_t ilocalsym;
142 uint32_t nlocalsym;
143 uint32_t iextdefsym;
144 uint32_t nextdefsym;
145 uint32_t iundefsym;
146 uint32_t nundefsym;
147 uint32_t tocoff;
148 uint32_t ntoc;
149 uint32_t modtaboff;
150 uint32_t nmodtab;
151 uint32_t extrefsymoff;
152 uint32_t nextrefsyms;
153 uint32_t indirectsymoff;
154 uint32_t nindirectsyms;
155 uint32_t extreloff;
156 uint32_t nextrel;
157 uint32_t locreloff;
158 uint32_t nlocrel;
159} _packed;
160
161struct dylib_table_of_contents {
162 uint32_t symbol_index;
163 uint32_t module_index;
164} _packed;
165
166struct dylib_module {
167 uint32_t module_name;
168 uint32_t iextdefsym;
169 uint32_t nextdefsym;
170 uint32_t irefsym;
171 uint32_t nrefsym;
172 uint32_t ilocalsym;
173 uint32_t nlocalsym;
174 uint32_t iextrel;
175 uint32_t nextrel;
176 uint32_t iinit_iterm;
177 uint32_t ninit_nterm;
178 uint32_t objc_module_info_addr;
179 uint32_t objc_module_info_size;
180} _packed;
181
182struct dylib_reference {
183 uint32_t isym:24;
184 uint32_t flags:8;
185} _packed;
186
187struct relocation_info {
188 int32_t r_address;
189 uint32_t r_symbolnum:24;
190 uint32_t r_pcrel:1;
191 uint32_t r_length:2;
192 uint32_t r_extern:1;
193 uint32_t r_type:4;
194} _packed;
195
196struct nlist {
197 union {
198 char *n_name;
199 int32_t n_strx;
200 } n_un;
201
202 uint8_t n_type;
203 uint8_t n_sect;
204 uint8_t n_desc;
205 uint32_t n_value;
206} _packed;
207
208struct segment_command {
209 uint32_t cmd;
210 uint32_t cmdsize;
211 char segname[16];
212 uint32_t vmaddr;
213 uint32_t vmsize;
214 uint32_t fileoff;
215 uint32_t filesize;
216 uint32_t maxprot;
217 uint32_t initprot;
218 uint32_t nsects;
219 uint32_t flags;
220} _packed;
221
222struct segment_command_64 {
223 uint32_t cmd;
224 uint32_t cmdsize;
225 char segname[16];
226 uint64_t vmaddr;
227 uint64_t vmsize;
228 uint64_t fileoff;
229 uint64_t filesize;
230 uint32_t maxprot;
231 uint32_t initprot;
232 uint32_t nsects;
233 uint32_t flags;
234} _packed;
235
236struct section {
237 char sectname[16];
238 char segname[16];
239 uint32_t addr;
240 uint32_t size;
241 uint32_t offset;
242 uint32_t align;
243 uint32_t reloff;
244 uint32_t nreloc;
245 uint32_t flags;
246 uint32_t reserved1;
247 uint32_t reserved2;
248} _packed;
249
250struct section_64 {
251 char sectname[16];
252 char segname[16];
253 uint64_t addr;
254 uint64_t size;
255 uint32_t offset;
256 uint32_t align;
257 uint32_t reloff;
258 uint32_t nreloc;
259 uint32_t flags;
260 uint32_t reserved1;
261 uint32_t reserved2;
262} _packed;
263
264struct linkedit_data_command {
265 uint32_t cmd;
266 uint32_t cmdsize;
267 uint32_t dataoff;
268 uint32_t datasize;
269} _packed;
270
271struct encryption_info_command {
272 uint32_t cmd;
273 uint32_t cmdsize;
274 uint32_t cryptoff;
275 uint32_t cryptsize;
276 uint32_t cryptid;
277} _packed;
278
279uint16_t Swap_(uint16_t value) {
280 return
281 ((value >> 8) & 0x00ff) |
282 ((value << 8) & 0xff00);
283}
284
285uint32_t Swap_(uint32_t value) {
286 value = ((value >> 8) & 0x00ff00ff) |
287 ((value << 8) & 0xff00ff00);
288 value = ((value >> 16) & 0x0000ffff) |
289 ((value << 16) & 0xffff0000);
290 return value;
291}
292
293int16_t Swap_(int16_t value) {
294 return Swap_(static_cast<uint16_t>(value));
295}
296
297int32_t Swap_(int32_t value) {
298 return Swap_(static_cast<uint32_t>(value));
299}
300
301bool little_(true);
302
303uint16_t Swap(uint16_t value) {
304 return little_ ? Swap_(value) : value;
305}
306
307uint32_t Swap(uint32_t value) {
308 return little_ ? Swap_(value) : value;
309}
310
311int16_t Swap(int16_t value) {
312 return Swap(static_cast<uint16_t>(value));
313}
314
315int32_t Swap(int32_t value) {
316 return Swap(static_cast<uint32_t>(value));
317}
318
319template <typename Target_>
320class Pointer;
321
322class Data {
323 private:
324 void *base_;
325 size_t size_;
326
327 protected:
328 bool swapped_;
329
330 public:
331 Data(void *base, size_t size) :
332 base_(base),
333 size_(size),
334 swapped_(false)
335 {
336 }
337
338 uint16_t Swap(uint16_t value) const {
339 return swapped_ ? Swap_(value) : value;
340 }
341
342 uint32_t Swap(uint32_t value) const {
343 return swapped_ ? Swap_(value) : value;
344 }
345
346 int16_t Swap(int16_t value) const {
347 return Swap(static_cast<uint16_t>(value));
348 }
349
350 int32_t Swap(int32_t value) const {
351 return Swap(static_cast<uint32_t>(value));
352 }
353
354 void *GetBase() const {
355 return base_;
356 }
357
358 size_t GetSize() const {
359 return size_;
360 }
361};
362
363class MachHeader :
364 public Data
365{
366 private:
367 bool bits64_;
368
369 struct mach_header *mach_header_;
370 struct load_command *load_command_;
371
372 public:
373 MachHeader(void *base, size_t size) :
374 Data(base, size)
375 {
376 mach_header_ = (mach_header *) base;
377
378 switch (Swap(mach_header_->magic)) {
379 case MH_CIGAM:
380 swapped_ = !swapped_;
381 case MH_MAGIC:
382 bits64_ = false;
383 break;
384
385 case MH_CIGAM_64:
386 swapped_ = !swapped_;
387 case MH_MAGIC_64:
388 bits64_ = true;
389 break;
390
391 default:
392 _assert(false);
393 }
394
395 void *post = mach_header_ + 1;
396 if (bits64_)
397 post = (uint32_t *) post + 1;
398 load_command_ = (struct load_command *) post;
399
400 _assert(
401 Swap(mach_header_->filetype) == MH_EXECUTE ||
402 Swap(mach_header_->filetype) == MH_DYLIB ||
403 Swap(mach_header_->filetype) == MH_BUNDLE
404 );
405 }
406
407 struct mach_header *operator ->() const {
408 return mach_header_;
409 }
410
411 uint32_t GetCPUType() const {
412 return Swap(mach_header_->cputype);
413 }
414
415 uint16_t GetCPUSubtype() const {
416 return Swap(mach_header_->cpusubtype) & 0xff;
417 }
418
419 std::vector<struct load_command *> GetLoadCommands() const {
420 std::vector<struct load_command *> load_commands;
421
422 struct load_command *load_command = load_command_;
423 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
424 load_commands.push_back(load_command);
425 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
426 }
427
428 return load_commands;
429 }
430
431 std::vector<segment_command *> GetSegments(const char *segment_name) const {
432 std::vector<struct segment_command *> segment_commands;
433
434 _foreach (load_command, GetLoadCommands()) {
435 if (Swap(load_command->cmd) == LC_SEGMENT) {
436 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
437 if (strncmp(segment_command->segname, segment_name, 16) == 0)
438 segment_commands.push_back(segment_command);
439 }
440 }
441
442 return segment_commands;
443 }
444
445 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) {
446 std::vector<struct segment_command_64 *> segment_commands;
447
448 _foreach (load_command, GetLoadCommands()) {
449 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
450 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
451 if (strncmp(segment_command->segname, segment_name, 16) == 0)
452 segment_commands.push_back(segment_command);
453 }
454 }
455
456 return segment_commands;
457 }
458
459 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
460 std::vector<section *> sections;
461
462 _foreach (segment, GetSegments(segment_name)) {
463 section *section = (struct section *) (segment + 1);
464
465 uint32_t sect;
466 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
467 if (strncmp(section->sectname, section_name, 16) == 0)
468 sections.push_back(section);
469 ++section;
470 }
471 }
472
473 return sections;
474 }
475
476 template <typename Target_>
477 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
478 load_command *load_command = (struct load_command *) (mach_header_ + 1);
479 uint32_t cmd;
480
481 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
482 if (Swap(load_command->cmd) == LC_SEGMENT) {
483 segment_command *segment_command = (struct segment_command *) load_command;
484 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
485 goto next_command;
486
487 section *sections = (struct section *) (segment_command + 1);
488
489 uint32_t sect;
490 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
491 section *section = &sections[sect];
492 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
493 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
494 //printf("0x%.8x %s\n", address, segment_command->segname);
495 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
496 }
497 }
498 }
499
500 next_command:
501 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
502 }
503
504 return Pointer<Target_>(this);
505 }
506
507 template <typename Target_>
508 Pointer<Target_> GetOffset(uint32_t offset) {
509 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
510 }
511};
512
513class FatMachHeader :
514 public MachHeader
515{
516 private:
517 fat_arch *fat_arch_;
518
519 public:
520 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
521 MachHeader(base, size),
522 fat_arch_(fat_arch)
523 {
524 }
525
526 fat_arch *GetFatArch() const {
527 return fat_arch_;
528 }
529};
530
531class FatHeader :
532 public Data
533{
534 private:
535 fat_header *fat_header_;
536 std::vector<FatMachHeader> mach_headers_;
537
538 public:
539 FatHeader(void *base, size_t size) :
540 Data(base, size)
541 {
542 fat_header_ = reinterpret_cast<struct fat_header *>(base);
543
544 if (Swap(fat_header_->magic) == FAT_CIGAM) {
545 swapped_ = !swapped_;
546 goto fat;
547 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
548 fat_header_ = NULL;
549 mach_headers_.push_back(FatMachHeader(base, size, NULL));
550 } else fat: {
551 size_t fat_narch = Swap(fat_header_->nfat_arch);
552 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
553 size_t arch;
554 for (arch = 0; arch != fat_narch; ++arch) {
555 uint32_t arch_offset = Swap(fat_arch->offset);
556 uint32_t arch_size = Swap(fat_arch->size);
557 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
558 ++fat_arch;
559 }
560 }
561 }
562
563 std::vector<FatMachHeader> &GetMachHeaders() {
564 return mach_headers_;
565 }
566
567 bool IsFat() const {
568 return fat_header_ != NULL;
569 }
570
571 struct fat_header *operator ->() const {
572 return fat_header_;
573 }
574};
575
576FatHeader Map(const char *path, bool ro = false) {
577 size_t size;
578 void *base(map(path, 0, _not(size_t), &size, ro));
579 return FatHeader(base, size);
580}
581
582template <typename Target_>
583class Pointer {
584 private:
585 const MachHeader *framework_;
586 const Target_ *pointer_;
587
588 public:
589 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
590 framework_(framework),
591 pointer_(pointer)
592 {
593 }
594
595 operator const Target_ *() const {
596 return pointer_;
597 }
598
599 const Target_ *operator ->() const {
600 return pointer_;
601 }
602
603 Pointer<Target_> &operator ++() {
604 ++pointer_;
605 return *this;
606 }
607
608 template <typename Value_>
609 Value_ Swap(Value_ value) {
610 return framework_->Swap(value);
611 }
612};
613
614#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
615#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
616#define CSMAGIC_ENTITLEMENTS uint32_t(0xfade7171)
617
618#define CSSLOT_CODEDIRECTORY uint32_t(0)
619#define CSSLOT_REQUIREMENTS uint32_t(2)
620#define CSSLOT_ENTITLEMENTS uint32_t(5)
621
622struct BlobIndex {
623 uint32_t type;
624 uint32_t offset;
625} _packed;
626
627struct Blob {
628 uint32_t magic;
629 uint32_t length;
630} _packed;
631
632struct SuperBlob {
633 struct Blob blob;
634 uint32_t count;
635 struct BlobIndex index[];
636} _packed;
637
638struct CodeDirectory {
639 struct Blob blob;
640 uint32_t version;
641 uint32_t flags;
642 uint32_t hashOffset;
643 uint32_t identOffset;
644 uint32_t nSpecialSlots;
645 uint32_t nCodeSlots;
646 uint32_t codeLimit;
647 uint8_t hashSize;
648 uint8_t hashType;
649 uint8_t spare1;
650 uint8_t pageSize;
651 uint32_t spare2;
652} _packed;
653
654extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
655
656void sha1(uint8_t *hash, uint8_t *data, size_t size) {
657 SHA1Context context;
658 SHA1Reset(&context);
659 SHA1Input(&context, data, size);
660 SHA1Result(&context, hash);
661}
662
663struct CodesignAllocation {
664 uint32_t type_;
665 uint16_t subtype_;
666 size_t size_;
667
668 CodesignAllocation(uint32_t type, uint16_t subtype, size_t size) :
669 type_(type),
670 subtype_(subtype),
671 size_(size)
672 {
673 }
674};
675
676int main(int argc, const char *argv[]) {
677 union {
678 uint16_t word;
679 uint8_t byte[2];
680 } endian = {1};
681
682 little_ = endian.byte[0];
683
684 bool flag_R(false);
685 bool flag_r(false);
686
687 bool flag_t(false);
688 bool flag_p(false);
689 bool flag_u(false);
690 bool flag_e(false);
691
692 bool flag_T(false);
693
694 bool flag_S(false);
695 bool flag_s(false);
696
697 bool flag_O(false);
698
699 bool flag_D(false);
700 bool flag_d(false);
701
702 bool flag_A(false);
703 bool flag_a(false);
704
705 uint32_t flag_CPUType(_not(uint32_t));
706 uint32_t flag_CPUSubtype(_not(uint32_t));
707
708 bool timeh(false);
709 uint32_t timev(0);
710
711 const void *xmld(NULL);
712 size_t xmls(0);
713
714 uintptr_t noffset(_not(uintptr_t));
715 uintptr_t woffset(_not(uintptr_t));
716
717 std::vector<std::string> files;
718
719 if (argc == 1) {
720 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
721 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
722 fprintf(stderr, " %s -S cat\n", argv[0]);
723 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
724 exit(0);
725 }
726
727 for (int argi(1); argi != argc; ++argi)
728 if (argv[argi][0] != '-')
729 files.push_back(argv[argi]);
730 else switch (argv[argi][1]) {
731 case 'R': flag_R = true; break;
732 case 'r': flag_r = true; break;
733
734 case 't': flag_t = true; break;
735 case 'u': flag_u = true; break;
736 case 'p': flag_p = true; break;
737 case 'e': flag_e = true; break;
738 case 'O': flag_O = true; break;
739
740 case 'D': flag_D = true; break;
741 case 'd': flag_d = true; break;
742
743 case 'a': flag_a = true; break;
744
745 case 'A':
746 flag_A = true;
747 if (argv[argi][2] != '\0') {
748 const char *cpu = argv[argi] + 2;
749 const char *colon = strchr(cpu, ':');
750 _assert(colon != NULL);
751 char *arge;
752 flag_CPUType = strtoul(cpu, &arge, 0);
753 _assert(arge == colon);
754 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
755 _assert(arge == argv[argi] + strlen(argv[argi]));
756 }
757 break;
758
759 case 's':
760 _assert(!flag_S);
761 flag_s = true;
762 break;
763
764 case 'S':
765 _assert(!flag_s);
766 flag_S = true;
767 if (argv[argi][2] != '\0') {
768 const char *xml = argv[argi] + 2;
769 xmld = map(xml, 0, _not(size_t), &xmls, true);
770 }
771 break;
772
773 case 'T': {
774 flag_T = true;
775 if (argv[argi][2] == '-')
776 timeh = true;
777 else {
778 char *arge;
779 timev = strtoul(argv[argi] + 2, &arge, 0);
780 _assert(arge == argv[argi] + strlen(argv[argi]));
781 }
782 } break;
783
784 case 'n': {
785 char *arge;
786 noffset = strtoul(argv[argi] + 2, &arge, 0);
787 _assert(arge == argv[argi] + strlen(argv[argi]));
788 } break;
789
790 case 'w': {
791 char *arge;
792 woffset = strtoul(argv[argi] + 2, &arge, 0);
793 _assert(arge == argv[argi] + strlen(argv[argi]));
794 } break;
795
796 default:
797 goto usage;
798 break;
799 }
800
801 if (files.empty()) usage: {
802 exit(0);
803 }
804
805 size_t filei(0), filee(0);
806 _foreach (file, files) try {
807 const char *path(file.c_str());
808 const char *base = strrchr(path, '/');
809 char *temp(NULL), *dir;
810
811 if (base != NULL)
812 dir = strndup_(path, base++ - path + 1);
813 else {
814 dir = strdup("");
815 base = path;
816 }
817
818 if (flag_r) {
819 uint32_t clip(0); {
820 FatHeader fat_header(Map(path));
821 _foreach (mach_header, fat_header.GetMachHeaders()) {
822 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
823
824 uint32_t size(_not(uint32_t)); {
825 _foreach (load_command, mach_header.GetLoadCommands()) {
826 switch (mach_header.Swap(load_command->cmd)) {
827 case LC_CODE_SIGNATURE: {
828 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
829 memset(reinterpret_cast<uint8_t *>(mach_header.GetBase()) + mach_header.Swap(signature->dataoff), 0, mach_header.Swap(signature->datasize));
830 memset(signature, 0, sizeof(struct linkedit_data_command));
831
832 mach_header->ncmds = mach_header.Swap(mach_header.Swap(mach_header->ncmds) - 1);
833 mach_header->sizeofcmds = mach_header.Swap(uint32_t(mach_header.Swap(mach_header->sizeofcmds) - sizeof(struct linkedit_data_command)));
834 } break;
835
836 case LC_SYMTAB: {
837 struct symtab_command *symtab = reinterpret_cast<struct symtab_command *>(load_command);
838 size = mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize);
839 } break;
840 }
841 }
842 }
843
844 _assert(size != _not(uint32_t));
845
846 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments("__LINKEDIT")) {
847 segment->filesize -= mach_header.GetSize() - size;
848
849 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
850 fat_arch->size = fat_header.Swap(size);
851 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
852 } else
853 clip = std::max(clip, size);
854 }
855
856 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments64("__LINKEDIT")) {
857 segment->filesize -= mach_header.GetSize() - size;
858
859 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
860 fat_arch->size = fat_header.Swap(size);
861 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
862 } else
863 clip = std::max(clip, size);
864 }
865 }
866 }
867
868 _assert(clip != 0);
869 _syscall(truncate(path, clip));
870 }
871
872 if (flag_S) {
873 asprintf(&temp, "%s.%s.cs", dir, base);
874 const char *allocate = getenv("CODESIGN_ALLOCATE");
875 if (allocate == NULL)
876 allocate = "codesign_allocate";
877
878 std::vector<CodesignAllocation> allocations; {
879 FatHeader fat_header(Map(path));
880 _foreach (mach_header, fat_header.GetMachHeaders()) {
881 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
882
883 size_t size(_not(size_t)); {
884 _foreach (load_command, mach_header.GetLoadCommands()) {
885 uint32_t cmd(mach_header.Swap(load_command->cmd));
886 if (cmd == LC_CODE_SIGNATURE) {
887 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
888 size = mach_header.Swap(signature->dataoff);
889 _assert(size < mach_header.GetSize());
890 break;
891 }
892 }
893
894 if (size == _not(size_t))
895 size = mach_header.GetSize();
896 }
897
898 allocations.push_back(CodesignAllocation(mach_header.GetCPUType(), mach_header.GetCPUSubtype(), size));
899 }
900 }
901
902 pid_t pid = fork();
903 _syscall(pid);
904 if (pid == 0) {
905 // XXX: this leaks memory, but it doesn't really matter
906 std::vector<const char *> args;
907 char *arg;
908
909 args.push_back(allocate);
910
911 args.push_back("-i");
912 args.push_back(path);
913
914 _foreach (allocation, allocations) {
915 args.push_back("-A");
916
917 asprintf(&arg, "%u", allocation.type_);
918 args.push_back(arg);
919
920 asprintf(&arg, "%u", allocation.subtype_);
921 args.push_back(arg);
922
923 size_t alloc(0);
924 alloc += sizeof(struct SuperBlob);
925 uint32_t special(0);
926
927 special = std::max(special, CSSLOT_CODEDIRECTORY);
928 alloc += sizeof(struct BlobIndex);
929 alloc += sizeof(struct CodeDirectory);
930 alloc += strlen(base) + 1;
931
932 special = std::max(special, CSSLOT_REQUIREMENTS);
933 alloc += sizeof(struct BlobIndex);
934 alloc += 0xc;
935
936 if (xmld != NULL) {
937 special = std::max(special, CSSLOT_ENTITLEMENTS);
938 alloc += sizeof(struct BlobIndex);
939 alloc += sizeof(struct Blob);
940 alloc += xmls;
941 }
942
943 size_t normal((allocation.size_ + 0x1000 - 1) / 0x1000);
944 alloc += (special + normal) * 0x14;
945
946 alloc += 15;
947 alloc /= 16;
948 alloc *= 16;
949
950 asprintf(&arg, "%zu", alloc);
951 args.push_back(arg);
952 }
953
954 args.push_back("-o");
955 args.push_back(temp);
956
957 args.push_back(NULL);
958
959 if (false) {
960 printf("run:");
961 _foreach (arg, args)
962 printf(" %s", arg);
963 printf("\n");
964 }
965
966 execvp(allocate, (char **) &args[0]);
967 _assert(false);
968 }
969
970 int status;
971 _syscall(waitpid(pid, &status, 0));
972 _assert(WIFEXITED(status));
973 _assert(WEXITSTATUS(status) == 0);
974 }
975
976 if (flag_p)
977 printf("path%zu='%s'\n", filei, file.c_str());
978
979 FatHeader fat_header(Map(temp == NULL ? path : temp, !(flag_R | flag_T | flag_s | flag_S | flag_O | flag_D)));
980 struct linkedit_data_command *signature(NULL);
981
982 _foreach (mach_header, fat_header.GetMachHeaders()) {
983 if (flag_A) {
984 if (mach_header.GetCPUType() != flag_CPUType)
985 continue;
986 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
987 continue;
988 }
989
990 if (flag_a)
991 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
992
993 if (flag_d) {
994 if (struct fat_arch *fat_arch = mach_header.GetFatArch())
995 printf("offset=0x%x\n", Swap(fat_arch->offset));
996 else
997 printf("offset=0x0\n");
998 }
999
1000 if (woffset != _not(uintptr_t)) {
1001 Pointer<uint32_t> wvalue(mach_header.GetPointer<uint32_t>(woffset));
1002 if (wvalue == NULL)
1003 printf("(null) %p\n", reinterpret_cast<void *>(woffset));
1004 else
1005 printf("0x%.08x\n", *wvalue);
1006 }
1007
1008 if (noffset != _not(uintptr_t))
1009 printf("%s\n", &*mach_header.GetPointer<char>(noffset));
1010
1011 if (flag_d)
1012 _foreach(segment, mach_header.GetSegments("__TEXT")) {
1013 printf("vmaddr=0x%x\n", mach_header.Swap(segment->vmaddr));
1014 printf("fileoff=0x%x\n", mach_header.Swap(segment->fileoff));
1015 }
1016
1017 if (flag_O) {
1018 _foreach(section, mach_header.GetSections("__TEXT", "__text"))
1019 section->addr = mach_header.Swap(0);
1020 }
1021
1022 _foreach (load_command, mach_header.GetLoadCommands()) {
1023 uint32_t cmd(mach_header.Swap(load_command->cmd));
1024
1025 if (flag_R && cmd == LC_REEXPORT_DYLIB)
1026 load_command->cmd = mach_header.Swap(LC_LOAD_DYLIB);
1027 else if (cmd == LC_CODE_SIGNATURE)
1028 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1029 else if (cmd == LC_UUID) {
1030 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(load_command));
1031
1032 if (flag_u) {
1033 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
1034 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
1035 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
1036 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
1037 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
1038 );
1039 }
1040 } else if (cmd == LC_ID_DYLIB) {
1041 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
1042
1043 if (flag_t)
1044 printf("time%zu=0x%.8x\n", filei, mach_header.Swap(dylib_command->dylib.timestamp));
1045
1046 if (flag_T) {
1047 uint32_t timed;
1048
1049 if (!timeh)
1050 timed = timev;
1051 else {
1052 dylib_command->dylib.timestamp = 0;
1053 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1054 }
1055
1056 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1057 }
1058 } else if (cmd == LC_ENCRYPTION_INFO) {
1059 volatile struct encryption_info_command *encryption_info_command(reinterpret_cast<struct encryption_info_command *>(load_command));
1060
1061 if (flag_D)
1062 encryption_info_command->cryptid = mach_header.Swap(0);
1063
1064 if (flag_d) {
1065 printf("cryptoff=0x%x\n", mach_header.Swap(encryption_info_command->cryptoff));
1066 printf("cryptsize=0x%x\n", mach_header.Swap(encryption_info_command->cryptsize));
1067 }
1068 }
1069 }
1070
1071 if (flag_e) {
1072 _assert(signature != NULL);
1073
1074 uint32_t data = mach_header.Swap(signature->dataoff);
1075
1076 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1077 uint8_t *blob = top + data;
1078 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1079
1080 for (size_t index(0); index != Swap(super->count); ++index)
1081 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1082 uint32_t begin = Swap(super->index[index].offset);
1083 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1084 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
1085 }
1086 }
1087
1088 if (flag_s) {
1089 _assert(signature != NULL);
1090
1091 uint32_t data = mach_header.Swap(signature->dataoff);
1092
1093 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1094 uint8_t *blob = top + data;
1095 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1096
1097 for (size_t index(0); index != Swap(super->count); ++index)
1098 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1099 uint32_t begin = Swap(super->index[index].offset);
1100 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1101
1102 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + begin + Swap(directory->hashOffset));
1103 uint32_t pages = Swap(directory->nCodeSlots);
1104
1105 if (pages != 1)
1106 for (size_t i = 0; i != pages - 1; ++i)
1107 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1108 if (pages != 0)
1109 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1110 }
1111 }
1112
1113 if (flag_S) {
1114 _assert(signature != NULL);
1115
1116 uint32_t data = mach_header.Swap(signature->dataoff);
1117 uint32_t size = mach_header.Swap(signature->datasize);
1118
1119 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1120 uint8_t *blob = top + data;
1121 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1122 super->blob.magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
1123
1124 uint32_t count = xmld == NULL ? 2 : 3;
1125 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
1126
1127 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
1128 super->index[0].offset = Swap(offset);
1129
1130 uint32_t begin = offset;
1131 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1132 offset += sizeof(struct CodeDirectory);
1133
1134 directory->blob.magic = Swap(CSMAGIC_CODEDIRECTORY);
1135 directory->version = Swap(uint32_t(0x00020001));
1136 directory->flags = Swap(uint32_t(0));
1137 directory->codeLimit = Swap(data);
1138 directory->hashSize = 0x14;
1139 directory->hashType = 0x01;
1140 directory->spare1 = 0x00;
1141 directory->pageSize = 0x0c;
1142 directory->spare2 = Swap(uint32_t(0));
1143
1144 directory->identOffset = Swap(offset - begin);
1145 strcpy(reinterpret_cast<char *>(blob + offset), base);
1146 offset += strlen(base) + 1;
1147
1148 uint32_t special = xmld == NULL ? CSSLOT_REQUIREMENTS : CSSLOT_ENTITLEMENTS;
1149 directory->nSpecialSlots = Swap(special);
1150
1151 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
1152 memset(hashes, 0, sizeof(*hashes) * special);
1153
1154 offset += sizeof(*hashes) * special;
1155 hashes += special;
1156
1157 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
1158 directory->nCodeSlots = Swap(pages);
1159
1160 if (pages != 1)
1161 for (size_t i = 0; i != pages - 1; ++i)
1162 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1163 if (pages != 0)
1164 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1165
1166 directory->hashOffset = Swap(offset - begin);
1167 offset += sizeof(*hashes) * pages;
1168 directory->blob.length = Swap(offset - begin);
1169
1170 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
1171 super->index[1].offset = Swap(offset);
1172
1173 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
1174 offset += 0xc;
1175
1176 if (xmld != NULL) {
1177 super->index[2].type = Swap(CSSLOT_ENTITLEMENTS);
1178 super->index[2].offset = Swap(offset);
1179
1180 uint32_t begin = offset;
1181 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1182 offset += sizeof(struct Blob);
1183
1184 memcpy(blob + offset, xmld, xmls);
1185 offset += xmls;
1186
1187 entitlements->magic = Swap(CSMAGIC_ENTITLEMENTS);
1188 entitlements->length = Swap(offset - begin);
1189 }
1190
1191 for (size_t index(0); index != count; ++index) {
1192 uint32_t type = Swap(super->index[index].type);
1193 if (type != 0 && type <= special) {
1194 uint32_t offset = Swap(super->index[index].offset);
1195 struct Blob *local = (struct Blob *) (blob + offset);
1196 sha1((uint8_t *) (hashes - type), (uint8_t *) local, Swap(local->length));
1197 }
1198 }
1199
1200 super->count = Swap(count);
1201 super->blob.length = Swap(offset);
1202
1203 if (offset > size) {
1204 fprintf(stderr, "offset (%u) > size (%u)\n", offset, size);
1205 _assert(false);
1206 } //else fprintf(stderr, "offset (%zu) <= size (%zu)\n", offset, size);
1207
1208 memset(blob + offset, 0, size - offset);
1209 }
1210 }
1211
1212 if (flag_S) {
1213 uint8_t *top = reinterpret_cast<uint8_t *>(fat_header.GetBase());
1214 size_t size = fat_header.GetSize();
1215
1216 char *copy;
1217 asprintf(&copy, "%s.%s.cp", dir, base);
1218 FILE *file = fopen(copy, "w+");
1219 size_t writ = fwrite(top, 1, size, file);
1220 _assert(writ == size);
1221 fclose(file);
1222
1223 _syscall(unlink(temp));
1224 free(temp);
1225 temp = copy;
1226 }
1227
1228 if (temp != NULL) {
1229 struct stat info;
1230 _syscall(stat(path, &info));
1231 _syscall(chown(temp, info.st_uid, info.st_gid));
1232 _syscall(chmod(temp, info.st_mode));
1233 _syscall(unlink(path));
1234 _syscall(rename(temp, path));
1235 free(temp);
1236 }
1237
1238 free(dir);
1239 ++filei;
1240 } catch (const char *) {
1241 ++filee;
1242 ++filei;
1243 }
1244
1245 return filee;
1246}