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