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