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