]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Generally prefer data.empty() to data.size() == 0.
[ldid.git] / ldid.cpp
CommitLineData
ab113d22 1/* ldid - (Mach-O) Link-Loader Identity Editor
16efdde5 2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
a362a82f
JF
3*/
4
dd6c06ed
JF
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
e0524446
JF
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
dd6c06ed 11
e0524446
JF
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
dd6c06ed
JF
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
e0524446
JF
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19**/
20/* }}} */
a362a82f 21
fa59c178
JF
22#include <cstdio>
23#include <cstdlib>
a362a82f 24#include <cstring>
4d4682ef
JF
25#include <fstream>
26#include <map>
27#include <sstream>
a362a82f
JF
28#include <string>
29#include <vector>
30
fa59c178 31#include <errno.h>
dede6121 32#include <fcntl.h>
fa59c178
JF
33#include <stdbool.h>
34#include <stdint.h>
a7f01a65 35#include <unistd.h>
dede6121
JF
36
37#include <sys/mman.h>
38#include <sys/stat.h>
39
a50bb1be
JF
40#include <openssl/sha.h>
41
15babeef
JF
42#include <plist/plist.h>
43
fa59c178
JF
44#define _assert___(line) \
45 #line
46#define _assert__(line) \
47 _assert___(line)
48#define _assert_(e) \
49 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" e ")"
50
51#define _assert(expr) \
52 do if (!(expr)) { \
53 fprintf(stderr, "%s(%u): _assert(%s); errno=%u\n", __FILE__, __LINE__, #expr, errno); \
54 _assert_(#expr); \
55 } while (false)
56
57#define _syscall(expr) ({ \
58 __typeof__(expr) _value; \
59 do if ((long) (_value = (expr)) != -1) \
60 break; \
61 else switch (errno) { \
62 case EINTR: \
63 continue; \
64 default: \
65 _assert(false); \
66 } while (true); \
67 _value; \
68})
69
70#define _trace() \
71 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
72
73#define _not(type) \
74 ((type) ~ (type) 0)
75
76#define _packed \
77 __attribute__((packed))
78
79template <typename Type_>
80struct Iterator_ {
81 typedef typename Type_::const_iterator Result;
82};
83
84#define _foreach(item, list) \
85 for (bool _stop(true); _stop; ) \
86 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
87 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
88 for (bool _suck(true); _suck; _suck = false) \
89 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
90
a362a82f
JF
91struct fat_header {
92 uint32_t magic;
93 uint32_t nfat_arch;
c05d9758 94} _packed;
a362a82f
JF
95
96#define FAT_MAGIC 0xcafebabe
97#define FAT_CIGAM 0xbebafeca
98
99struct fat_arch {
100 uint32_t cputype;
101 uint32_t cpusubtype;
102 uint32_t offset;
103 uint32_t size;
104 uint32_t align;
c05d9758 105} _packed;
a362a82f
JF
106
107struct mach_header {
108 uint32_t magic;
109 uint32_t cputype;
04802ab1 110 uint32_t cpusubtype;
a362a82f
JF
111 uint32_t filetype;
112 uint32_t ncmds;
113 uint32_t sizeofcmds;
114 uint32_t flags;
c05d9758 115} _packed;
a362a82f 116
fdb119ef 117#define MH_MAGIC 0xfeedface
a362a82f
JF
118#define MH_CIGAM 0xcefaedfe
119
3cbc6463
JF
120#define MH_MAGIC_64 0xfeedfacf
121#define MH_CIGAM_64 0xcffaedfe
122
82813bde
JF
123#define MH_DYLDLINK 0x4
124
4a864785 125#define MH_OBJECT 0x1
efd6cd4a
JF
126#define MH_EXECUTE 0x2
127#define MH_DYLIB 0x6
128#define MH_BUNDLE 0x8
129#define MH_DYLIB_STUB 0x9
a362a82f
JF
130
131struct load_command {
132 uint32_t cmd;
133 uint32_t cmdsize;
c05d9758 134} _packed;
a362a82f 135
4a57e66c
JF
136#define LC_REQ_DYLD uint32_t(0x80000000)
137
138#define LC_SEGMENT uint32_t(0x01)
139#define LC_SYMTAB uint32_t(0x02)
140#define LC_DYSYMTAB uint32_t(0x0b)
141#define LC_LOAD_DYLIB uint32_t(0x0c)
142#define LC_ID_DYLIB uint32_t(0x0d)
289ccbbc 143#define LC_SEGMENT_64 uint32_t(0x19)
4a57e66c
JF
144#define LC_UUID uint32_t(0x1b)
145#define LC_CODE_SIGNATURE uint32_t(0x1d)
146#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
147#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
c0cc1574 148#define LC_ENCRYPTION_INFO uint32_t(0x21)
4a57e66c
JF
149#define LC_DYLD_INFO uint32_t(0x22)
150#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
843aea8c 151#define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
a362a82f
JF
152
153struct dylib {
154 uint32_t name;
155 uint32_t timestamp;
156 uint32_t current_version;
157 uint32_t compatibility_version;
c05d9758 158} _packed;
a362a82f
JF
159
160struct dylib_command {
161 uint32_t cmd;
162 uint32_t cmdsize;
163 struct dylib dylib;
c05d9758 164} _packed;
a362a82f
JF
165
166struct uuid_command {
167 uint32_t cmd;
168 uint32_t cmdsize;
169 uint8_t uuid[16];
c05d9758 170} _packed;
a362a82f 171
20e7eb29
JF
172struct symtab_command {
173 uint32_t cmd;
174 uint32_t cmdsize;
175 uint32_t symoff;
176 uint32_t nsyms;
177 uint32_t stroff;
178 uint32_t strsize;
179} _packed;
180
4a57e66c
JF
181struct dyld_info_command {
182 uint32_t cmd;
183 uint32_t cmdsize;
184 uint32_t rebase_off;
185 uint32_t rebase_size;
186 uint32_t bind_off;
187 uint32_t bind_size;
188 uint32_t weak_bind_off;
189 uint32_t weak_bind_size;
190 uint32_t lazy_bind_off;
191 uint32_t lazy_bind_size;
192 uint32_t export_off;
193 uint32_t export_size;
194} _packed;
195
196struct dysymtab_command {
197 uint32_t cmd;
198 uint32_t cmdsize;
199 uint32_t ilocalsym;
200 uint32_t nlocalsym;
201 uint32_t iextdefsym;
202 uint32_t nextdefsym;
203 uint32_t iundefsym;
204 uint32_t nundefsym;
205 uint32_t tocoff;
206 uint32_t ntoc;
207 uint32_t modtaboff;
208 uint32_t nmodtab;
209 uint32_t extrefsymoff;
210 uint32_t nextrefsyms;
211 uint32_t indirectsymoff;
212 uint32_t nindirectsyms;
213 uint32_t extreloff;
214 uint32_t nextrel;
215 uint32_t locreloff;
216 uint32_t nlocrel;
217} _packed;
218
219struct dylib_table_of_contents {
220 uint32_t symbol_index;
221 uint32_t module_index;
222} _packed;
223
224struct dylib_module {
225 uint32_t module_name;
226 uint32_t iextdefsym;
227 uint32_t nextdefsym;
228 uint32_t irefsym;
229 uint32_t nrefsym;
230 uint32_t ilocalsym;
231 uint32_t nlocalsym;
232 uint32_t iextrel;
233 uint32_t nextrel;
234 uint32_t iinit_iterm;
235 uint32_t ninit_nterm;
236 uint32_t objc_module_info_addr;
237 uint32_t objc_module_info_size;
238} _packed;
239
240struct dylib_reference {
241 uint32_t isym:24;
242 uint32_t flags:8;
243} _packed;
244
245struct relocation_info {
246 int32_t r_address;
247 uint32_t r_symbolnum:24;
248 uint32_t r_pcrel:1;
249 uint32_t r_length:2;
250 uint32_t r_extern:1;
251 uint32_t r_type:4;
252} _packed;
253
254struct nlist {
255 union {
256 char *n_name;
257 int32_t n_strx;
258 } n_un;
259
260 uint8_t n_type;
261 uint8_t n_sect;
262 uint8_t n_desc;
263 uint32_t n_value;
264} _packed;
265
6e83315b
JF
266struct segment_command {
267 uint32_t cmd;
268 uint32_t cmdsize;
269 char segname[16];
270 uint32_t vmaddr;
271 uint32_t vmsize;
272 uint32_t fileoff;
273 uint32_t filesize;
274 uint32_t maxprot;
275 uint32_t initprot;
276 uint32_t nsects;
277 uint32_t flags;
429e34a5 278} _packed;
6e83315b 279
289ccbbc
JF
280struct segment_command_64 {
281 uint32_t cmd;
282 uint32_t cmdsize;
283 char segname[16];
284 uint64_t vmaddr;
285 uint64_t vmsize;
286 uint64_t fileoff;
287 uint64_t filesize;
288 uint32_t maxprot;
289 uint32_t initprot;
290 uint32_t nsects;
291 uint32_t flags;
429e34a5 292} _packed;
289ccbbc 293
6e83315b
JF
294struct section {
295 char sectname[16];
296 char segname[16];
297 uint32_t addr;
298 uint32_t size;
299 uint32_t offset;
300 uint32_t align;
301 uint32_t reloff;
302 uint32_t nreloc;
303 uint32_t flags;
304 uint32_t reserved1;
305 uint32_t reserved2;
429e34a5 306} _packed;
6e83315b 307
289ccbbc
JF
308struct section_64 {
309 char sectname[16];
310 char segname[16];
311 uint64_t addr;
312 uint64_t size;
313 uint32_t offset;
314 uint32_t align;
315 uint32_t reloff;
316 uint32_t nreloc;
317 uint32_t flags;
318 uint32_t reserved1;
319 uint32_t reserved2;
429e34a5 320} _packed;
289ccbbc 321
fdb119ef
JF
322struct linkedit_data_command {
323 uint32_t cmd;
324 uint32_t cmdsize;
325 uint32_t dataoff;
326 uint32_t datasize;
c05d9758 327} _packed;
fdb119ef 328
c0cc1574
JF
329struct encryption_info_command {
330 uint32_t cmd;
331 uint32_t cmdsize;
332 uint32_t cryptoff;
333 uint32_t cryptsize;
334 uint32_t cryptid;
335} _packed;
336
4a864785
JF
337#define BIND_OPCODE_MASK 0xf0
338#define BIND_IMMEDIATE_MASK 0x0f
339#define BIND_OPCODE_DONE 0x00
340#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
341#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
342#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
343#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
344#define BIND_OPCODE_SET_TYPE_IMM 0x50
345#define BIND_OPCODE_SET_ADDEND_SLEB 0x60
346#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
347#define BIND_OPCODE_ADD_ADDR_ULEB 0x80
348#define BIND_OPCODE_DO_BIND 0x90
349#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
350#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
351#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
352
4d4682ef
JF
353inline void get(std::streambuf &stream, void *data, size_t size) {
354 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
355}
356
357inline void put(std::streambuf &stream, const void *data, size_t size) {
358 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
359}
360
361inline void pad(std::streambuf &stream, size_t size) {
362 char padding[size];
363 memset(padding, 0, size);
364 put(stream, padding, size);
365}
366
4374152f
JF
367template <typename Type_>
368Type_ Align(Type_ value, size_t align) {
369 value += align - 1;
370 value /= align;
371 value *= align;
372 return value;
373}
374
fdb119ef
JF
375uint16_t Swap_(uint16_t value) {
376 return
377 ((value >> 8) & 0x00ff) |
378 ((value << 8) & 0xff00);
379}
380
381uint32_t Swap_(uint32_t value) {
382 value = ((value >> 8) & 0x00ff00ff) |
383 ((value << 8) & 0xff00ff00);
384 value = ((value >> 16) & 0x0000ffff) |
385 ((value << 16) & 0xffff0000);
386 return value;
387}
388
4374152f
JF
389uint64_t Swap_(uint64_t value) {
390 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
391 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
392 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
393 return value;
394}
395
fdb119ef
JF
396int16_t Swap_(int16_t value) {
397 return Swap_(static_cast<uint16_t>(value));
398}
399
400int32_t Swap_(int32_t value) {
401 return Swap_(static_cast<uint32_t>(value));
402}
403
4374152f
JF
404int64_t Swap_(int64_t value) {
405 return Swap_(static_cast<uint64_t>(value));
406}
407
5525a5a7
JF
408bool little_(true);
409
fdb119ef 410uint16_t Swap(uint16_t value) {
5525a5a7 411 return little_ ? Swap_(value) : value;
fdb119ef
JF
412}
413
414uint32_t Swap(uint32_t value) {
5525a5a7 415 return little_ ? Swap_(value) : value;
fdb119ef
JF
416}
417
4374152f
JF
418uint64_t Swap(uint64_t value) {
419 return little_ ? Swap_(value) : value;
420}
421
fdb119ef
JF
422int16_t Swap(int16_t value) {
423 return Swap(static_cast<uint16_t>(value));
424}
425
426int32_t Swap(int32_t value) {
427 return Swap(static_cast<uint32_t>(value));
428}
429
4374152f
JF
430int64_t Swap(int64_t value) {
431 return Swap(static_cast<uint64_t>(value));
432}
433
6e83315b
JF
434template <typename Target_>
435class Pointer;
436
4d4682ef 437class Swapped {
0a033524 438 protected:
a362a82f
JF
439 bool swapped_;
440
4d4682ef 441 Swapped() :
0a033524
JF
442 swapped_(false)
443 {
444 }
445
4d4682ef
JF
446 public:
447 Swapped(bool swapped) :
448 swapped_(swapped)
449 {
a362a82f
JF
450 }
451
4d4682ef
JF
452 template <typename Type_>
453 Type_ Swap(Type_ value) const {
4374152f
JF
454 return swapped_ ? Swap_(value) : value;
455 }
4d4682ef 456};
4374152f 457
4d4682ef
JF
458class Data :
459 public Swapped
460{
461 private:
462 void *base_;
463 size_t size_;
a362a82f 464
4d4682ef
JF
465 public:
466 Data(void *base, size_t size) :
467 base_(base),
468 size_(size)
469 {
4374152f
JF
470 }
471
0a033524
JF
472 void *GetBase() const {
473 return base_;
474 }
a362a82f 475
0a033524
JF
476 size_t GetSize() const {
477 return size_;
478 }
479};
a362a82f 480
0a033524
JF
481class MachHeader :
482 public Data
483{
484 private:
485 bool bits64_;
486
487 struct mach_header *mach_header_;
488 struct load_command *load_command_;
489
490 public:
491 MachHeader(void *base, size_t size) :
492 Data(base, size)
493 {
494 mach_header_ = (mach_header *) base;
a362a82f 495
3cbc6463
JF
496 switch (Swap(mach_header_->magic)) {
497 case MH_CIGAM:
498 swapped_ = !swapped_;
499 case MH_MAGIC:
500 bits64_ = false;
501 break;
502
503 case MH_CIGAM_64:
504 swapped_ = !swapped_;
505 case MH_MAGIC_64:
506 bits64_ = true;
507 break;
508
509 default:
510 _assert(false);
511 }
512
513 void *post = mach_header_ + 1;
514 if (bits64_)
515 post = (uint32_t *) post + 1;
516 load_command_ = (struct load_command *) post;
a362a82f
JF
517
518 _assert(
519 Swap(mach_header_->filetype) == MH_EXECUTE ||
520 Swap(mach_header_->filetype) == MH_DYLIB ||
521 Swap(mach_header_->filetype) == MH_BUNDLE
522 );
523 }
524
4d4682ef
JF
525 bool Bits64() const {
526 return bits64_;
527 }
528
afbb7c8e
JF
529 struct mach_header *operator ->() const {
530 return mach_header_;
531 }
532
4374152f
JF
533 operator struct mach_header *() const {
534 return mach_header_;
535 }
536
04802ab1
JF
537 uint32_t GetCPUType() const {
538 return Swap(mach_header_->cputype);
539 }
540
4374152f 541 uint32_t GetCPUSubtype() const {
04802ab1
JF
542 return Swap(mach_header_->cpusubtype) & 0xff;
543 }
544
4374152f
JF
545 struct load_command *GetLoadCommand() const {
546 return load_command_;
547 }
548
0a033524 549 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
550 std::vector<struct load_command *> load_commands;
551
3cbc6463 552 struct load_command *load_command = load_command_;
a362a82f
JF
553 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
554 load_commands.push_back(load_command);
555 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
556 }
557
558 return load_commands;
559 }
6e83315b 560
6f340f51 561 std::vector<segment_command *> GetSegments(const char *segment_name) const {
6e83315b
JF
562 std::vector<struct segment_command *> segment_commands;
563
289ccbbc 564 _foreach (load_command, GetLoadCommands()) {
0a033524
JF
565 if (Swap(load_command->cmd) == LC_SEGMENT) {
566 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
567 if (strncmp(segment_command->segname, segment_name, 16) == 0)
568 segment_commands.push_back(segment_command);
569 }
289ccbbc
JF
570 }
571
572 return segment_commands;
573 }
574
4374152f 575 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
289ccbbc
JF
576 std::vector<struct segment_command_64 *> segment_commands;
577
578 _foreach (load_command, GetLoadCommands()) {
579 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
580 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
581 if (strncmp(segment_command->segname, segment_name, 16) == 0)
582 segment_commands.push_back(segment_command);
583 }
584 }
6e83315b
JF
585
586 return segment_commands;
587 }
588
6f340f51 589 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
6e83315b
JF
590 std::vector<section *> sections;
591
592 _foreach (segment, GetSegments(segment_name)) {
0a033524 593 section *section = (struct section *) (segment + 1);
6e83315b
JF
594
595 uint32_t sect;
0a033524 596 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
597 if (strncmp(section->sectname, section_name, 16) == 0)
598 sections.push_back(section);
599 ++section;
600 }
601 }
602
603 return sections;
604 }
605
606 template <typename Target_>
0a033524 607 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
608 load_command *load_command = (struct load_command *) (mach_header_ + 1);
609 uint32_t cmd;
610
611 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
612 if (Swap(load_command->cmd) == LC_SEGMENT) {
613 segment_command *segment_command = (struct segment_command *) load_command;
614 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
615 goto next_command;
616
617 section *sections = (struct section *) (segment_command + 1);
618
619 uint32_t sect;
620 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
621 section *section = &sections[sect];
622 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
623 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
624 //printf("0x%.8x %s\n", address, segment_command->segname);
625 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
626 }
627 }
628 }
629
630 next_command:
631 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
632 }
633
634 return Pointer<Target_>(this);
635 }
636
637 template <typename Target_>
638 Pointer<Target_> GetOffset(uint32_t offset) {
639 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
640 }
641};
642
289ccbbc
JF
643class FatMachHeader :
644 public MachHeader
645{
646 private:
647 fat_arch *fat_arch_;
648
649 public:
650 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
651 MachHeader(base, size),
652 fat_arch_(fat_arch)
653 {
654 }
655
656 fat_arch *GetFatArch() const {
657 return fat_arch_;
658 }
659};
660
0a033524
JF
661class FatHeader :
662 public Data
663{
664 private:
665 fat_header *fat_header_;
289ccbbc 666 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
667
668 public:
669 FatHeader(void *base, size_t size) :
670 Data(base, size)
671 {
672 fat_header_ = reinterpret_cast<struct fat_header *>(base);
673
674 if (Swap(fat_header_->magic) == FAT_CIGAM) {
675 swapped_ = !swapped_;
676 goto fat;
677 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
678 fat_header_ = NULL;
289ccbbc 679 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
680 } else fat: {
681 size_t fat_narch = Swap(fat_header_->nfat_arch);
682 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
683 size_t arch;
684 for (arch = 0; arch != fat_narch; ++arch) {
685 uint32_t arch_offset = Swap(fat_arch->offset);
686 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 687 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
688 ++fat_arch;
689 }
690 }
691 }
692
289ccbbc 693 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
694 return mach_headers_;
695 }
20e7eb29
JF
696
697 bool IsFat() const {
698 return fat_header_ != NULL;
699 }
6b38c173
JF
700
701 struct fat_header *operator ->() const {
702 return fat_header_;
703 }
4374152f
JF
704
705 operator struct fat_header *() const {
706 return fat_header_;
707 }
0a033524
JF
708};
709
6e83315b
JF
710template <typename Target_>
711class Pointer {
712 private:
0a033524 713 const MachHeader *framework_;
6e83315b
JF
714 const Target_ *pointer_;
715
716 public:
0a033524 717 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
718 framework_(framework),
719 pointer_(pointer)
720 {
721 }
722
723 operator const Target_ *() const {
724 return pointer_;
725 }
726
727 const Target_ *operator ->() const {
728 return pointer_;
729 }
730
731 Pointer<Target_> &operator ++() {
732 ++pointer_;
733 return *this;
734 }
735
736 template <typename Value_>
737 Value_ Swap(Value_ value) {
738 return framework_->Swap(value);
739 }
a362a82f
JF
740};
741
4d4682ef
JF
742#define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
743#define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
744#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
745#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
746#define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
747#define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
748#define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
749#define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
c05d9758 750
4d4682ef
JF
751#define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
752#define CSSLOT_INFOSLOT uint32_t(0x00001)
753#define CSSLOT_REQUIREMENTS uint32_t(0x00002)
754#define CSSLOT_RESOURCEDIR uint32_t(0x00003)
755#define CSSLOT_APPLICATION uint32_t(0x00004)
756#define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
757
758#define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
759
760#define CS_HASHTYPE_SHA1 1
fdb119ef
JF
761
762struct BlobIndex {
763 uint32_t type;
764 uint32_t offset;
c05d9758 765} _packed;
fdb119ef 766
c05d9758 767struct Blob {
fdb119ef
JF
768 uint32_t magic;
769 uint32_t length;
c05d9758
JF
770} _packed;
771
772struct SuperBlob {
773 struct Blob blob;
fdb119ef
JF
774 uint32_t count;
775 struct BlobIndex index[];
c05d9758 776} _packed;
fdb119ef
JF
777
778struct CodeDirectory {
fdb119ef
JF
779 uint32_t version;
780 uint32_t flags;
781 uint32_t hashOffset;
782 uint32_t identOffset;
783 uint32_t nSpecialSlots;
784 uint32_t nCodeSlots;
785 uint32_t codeLimit;
786 uint8_t hashSize;
787 uint8_t hashType;
788 uint8_t spare1;
789 uint8_t pageSize;
790 uint32_t spare2;
c05d9758 791} _packed;
fdb119ef 792
a362a82f
JF
793extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
794
4d4682ef
JF
795void sha1(uint8_t *hash, const void *data, size_t size) {
796 SHA1(static_cast<const uint8_t *>(data), size, hash);
fdb119ef
JF
797}
798
0a033524 799struct CodesignAllocation {
4374152f
JF
800 FatMachHeader mach_header_;
801 uint32_t offset_;
802 uint32_t size_;
4d4682ef 803 uint32_t limit_;
4374152f 804 uint32_t alloc_;
e4b7adc1 805 uint32_t align_;
4374152f 806
e0098838 807 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
4374152f
JF
808 mach_header_(mach_header),
809 offset_(offset),
810 size_(size),
4d4682ef 811 limit_(limit),
e4b7adc1
JF
812 alloc_(alloc),
813 align_(align)
0a033524
JF
814 {
815 }
816};
817
dede6121
JF
818class File {
819 private:
820 int file_;
821
822 public:
823 File() :
824 file_(-1)
825 {
826 }
827
828 ~File() {
829 if (file_ != -1)
830 _syscall(close(file_));
831 }
832
cad40c43 833 void open(const char *path, int flags) {
dede6121 834 _assert(file_ == -1);
cad40c43 835 _syscall(file_ = ::open(path, flags));
dede6121
JF
836 }
837
838 int file() const {
839 return file_;
840 }
841};
842
843class Map {
844 private:
845 File file_;
846 void *data_;
847 size_t size_;
848
849 void clear() {
850 if (data_ == NULL)
851 return;
852 _syscall(munmap(data_, size_));
853 data_ = NULL;
854 size_ = 0;
855 }
856
857 public:
858 Map() :
859 data_(NULL),
860 size_(0)
861 {
862 }
863
cad40c43
JF
864 Map(const char *path, int oflag, int pflag, int mflag) :
865 Map()
866 {
867 open(path, oflag, pflag, mflag);
868 }
869
870 Map(const char *path, bool edit) :
871 Map()
872 {
873 open(path, edit);
dede6121
JF
874 }
875
876 ~Map() {
877 clear();
878 }
879
cad40c43 880 void open(const char *path, int oflag, int pflag, int mflag) {
dede6121
JF
881 clear();
882
cad40c43 883 file_.open(path, oflag);
dede6121
JF
884 int file(file_.file());
885
886 struct stat stat;
887 _syscall(fstat(file, &stat));
888 size_ = stat.st_size;
889
cad40c43
JF
890 _syscall(data_ = mmap(NULL, size_, pflag, mflag, file, 0));
891 }
892
893 void open(const char *path, bool edit) {
894 if (edit)
895 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
896 else
897 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
898 }
899
900 void *data() const {
901 return data_;
902 }
903
904 size_t size() const {
905 return size_;
906 }
f4b2df35
JF
907
908 operator std::string() const {
909 return std::string(static_cast<char *>(data_), size_);
910 }
dede6121
JF
911};
912
e0098838 913// I wish Apple cared about providing quality toolchains :/
4d4682ef 914
e0098838
JF
915template <typename Function_>
916class Functor;
917
918template <typename Type_, typename... Args_>
919class Functor<Type_ (Args_...)> {
920 public:
921 virtual Type_ operator ()(Args_... args) const = 0;
e0098838
JF
922};
923
924template <typename Function_>
925class FunctorImpl;
926
927template <typename Value_, typename Type_, typename... Args_>
928class FunctorImpl<Type_ (Value_::*)(Args_...) const> :
929 public Functor<Type_ (Args_...)>
930{
931 private:
932 const Value_ *value_;
933
934 public:
935 FunctorImpl() :
936 value_(NULL)
937 {
938 }
939
940 FunctorImpl(const Value_ &value) :
941 value_(&value)
942 {
943 }
944
945 virtual Type_ operator ()(Args_... args) const {
946 return (*value_)(args...);
947 }
948};
949
950template <typename Function_>
951FunctorImpl<decltype(&Function_::operator())> fun(const Function_ &value) {
952 return value;
953}
954
955void resign(void *idata, size_t isize, std::streambuf &output, const Functor<size_t (size_t)> &allocate, const Functor<size_t (std::streambuf &output, size_t, const std::string &, const char *)> &save) {
956 FatHeader source(idata, isize);
f4b2df35
JF
957
958 size_t offset(0);
959 if (source.IsFat())
960 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
961
962 std::vector<CodesignAllocation> allocations;
963 _foreach (mach_header, source.GetMachHeaders()) {
964 struct linkedit_data_command *signature(NULL);
965 struct symtab_command *symtab(NULL);
966
967 _foreach (load_command, mach_header.GetLoadCommands()) {
968 uint32_t cmd(mach_header.Swap(load_command->cmd));
969 if (false);
970 else if (cmd == LC_CODE_SIGNATURE)
971 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
972 else if (cmd == LC_SYMTAB)
973 symtab = reinterpret_cast<struct symtab_command *>(load_command);
974 }
975
976 size_t size;
977 if (signature == NULL)
978 size = mach_header.GetSize();
979 else {
980 size = mach_header.Swap(signature->dataoff);
981 _assert(size <= mach_header.GetSize());
982 }
983
984 if (symtab != NULL) {
985 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
986 _assert(end <= size);
987 _assert(end >= size - 0x10);
988 size = end;
989 }
990
e0098838 991 size_t alloc(allocate(size));
f4b2df35
JF
992
993 auto *fat_arch(mach_header.GetFatArch());
994 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
995 offset = Align(offset, 1 << align);
996
4d4682ef
JF
997 uint32_t limit(size);
998 if (alloc != 0)
999 limit = Align(limit, 0x10);
1000
e0098838 1001 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
f4b2df35
JF
1002 offset += size + alloc;
1003 offset = Align(offset, 16);
1004 }
1005
4d4682ef
JF
1006 size_t position(0);
1007
1008 if (source.IsFat()) {
1009 fat_header fat_header;
1010 fat_header.magic = Swap(FAT_MAGIC);
1011 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1012 put(output, &fat_header, sizeof(fat_header));
1013 position += sizeof(fat_header);
1014
1015 _foreach (allocation, allocations) {
1016 auto &mach_header(allocation.mach_header_);
1017
1018 fat_arch fat_arch;
1019 fat_arch.cputype = Swap(mach_header->cputype);
1020 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1021 fat_arch.offset = Swap(allocation.offset_);
1022 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1023 fat_arch.align = Swap(allocation.align_);
1024 put(output, &fat_arch, sizeof(fat_arch));
1025 position += sizeof(fat_arch);
1026 }
f4b2df35
JF
1027 }
1028
1029 _foreach (allocation, allocations) {
4d4682ef 1030 auto &mach_header(allocation.mach_header_);
f4b2df35 1031
4d4682ef
JF
1032 pad(output, allocation.offset_ - position);
1033 position = allocation.offset_;
f4b2df35 1034
4d4682ef 1035 std::vector<std::string> commands;
f4b2df35 1036
4d4682ef
JF
1037 _foreach (load_command, mach_header.GetLoadCommands()) {
1038 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1039
a7f01a65 1040 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1041 case LC_CODE_SIGNATURE:
1042 continue;
1043 break;
1044
1045 case LC_SEGMENT: {
1046 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1047 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1048 break;
1049 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1050 segment_command->filesize = size;
1051 segment_command->vmsize = Align(size, 0x1000);
1052 } break;
1053
1054 case LC_SEGMENT_64: {
1055 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1056 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1057 break;
1058 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1059 segment_command->filesize = size;
1060 segment_command->vmsize = Align(size, 0x1000);
1061 } break;
1062 }
f4b2df35 1063
4d4682ef 1064 commands.push_back(copy);
f4b2df35
JF
1065 }
1066
e0098838 1067 if (allocation.alloc_ != 0) {
4d4682ef
JF
1068 linkedit_data_command signature;
1069 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1070 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1071 signature.dataoff = mach_header.Swap(allocation.limit_);
1072 signature.datasize = mach_header.Swap(allocation.alloc_);
1073 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1074 }
f4b2df35 1075
4d4682ef 1076 size_t begin(position);
f4b2df35 1077
4d4682ef
JF
1078 uint32_t after(0);
1079 _foreach(command, commands)
1080 after += command.size();
f4b2df35 1081
4d4682ef 1082 std::stringbuf altern;
f4b2df35 1083
4d4682ef
JF
1084 struct mach_header header(*mach_header);
1085 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1086 header.sizeofcmds = mach_header.Swap(after);
1087 put(output, &header, sizeof(header));
1088 put(altern, &header, sizeof(header));
1089 position += sizeof(header);
f4b2df35 1090
4d4682ef
JF
1091 if (mach_header.Bits64()) {
1092 auto pad(mach_header.Swap(uint32_t(0)));
1093 put(output, &pad, sizeof(pad));
1094 put(altern, &pad, sizeof(pad));
1095 position += sizeof(pad);
1096 }
f4b2df35 1097
4d4682ef
JF
1098 _foreach(command, commands) {
1099 put(output, command.data(), command.size());
1100 put(altern, command.data(), command.size());
1101 position += command.size();
1102 }
f4b2df35 1103
4d4682ef
JF
1104 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1105 if (before > after) {
1106 pad(output, before - after);
1107 pad(altern, before - after);
1108 position += before - after;
1109 }
f4b2df35 1110
4d4682ef 1111 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1112
4d4682ef
JF
1113 std::string overlap(altern.str());
1114 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1115
4d4682ef
JF
1116 put(output, top + (position - begin), allocation.size_ - (position - begin));
1117 position = begin + allocation.size_;
f4b2df35 1118
4d4682ef
JF
1119 pad(output, allocation.limit_ - allocation.size_);
1120 position += allocation.limit_ - allocation.size_;
f4b2df35 1121
67205335
JF
1122 size_t saved(save(output, allocation.limit_, overlap, top));
1123 if (allocation.alloc_ > saved)
1124 pad(output, allocation.alloc_ - saved);
1125 position += allocation.alloc_;
e0098838
JF
1126 }
1127}
f4b2df35 1128
efad8a44
JF
1129typedef std::map<uint32_t, std::string> Blobs;
1130
bb591e2b
JF
1131static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1132 auto value(buffer.str());
1133 std::swap(blobs[slot], value);
1134}
1135
8f310b91
JF
1136static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1137 auto value(buffer.str());
1138 Blob blob;
1139 blob.magic = Swap(magic);
1140 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1141 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1142 std::swap(blobs[slot], value);
efad8a44
JF
1143}
1144
1145static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1146 size_t total(0);
1147 _foreach (blob, blobs)
1148 total += blob.second.size();
1149
1150 struct SuperBlob super;
1151 super.blob.magic = Swap(magic);
1152 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1153 super.count = Swap(uint32_t(blobs.size()));
1154 put(output, &super, sizeof(super));
1155
1156 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1157
1158 _foreach (blob, blobs) {
1159 BlobIndex index;
1160 index.type = Swap(blob.first);
1161 index.offset = Swap(uint32_t(offset));
1162 put(output, &index, sizeof(index));
1163 offset += blob.second.size();
1164 }
1165
1166 _foreach (blob, blobs)
1167 put(output, blob.second.data(), blob.second.size());
1168
1169 return offset;
1170}
1171
7c171fd3 1172void resign(void *idata, size_t isize, std::streambuf &output, const std::string &name, const std::string &entitlements) {
e0098838
JF
1173 uint8_t pageshift(0x0c);
1174 uint32_t pagesize(1 << pageshift);
f4b2df35 1175
e0098838
JF
1176 resign(idata, isize, output, fun([&](size_t size) -> size_t {
1177 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1178
e0098838 1179 uint32_t special(0);
f4b2df35 1180
e0098838
JF
1181 special = std::max(special, CSSLOT_REQUIREMENTS);
1182 alloc += sizeof(struct BlobIndex);
1183 alloc += 0xc;
f4b2df35 1184
faa1b1f8 1185 if (!entitlements.empty()) {
e0098838
JF
1186 special = std::max(special, CSSLOT_ENTITLEMENTS);
1187 alloc += sizeof(struct BlobIndex);
1188 alloc += sizeof(struct Blob);
1189 alloc += entitlements.size();
1190 }
f4b2df35 1191
e0098838
JF
1192 special = std::max(special, CSSLOT_CODEDIRECTORY);
1193 alloc += sizeof(struct BlobIndex);
1194 alloc += sizeof(struct Blob);
1195 alloc += sizeof(struct CodeDirectory);
7c171fd3 1196 alloc += name.size() + 1;
f4b2df35 1197
e0098838
JF
1198 uint32_t normal((size + pagesize - 1) / pagesize);
1199 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1200 return alloc;
1201 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
efad8a44 1202 Blobs blobs;
f4b2df35 1203
e0098838
JF
1204 if (true) {
1205 std::stringbuf data;
f4b2df35 1206
bb591e2b
JF
1207 Blobs requirements;
1208 put(data, CSMAGIC_REQUIREMENTS, requirements);
4d4682ef 1209
bb591e2b 1210 insert(blobs, CSSLOT_REQUIREMENTS, data);
e0098838 1211 }
4d4682ef 1212
faa1b1f8 1213 if (!entitlements.empty()) {
e0098838 1214 std::stringbuf data;
e0098838 1215 put(data, entitlements.data(), entitlements.size());
8f310b91 1216 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
e0098838
JF
1217 }
1218
1219 if (true) {
1220 std::stringbuf data;
1221
1222 uint32_t special(0);
1223 _foreach (blob, blobs)
1224 special = std::max(special, blob.first);
1225 uint32_t normal((limit + pagesize - 1) / pagesize);
1226
e0098838
JF
1227 CodeDirectory directory;
1228 directory.version = Swap(uint32_t(0x00020001));
1229 directory.flags = Swap(uint32_t(0));
8f310b91
JF
1230 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + name.size() + 1 + SHA_DIGEST_LENGTH * special));
1231 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
e0098838
JF
1232 directory.nSpecialSlots = Swap(special);
1233 directory.codeLimit = Swap(uint32_t(limit));
1234 directory.nCodeSlots = Swap(normal);
1235 directory.hashSize = SHA_DIGEST_LENGTH;
1236 directory.hashType = CS_HASHTYPE_SHA1;
1237 directory.spare1 = 0x00;
1238 directory.pageSize = pageshift;
1239 directory.spare2 = Swap(uint32_t(0));
1240 put(data, &directory, sizeof(directory));
1241
7c171fd3 1242 put(data, name.c_str(), name.size() + 1);
e0098838
JF
1243
1244 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1245 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1246
1247 memset(storage, 0, sizeof(*storage) * special);
4d4682ef
JF
1248
1249 _foreach (blob, blobs) {
e0098838
JF
1250 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1251 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
4d4682ef 1252 }
f4b2df35 1253
e0098838
JF
1254 if (normal != 1)
1255 for (size_t i = 0; i != normal - 1; ++i)
1256 sha1(hashes[i], (pagesize * i < overlap.size() ? overlap.data() : top) + pagesize * i, pagesize);
1257 if (normal != 0)
1258 sha1(hashes[normal - 1], top + pagesize * (normal - 1), ((limit - 1) % pagesize) + 1);
f4b2df35 1259
e0098838
JF
1260 put(data, storage, sizeof(storage));
1261
8f310b91 1262 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
f4b2df35 1263 }
e0098838 1264
efad8a44 1265 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
e0098838
JF
1266 }));
1267}
1268
1269void resign(void *idata, size_t isize, std::streambuf &output) {
1270 resign(idata, isize, output, fun([](size_t size) -> size_t {
1271 return 0;
1272 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1273 return 0;
1274 }));
f4b2df35
JF
1275}
1276
a7f01a65 1277int main(int argc, char *argv[]) {
5525a5a7
JF
1278 union {
1279 uint16_t word;
1280 uint8_t byte[2];
1281 } endian = {1};
1282
1283 little_ = endian.byte[0];
1284
20e7eb29 1285 bool flag_r(false);
9c83be90 1286 bool flag_e(false);
a362a82f
JF
1287
1288 bool flag_T(false);
20c5f1e8 1289
fdb119ef 1290 bool flag_S(false);
20c5f1e8 1291 bool flag_s(false);
a362a82f 1292
c0cc1574 1293 bool flag_D(false);
c0cc1574 1294
8c417842
JF
1295 bool flag_A(false);
1296 bool flag_a(false);
1297
c0cc1574
JF
1298 uint32_t flag_CPUType(_not(uint32_t));
1299 uint32_t flag_CPUSubtype(_not(uint32_t));
1300
5d7ceb5d
JF
1301 const char *flag_I(NULL);
1302
a362a82f
JF
1303 bool timeh(false);
1304 uint32_t timev(0);
1305
4d4682ef 1306 Map entitlements;
c05d9758 1307
a362a82f
JF
1308 std::vector<std::string> files;
1309
a960f392
JF
1310 if (argc == 1) {
1311 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 1312 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
1313 fprintf(stderr, " %s -S cat\n", argv[0]);
1314 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1315 exit(0);
1316 }
1317
a362a82f
JF
1318 for (int argi(1); argi != argc; ++argi)
1319 if (argv[argi][0] != '-')
1320 files.push_back(argv[argi]);
1321 else switch (argv[argi][1]) {
20e7eb29 1322 case 'r': flag_r = true; break;
9c83be90 1323 case 'e': flag_e = true; break;
c05d9758 1324
c0cc1574 1325 case 'D': flag_D = true; break;
c0cc1574 1326
8c417842
JF
1327 case 'a': flag_a = true; break;
1328
1329 case 'A':
1330 flag_A = true;
1331 if (argv[argi][2] != '\0') {
1332 const char *cpu = argv[argi] + 2;
1333 const char *colon = strchr(cpu, ':');
1334 _assert(colon != NULL);
1335 char *arge;
1336 flag_CPUType = strtoul(cpu, &arge, 0);
1337 _assert(arge == colon);
1338 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
1339 _assert(arge == argv[argi] + strlen(argv[argi]));
1340 }
1341 break;
1342
20c5f1e8
JF
1343 case 's':
1344 _assert(!flag_S);
1345 flag_s = true;
1346 break;
1347
c05d9758 1348 case 'S':
20c5f1e8 1349 _assert(!flag_s);
c05d9758
JF
1350 flag_S = true;
1351 if (argv[argi][2] != '\0') {
1352 const char *xml = argv[argi] + 2;
4d4682ef 1353 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
1354 }
1355 break;
a362a82f
JF
1356
1357 case 'T': {
1358 flag_T = true;
1359 if (argv[argi][2] == '-')
1360 timeh = true;
1361 else {
1362 char *arge;
1363 timev = strtoul(argv[argi] + 2, &arge, 0);
1364 _assert(arge == argv[argi] + strlen(argv[argi]));
1365 }
1366 } break;
1367
5d7ceb5d
JF
1368 case 'I': {
1369 flag_I = argv[argi] + 2;
1370 } break;
1371
a362a82f
JF
1372 default:
1373 goto usage;
1374 break;
1375 }
1376
f4b2df35
JF
1377 _assert(!flag_S || !flag_r);
1378
a362a82f
JF
1379 if (files.empty()) usage: {
1380 exit(0);
1381 }
1382
1383 size_t filei(0), filee(0);
1384 _foreach (file, files) try {
0a033524 1385 const char *path(file.c_str());
fdb119ef 1386 const char *base = strrchr(path, '/');
fdb119ef 1387
b7c20a6d 1388 std::string dir;
fdb119ef 1389 if (base != NULL)
b7c20a6d
JF
1390 dir.assign(path, base++ - path + 1);
1391 else
fdb119ef 1392 base = path;
fdb119ef 1393
5d7ceb5d 1394 const char *name(flag_I ?: base);
a7f01a65 1395 std::string temp;
5d7ceb5d 1396
cad40c43 1397 if (flag_S || flag_r) {
4d4682ef
JF
1398 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1399
a7f01a65 1400 temp = dir + "." + base + ".cs";
4d4682ef 1401 std::filebuf output;
a7f01a65 1402 _assert(output.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &output);
4d4682ef 1403
e0098838
JF
1404 if (flag_r)
1405 resign(input.data(), input.size(), output);
1406 else {
1407 resign(input.data(), input.size(), output, name, entitlements);
1408 }
fdb119ef
JF
1409 }
1410
a7f01a65 1411 Map mapping(!temp.empty() ? temp.c_str() : path, flag_T || flag_s);
dede6121 1412 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 1413
0a033524 1414 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 1415 struct linkedit_data_command *signature(NULL);
7b496abd
JF
1416 struct encryption_info_command *encryption(NULL);
1417
8c417842
JF
1418 if (flag_A) {
1419 if (mach_header.GetCPUType() != flag_CPUType)
1420 continue;
1421 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1422 continue;
1423 }
1424
1425 if (flag_a)
1426 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1427
0a033524
JF
1428 _foreach (load_command, mach_header.GetLoadCommands()) {
1429 uint32_t cmd(mach_header.Swap(load_command->cmd));
1430
cad40c43 1431 if (false);
0a033524
JF
1432 else if (cmd == LC_CODE_SIGNATURE)
1433 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 1434 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 1435 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
cad40c43 1436 else if (cmd == LC_ID_DYLIB) {
0a033524 1437 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 1438
0a033524
JF
1439 if (flag_T) {
1440 uint32_t timed;
a362a82f 1441
0a033524
JF
1442 if (!timeh)
1443 timed = timev;
1444 else {
1445 dylib_command->dylib.timestamp = 0;
1446 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1447 }
a362a82f 1448
0a033524
JF
1449 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1450 }
7b496abd
JF
1451 }
1452 }
1453
7b496abd
JF
1454 if (flag_D) {
1455 _assert(encryption != NULL);
1456 encryption->cryptid = mach_header.Swap(0);
a362a82f 1457 }
a362a82f 1458
0a033524
JF
1459 if (flag_e) {
1460 _assert(signature != NULL);
9c83be90 1461
0a033524 1462 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 1463
0a033524
JF
1464 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1465 uint8_t *blob = top + data;
1466 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 1467
0a033524
JF
1468 for (size_t index(0); index != Swap(super->count); ++index)
1469 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1470 uint32_t begin = Swap(super->index[index].offset);
1471 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1472 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
1473 }
1474 }
9c83be90 1475
0a033524
JF
1476 if (flag_s) {
1477 _assert(signature != NULL);
20c5f1e8 1478
0a033524 1479 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 1480
0a033524
JF
1481 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1482 uint8_t *blob = top + data;
1483 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 1484
0a033524
JF
1485 for (size_t index(0); index != Swap(super->count); ++index)
1486 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1487 uint32_t begin = Swap(super->index[index].offset);
1488 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 1489
4d4682ef 1490 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 1491 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 1492
0a033524
JF
1493 if (pages != 1)
1494 for (size_t i = 0; i != pages - 1; ++i)
1495 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1496 if (pages != 0)
1497 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1498 }
1499 }
fdb119ef
JF
1500 }
1501
a7f01a65 1502 if (!temp.empty()) {
31ad673b
JF
1503 struct stat info;
1504 _syscall(stat(path, &info));
a7f01a65
JF
1505#ifndef __WIN32__
1506 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1507#endif
1508 _syscall(chmod(temp.c_str(), info.st_mode));
fdb119ef 1509 _syscall(unlink(path));
a7f01a65 1510 _syscall(rename(temp.c_str(), path));
fdb119ef
JF
1511 }
1512
a362a82f
JF
1513 ++filei;
1514 } catch (const char *) {
1515 ++filee;
1516 ++filei;
1517 }
1518
1519 return filee;
1520}