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