]> git.cameronkatri.com Git - ldid.git/blob - ldid.cpp
Use the new -A cpu filter when using -r and -S.
[ldid.git] / ldid.cpp
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
35 struct 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
43 struct 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
51 struct 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
74 struct 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
95 struct dylib {
96 uint32_t name;
97 uint32_t timestamp;
98 uint32_t current_version;
99 uint32_t compatibility_version;
100 } _packed;
101
102 struct dylib_command {
103 uint32_t cmd;
104 uint32_t cmdsize;
105 struct dylib dylib;
106 } _packed;
107
108 struct uuid_command {
109 uint32_t cmd;
110 uint32_t cmdsize;
111 uint8_t uuid[16];
112 } _packed;
113
114 struct 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
123 struct 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
138 struct 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
161 struct dylib_table_of_contents {
162 uint32_t symbol_index;
163 uint32_t module_index;
164 } _packed;
165
166 struct 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
182 struct dylib_reference {
183 uint32_t isym:24;
184 uint32_t flags:8;
185 } _packed;
186
187 struct 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
196 struct 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
208 struct 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
222 struct 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
236 struct 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
250 struct 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
264 struct linkedit_data_command {
265 uint32_t cmd;
266 uint32_t cmdsize;
267 uint32_t dataoff;
268 uint32_t datasize;
269 } _packed;
270
271 struct 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
279 uint16_t Swap_(uint16_t value) {
280 return
281 ((value >> 8) & 0x00ff) |
282 ((value << 8) & 0xff00);
283 }
284
285 uint32_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
293 int16_t Swap_(int16_t value) {
294 return Swap_(static_cast<uint16_t>(value));
295 }
296
297 int32_t Swap_(int32_t value) {
298 return Swap_(static_cast<uint32_t>(value));
299 }
300
301 bool little_(true);
302
303 uint16_t Swap(uint16_t value) {
304 return little_ ? Swap_(value) : value;
305 }
306
307 uint32_t Swap(uint32_t value) {
308 return little_ ? Swap_(value) : value;
309 }
310
311 int16_t Swap(int16_t value) {
312 return Swap(static_cast<uint16_t>(value));
313 }
314
315 int32_t Swap(int32_t value) {
316 return Swap(static_cast<uint32_t>(value));
317 }
318
319 template <typename Target_>
320 class Pointer;
321
322 class 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
363 class 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
513 class 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
531 class 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
576 FatHeader 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
582 template <typename Target_>
583 class 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
622 struct BlobIndex {
623 uint32_t type;
624 uint32_t offset;
625 } _packed;
626
627 struct Blob {
628 uint32_t magic;
629 uint32_t length;
630 } _packed;
631
632 struct SuperBlob {
633 struct Blob blob;
634 uint32_t count;
635 struct BlobIndex index[];
636 } _packed;
637
638 struct 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
654 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
655
656 void 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
663 struct 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
676 int 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 if (flag_A) {
823 if (mach_header.GetCPUType() != flag_CPUType)
824 continue;
825 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
826 continue;
827 }
828
829 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
830
831 uint32_t size(_not(uint32_t)); {
832 _foreach (load_command, mach_header.GetLoadCommands()) {
833 switch (mach_header.Swap(load_command->cmd)) {
834 case LC_CODE_SIGNATURE: {
835 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
836 memset(reinterpret_cast<uint8_t *>(mach_header.GetBase()) + mach_header.Swap(signature->dataoff), 0, mach_header.Swap(signature->datasize));
837 memset(signature, 0, sizeof(struct linkedit_data_command));
838
839 mach_header->ncmds = mach_header.Swap(mach_header.Swap(mach_header->ncmds) - 1);
840 mach_header->sizeofcmds = mach_header.Swap(uint32_t(mach_header.Swap(mach_header->sizeofcmds) - sizeof(struct linkedit_data_command)));
841 } break;
842
843 case LC_SYMTAB: {
844 struct symtab_command *symtab = reinterpret_cast<struct symtab_command *>(load_command);
845 size = mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize);
846 } break;
847 }
848 }
849 }
850
851 _assert(size != _not(uint32_t));
852
853 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments("__LINKEDIT")) {
854 segment->filesize -= mach_header.GetSize() - size;
855
856 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
857 fat_arch->size = fat_header.Swap(size);
858 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
859 } else
860 clip = std::max(clip, size);
861 }
862
863 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments64("__LINKEDIT")) {
864 segment->filesize -= mach_header.GetSize() - size;
865
866 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
867 fat_arch->size = fat_header.Swap(size);
868 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
869 } else
870 clip = std::max(clip, size);
871 }
872 }
873 }
874
875 if (clip != 0)
876 _syscall(truncate(path, clip));
877 }
878
879 if (flag_S) {
880 asprintf(&temp, "%s.%s.cs", dir, base);
881 const char *allocate = getenv("CODESIGN_ALLOCATE");
882 if (allocate == NULL)
883 allocate = "codesign_allocate";
884
885 std::vector<CodesignAllocation> allocations; {
886 FatHeader fat_header(Map(path));
887 _foreach (mach_header, fat_header.GetMachHeaders()) {
888 if (flag_A) {
889 if (mach_header.GetCPUType() != flag_CPUType)
890 continue;
891 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
892 continue;
893 }
894
895 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
896
897 size_t size(_not(size_t)); {
898 _foreach (load_command, mach_header.GetLoadCommands()) {
899 uint32_t cmd(mach_header.Swap(load_command->cmd));
900 if (cmd == LC_CODE_SIGNATURE) {
901 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
902 size = mach_header.Swap(signature->dataoff);
903 _assert(size < mach_header.GetSize());
904 break;
905 }
906 }
907
908 if (size == _not(size_t))
909 size = mach_header.GetSize();
910 }
911
912 allocations.push_back(CodesignAllocation(mach_header.GetCPUType(), mach_header.GetCPUSubtype(), size));
913 }
914 }
915
916 if (!allocations.empty()) {
917
918 pid_t pid = fork();
919 _syscall(pid);
920 if (pid == 0) {
921 // XXX: this leaks memory, but it doesn't really matter
922 std::vector<const char *> args;
923 char *arg;
924
925 args.push_back(allocate);
926
927 args.push_back("-i");
928 args.push_back(path);
929
930 _foreach (allocation, allocations) {
931 args.push_back("-A");
932
933 asprintf(&arg, "%u", allocation.type_);
934 args.push_back(arg);
935
936 asprintf(&arg, "%u", allocation.subtype_);
937 args.push_back(arg);
938
939 size_t alloc(0);
940 alloc += sizeof(struct SuperBlob);
941 uint32_t special(0);
942
943 special = std::max(special, CSSLOT_CODEDIRECTORY);
944 alloc += sizeof(struct BlobIndex);
945 alloc += sizeof(struct CodeDirectory);
946 alloc += strlen(base) + 1;
947
948 special = std::max(special, CSSLOT_REQUIREMENTS);
949 alloc += sizeof(struct BlobIndex);
950 alloc += 0xc;
951
952 if (xmld != NULL) {
953 special = std::max(special, CSSLOT_ENTITLEMENTS);
954 alloc += sizeof(struct BlobIndex);
955 alloc += sizeof(struct Blob);
956 alloc += xmls;
957 }
958
959 size_t normal((allocation.size_ + 0x1000 - 1) / 0x1000);
960 alloc += (special + normal) * 0x14;
961
962 alloc += 15;
963 alloc /= 16;
964 alloc *= 16;
965
966 asprintf(&arg, "%zu", alloc);
967 args.push_back(arg);
968 }
969
970 args.push_back("-o");
971 args.push_back(temp);
972
973 args.push_back(NULL);
974
975 if (false) {
976 printf("run:");
977 _foreach (arg, args)
978 printf(" %s", arg);
979 printf("\n");
980 }
981
982 execvp(allocate, (char **) &args[0]);
983 _assert(false);
984 }
985
986 int status;
987 _syscall(waitpid(pid, &status, 0));
988 _assert(WIFEXITED(status));
989 _assert(WEXITSTATUS(status) == 0);
990
991 }
992 }
993
994 if (flag_p)
995 printf("path%zu='%s'\n", filei, file.c_str());
996
997 FatHeader fat_header(Map(temp == NULL ? path : temp, !(flag_R | flag_T | flag_s | flag_S | flag_O | flag_D)));
998 struct linkedit_data_command *signature(NULL);
999
1000 _foreach (mach_header, fat_header.GetMachHeaders()) {
1001 if (flag_A) {
1002 if (mach_header.GetCPUType() != flag_CPUType)
1003 continue;
1004 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1005 continue;
1006 }
1007
1008 if (flag_a)
1009 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1010
1011 if (flag_d) {
1012 if (struct fat_arch *fat_arch = mach_header.GetFatArch())
1013 printf("offset=0x%x\n", Swap(fat_arch->offset));
1014 else
1015 printf("offset=0x0\n");
1016 }
1017
1018 if (woffset != _not(uintptr_t)) {
1019 Pointer<uint32_t> wvalue(mach_header.GetPointer<uint32_t>(woffset));
1020 if (wvalue == NULL)
1021 printf("(null) %p\n", reinterpret_cast<void *>(woffset));
1022 else
1023 printf("0x%.08x\n", *wvalue);
1024 }
1025
1026 if (noffset != _not(uintptr_t))
1027 printf("%s\n", &*mach_header.GetPointer<char>(noffset));
1028
1029 if (flag_d)
1030 _foreach(segment, mach_header.GetSegments("__TEXT")) {
1031 printf("vmaddr=0x%x\n", mach_header.Swap(segment->vmaddr));
1032 printf("fileoff=0x%x\n", mach_header.Swap(segment->fileoff));
1033 }
1034
1035 if (flag_O) {
1036 _foreach(section, mach_header.GetSections("__TEXT", "__text"))
1037 section->addr = mach_header.Swap(0);
1038 }
1039
1040 _foreach (load_command, mach_header.GetLoadCommands()) {
1041 uint32_t cmd(mach_header.Swap(load_command->cmd));
1042
1043 if (flag_R && cmd == LC_REEXPORT_DYLIB)
1044 load_command->cmd = mach_header.Swap(LC_LOAD_DYLIB);
1045 else if (cmd == LC_CODE_SIGNATURE)
1046 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1047 else if (cmd == LC_UUID) {
1048 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(load_command));
1049
1050 if (flag_u) {
1051 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
1052 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
1053 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
1054 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
1055 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
1056 );
1057 }
1058 } else if (cmd == LC_ID_DYLIB) {
1059 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
1060
1061 if (flag_t)
1062 printf("time%zu=0x%.8x\n", filei, mach_header.Swap(dylib_command->dylib.timestamp));
1063
1064 if (flag_T) {
1065 uint32_t timed;
1066
1067 if (!timeh)
1068 timed = timev;
1069 else {
1070 dylib_command->dylib.timestamp = 0;
1071 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1072 }
1073
1074 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1075 }
1076 } else if (cmd == LC_ENCRYPTION_INFO) {
1077 volatile struct encryption_info_command *encryption_info_command(reinterpret_cast<struct encryption_info_command *>(load_command));
1078
1079 if (flag_D)
1080 encryption_info_command->cryptid = mach_header.Swap(0);
1081
1082 if (flag_d) {
1083 printf("cryptoff=0x%x\n", mach_header.Swap(encryption_info_command->cryptoff));
1084 printf("cryptsize=0x%x\n", mach_header.Swap(encryption_info_command->cryptsize));
1085 printf("cryptid=0x%x\n", mach_header.Swap(encryption_info_command->cryptid));
1086 }
1087 }
1088 }
1089
1090 if (flag_e) {
1091 _assert(signature != NULL);
1092
1093 uint32_t data = mach_header.Swap(signature->dataoff);
1094
1095 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1096 uint8_t *blob = top + data;
1097 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1098
1099 for (size_t index(0); index != Swap(super->count); ++index)
1100 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1101 uint32_t begin = Swap(super->index[index].offset);
1102 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1103 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
1104 }
1105 }
1106
1107 if (flag_s) {
1108 _assert(signature != NULL);
1109
1110 uint32_t data = mach_header.Swap(signature->dataoff);
1111
1112 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1113 uint8_t *blob = top + data;
1114 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1115
1116 for (size_t index(0); index != Swap(super->count); ++index)
1117 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1118 uint32_t begin = Swap(super->index[index].offset);
1119 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1120
1121 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + begin + Swap(directory->hashOffset));
1122 uint32_t pages = Swap(directory->nCodeSlots);
1123
1124 if (pages != 1)
1125 for (size_t i = 0; i != pages - 1; ++i)
1126 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1127 if (pages != 0)
1128 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1129 }
1130 }
1131
1132 if (flag_S) {
1133 _assert(signature != NULL);
1134
1135 uint32_t data = mach_header.Swap(signature->dataoff);
1136 uint32_t size = mach_header.Swap(signature->datasize);
1137
1138 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1139 uint8_t *blob = top + data;
1140 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1141 super->blob.magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
1142
1143 uint32_t count = xmld == NULL ? 2 : 3;
1144 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
1145
1146 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
1147 super->index[0].offset = Swap(offset);
1148
1149 uint32_t begin = offset;
1150 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1151 offset += sizeof(struct CodeDirectory);
1152
1153 directory->blob.magic = Swap(CSMAGIC_CODEDIRECTORY);
1154 directory->version = Swap(uint32_t(0x00020001));
1155 directory->flags = Swap(uint32_t(0));
1156 directory->codeLimit = Swap(data);
1157 directory->hashSize = 0x14;
1158 directory->hashType = 0x01;
1159 directory->spare1 = 0x00;
1160 directory->pageSize = 0x0c;
1161 directory->spare2 = Swap(uint32_t(0));
1162
1163 directory->identOffset = Swap(offset - begin);
1164 strcpy(reinterpret_cast<char *>(blob + offset), base);
1165 offset += strlen(base) + 1;
1166
1167 uint32_t special = xmld == NULL ? CSSLOT_REQUIREMENTS : CSSLOT_ENTITLEMENTS;
1168 directory->nSpecialSlots = Swap(special);
1169
1170 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
1171 memset(hashes, 0, sizeof(*hashes) * special);
1172
1173 offset += sizeof(*hashes) * special;
1174 hashes += special;
1175
1176 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
1177 directory->nCodeSlots = Swap(pages);
1178
1179 if (pages != 1)
1180 for (size_t i = 0; i != pages - 1; ++i)
1181 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1182 if (pages != 0)
1183 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1184
1185 directory->hashOffset = Swap(offset - begin);
1186 offset += sizeof(*hashes) * pages;
1187 directory->blob.length = Swap(offset - begin);
1188
1189 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
1190 super->index[1].offset = Swap(offset);
1191
1192 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
1193 offset += 0xc;
1194
1195 if (xmld != NULL) {
1196 super->index[2].type = Swap(CSSLOT_ENTITLEMENTS);
1197 super->index[2].offset = Swap(offset);
1198
1199 uint32_t begin = offset;
1200 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1201 offset += sizeof(struct Blob);
1202
1203 memcpy(blob + offset, xmld, xmls);
1204 offset += xmls;
1205
1206 entitlements->magic = Swap(CSMAGIC_ENTITLEMENTS);
1207 entitlements->length = Swap(offset - begin);
1208 }
1209
1210 for (size_t index(0); index != count; ++index) {
1211 uint32_t type = Swap(super->index[index].type);
1212 if (type != 0 && type <= special) {
1213 uint32_t offset = Swap(super->index[index].offset);
1214 struct Blob *local = (struct Blob *) (blob + offset);
1215 sha1((uint8_t *) (hashes - type), (uint8_t *) local, Swap(local->length));
1216 }
1217 }
1218
1219 super->count = Swap(count);
1220 super->blob.length = Swap(offset);
1221
1222 if (offset > size) {
1223 fprintf(stderr, "offset (%u) > size (%u)\n", offset, size);
1224 _assert(false);
1225 } //else fprintf(stderr, "offset (%zu) <= size (%zu)\n", offset, size);
1226
1227 memset(blob + offset, 0, size - offset);
1228 }
1229 }
1230
1231 if (flag_S) {
1232 uint8_t *top = reinterpret_cast<uint8_t *>(fat_header.GetBase());
1233 size_t size = fat_header.GetSize();
1234
1235 char *copy;
1236 asprintf(&copy, "%s.%s.cp", dir, base);
1237 FILE *file = fopen(copy, "w+");
1238 size_t writ = fwrite(top, 1, size, file);
1239 _assert(writ == size);
1240 fclose(file);
1241
1242 _syscall(unlink(temp));
1243 free(temp);
1244 temp = copy;
1245 }
1246
1247 if (temp != NULL) {
1248 struct stat info;
1249 _syscall(stat(path, &info));
1250 _syscall(chown(temp, info.st_uid, info.st_gid));
1251 _syscall(chmod(temp, info.st_mode));
1252 _syscall(unlink(path));
1253 _syscall(rename(temp, path));
1254 free(temp);
1255 }
1256
1257 free(dir);
1258 ++filei;
1259 } catch (const char *) {
1260 ++filee;
1261 ++filei;
1262 }
1263
1264 return filee;
1265 }