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