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