]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Remove unused constructor in already-long Functor.
[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
b9652d6e
JF
379static const uint8_t PageShift_(0x0c);
380static const uint32_t PageSize_(1 << PageShift_);
381
f65c321b 382static inline uint16_t Swap_(uint16_t value) {
fdb119ef
JF
383 return
384 ((value >> 8) & 0x00ff) |
385 ((value << 8) & 0xff00);
386}
387
f65c321b 388static inline uint32_t Swap_(uint32_t value) {
fdb119ef
JF
389 value = ((value >> 8) & 0x00ff00ff) |
390 ((value << 8) & 0xff00ff00);
391 value = ((value >> 16) & 0x0000ffff) |
392 ((value << 16) & 0xffff0000);
393 return value;
394}
395
f65c321b 396static inline uint64_t Swap_(uint64_t value) {
4374152f
JF
397 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
398 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
399 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
400 return value;
401}
402
f65c321b 403static inline int16_t Swap_(int16_t value) {
fdb119ef
JF
404 return Swap_(static_cast<uint16_t>(value));
405}
406
f65c321b 407static inline int32_t Swap_(int32_t value) {
fdb119ef
JF
408 return Swap_(static_cast<uint32_t>(value));
409}
410
f65c321b 411static inline int64_t Swap_(int64_t value) {
4374152f
JF
412 return Swap_(static_cast<uint64_t>(value));
413}
414
f65c321b 415static bool little_(true);
5525a5a7 416
f65c321b 417static inline uint16_t Swap(uint16_t value) {
5525a5a7 418 return little_ ? Swap_(value) : value;
fdb119ef
JF
419}
420
f65c321b 421static inline uint32_t Swap(uint32_t value) {
5525a5a7 422 return little_ ? Swap_(value) : value;
fdb119ef
JF
423}
424
f65c321b 425static inline uint64_t Swap(uint64_t value) {
4374152f
JF
426 return little_ ? Swap_(value) : value;
427}
428
f65c321b 429static inline int16_t Swap(int16_t value) {
fdb119ef
JF
430 return Swap(static_cast<uint16_t>(value));
431}
432
f65c321b 433static inline int32_t Swap(int32_t value) {
fdb119ef
JF
434 return Swap(static_cast<uint32_t>(value));
435}
436
f65c321b 437static inline int64_t Swap(int64_t value) {
4374152f
JF
438 return Swap(static_cast<uint64_t>(value));
439}
440
6e83315b
JF
441template <typename Target_>
442class Pointer;
443
4d4682ef 444class Swapped {
0a033524 445 protected:
a362a82f
JF
446 bool swapped_;
447
4d4682ef 448 Swapped() :
0a033524
JF
449 swapped_(false)
450 {
451 }
452
4d4682ef
JF
453 public:
454 Swapped(bool swapped) :
455 swapped_(swapped)
456 {
a362a82f
JF
457 }
458
4d4682ef
JF
459 template <typename Type_>
460 Type_ Swap(Type_ value) const {
4374152f
JF
461 return swapped_ ? Swap_(value) : value;
462 }
4d4682ef 463};
4374152f 464
4d4682ef
JF
465class Data :
466 public Swapped
467{
468 private:
469 void *base_;
470 size_t size_;
a362a82f 471
4d4682ef
JF
472 public:
473 Data(void *base, size_t size) :
474 base_(base),
475 size_(size)
476 {
4374152f
JF
477 }
478
0a033524
JF
479 void *GetBase() const {
480 return base_;
481 }
a362a82f 482
0a033524
JF
483 size_t GetSize() const {
484 return size_;
485 }
486};
a362a82f 487
0a033524
JF
488class MachHeader :
489 public Data
490{
491 private:
492 bool bits64_;
493
494 struct mach_header *mach_header_;
495 struct load_command *load_command_;
496
497 public:
498 MachHeader(void *base, size_t size) :
499 Data(base, size)
500 {
501 mach_header_ = (mach_header *) base;
a362a82f 502
3cbc6463
JF
503 switch (Swap(mach_header_->magic)) {
504 case MH_CIGAM:
505 swapped_ = !swapped_;
506 case MH_MAGIC:
507 bits64_ = false;
508 break;
509
510 case MH_CIGAM_64:
511 swapped_ = !swapped_;
512 case MH_MAGIC_64:
513 bits64_ = true;
514 break;
515
516 default:
517 _assert(false);
518 }
519
520 void *post = mach_header_ + 1;
521 if (bits64_)
522 post = (uint32_t *) post + 1;
523 load_command_ = (struct load_command *) post;
a362a82f
JF
524
525 _assert(
526 Swap(mach_header_->filetype) == MH_EXECUTE ||
527 Swap(mach_header_->filetype) == MH_DYLIB ||
528 Swap(mach_header_->filetype) == MH_BUNDLE
529 );
530 }
531
4d4682ef
JF
532 bool Bits64() const {
533 return bits64_;
534 }
535
afbb7c8e
JF
536 struct mach_header *operator ->() const {
537 return mach_header_;
538 }
539
4374152f
JF
540 operator struct mach_header *() const {
541 return mach_header_;
542 }
543
04802ab1
JF
544 uint32_t GetCPUType() const {
545 return Swap(mach_header_->cputype);
546 }
547
4374152f 548 uint32_t GetCPUSubtype() const {
04802ab1
JF
549 return Swap(mach_header_->cpusubtype) & 0xff;
550 }
551
4374152f
JF
552 struct load_command *GetLoadCommand() const {
553 return load_command_;
554 }
555
0a033524 556 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
557 std::vector<struct load_command *> load_commands;
558
3cbc6463 559 struct load_command *load_command = load_command_;
a362a82f
JF
560 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
561 load_commands.push_back(load_command);
562 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
563 }
564
565 return load_commands;
566 }
6e83315b 567
6f340f51 568 std::vector<segment_command *> GetSegments(const char *segment_name) const {
6e83315b
JF
569 std::vector<struct segment_command *> segment_commands;
570
289ccbbc 571 _foreach (load_command, GetLoadCommands()) {
0a033524
JF
572 if (Swap(load_command->cmd) == LC_SEGMENT) {
573 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
574 if (strncmp(segment_command->segname, segment_name, 16) == 0)
575 segment_commands.push_back(segment_command);
576 }
289ccbbc
JF
577 }
578
579 return segment_commands;
580 }
581
4374152f 582 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
289ccbbc
JF
583 std::vector<struct segment_command_64 *> segment_commands;
584
585 _foreach (load_command, GetLoadCommands()) {
586 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
587 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
588 if (strncmp(segment_command->segname, segment_name, 16) == 0)
589 segment_commands.push_back(segment_command);
590 }
591 }
6e83315b
JF
592
593 return segment_commands;
594 }
595
6f340f51 596 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
6e83315b
JF
597 std::vector<section *> sections;
598
599 _foreach (segment, GetSegments(segment_name)) {
0a033524 600 section *section = (struct section *) (segment + 1);
6e83315b
JF
601
602 uint32_t sect;
0a033524 603 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
604 if (strncmp(section->sectname, section_name, 16) == 0)
605 sections.push_back(section);
606 ++section;
607 }
608 }
609
610 return sections;
611 }
612
613 template <typename Target_>
0a033524 614 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
615 load_command *load_command = (struct load_command *) (mach_header_ + 1);
616 uint32_t cmd;
617
618 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
619 if (Swap(load_command->cmd) == LC_SEGMENT) {
620 segment_command *segment_command = (struct segment_command *) load_command;
621 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
622 goto next_command;
623
624 section *sections = (struct section *) (segment_command + 1);
625
626 uint32_t sect;
627 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
628 section *section = &sections[sect];
629 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
630 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
631 //printf("0x%.8x %s\n", address, segment_command->segname);
632 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
633 }
634 }
635 }
636
637 next_command:
638 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
639 }
640
641 return Pointer<Target_>(this);
642 }
643
644 template <typename Target_>
645 Pointer<Target_> GetOffset(uint32_t offset) {
646 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
647 }
648};
649
289ccbbc
JF
650class FatMachHeader :
651 public MachHeader
652{
653 private:
654 fat_arch *fat_arch_;
655
656 public:
657 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
658 MachHeader(base, size),
659 fat_arch_(fat_arch)
660 {
661 }
662
663 fat_arch *GetFatArch() const {
664 return fat_arch_;
665 }
666};
667
0a033524
JF
668class FatHeader :
669 public Data
670{
671 private:
672 fat_header *fat_header_;
289ccbbc 673 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
674
675 public:
676 FatHeader(void *base, size_t size) :
677 Data(base, size)
678 {
679 fat_header_ = reinterpret_cast<struct fat_header *>(base);
680
681 if (Swap(fat_header_->magic) == FAT_CIGAM) {
682 swapped_ = !swapped_;
683 goto fat;
684 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
685 fat_header_ = NULL;
289ccbbc 686 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
687 } else fat: {
688 size_t fat_narch = Swap(fat_header_->nfat_arch);
689 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
690 size_t arch;
691 for (arch = 0; arch != fat_narch; ++arch) {
692 uint32_t arch_offset = Swap(fat_arch->offset);
693 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 694 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
695 ++fat_arch;
696 }
697 }
698 }
699
289ccbbc 700 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
701 return mach_headers_;
702 }
20e7eb29
JF
703
704 bool IsFat() const {
705 return fat_header_ != NULL;
706 }
6b38c173
JF
707
708 struct fat_header *operator ->() const {
709 return fat_header_;
710 }
4374152f
JF
711
712 operator struct fat_header *() const {
713 return fat_header_;
714 }
0a033524
JF
715};
716
6e83315b
JF
717template <typename Target_>
718class Pointer {
719 private:
0a033524 720 const MachHeader *framework_;
6e83315b
JF
721 const Target_ *pointer_;
722
723 public:
0a033524 724 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
725 framework_(framework),
726 pointer_(pointer)
727 {
728 }
729
730 operator const Target_ *() const {
731 return pointer_;
732 }
733
734 const Target_ *operator ->() const {
735 return pointer_;
736 }
737
738 Pointer<Target_> &operator ++() {
739 ++pointer_;
740 return *this;
741 }
742
743 template <typename Value_>
744 Value_ Swap(Value_ value) {
745 return framework_->Swap(value);
746 }
a362a82f
JF
747};
748
4d4682ef
JF
749#define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
750#define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
751#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
752#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
753#define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
754#define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
755#define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
756#define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
c05d9758 757
4d4682ef
JF
758#define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
759#define CSSLOT_INFOSLOT uint32_t(0x00001)
760#define CSSLOT_REQUIREMENTS uint32_t(0x00002)
761#define CSSLOT_RESOURCEDIR uint32_t(0x00003)
762#define CSSLOT_APPLICATION uint32_t(0x00004)
763#define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
764
765#define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
766
767#define CS_HASHTYPE_SHA1 1
fdb119ef
JF
768
769struct BlobIndex {
770 uint32_t type;
771 uint32_t offset;
c05d9758 772} _packed;
fdb119ef 773
c05d9758 774struct Blob {
fdb119ef
JF
775 uint32_t magic;
776 uint32_t length;
c05d9758
JF
777} _packed;
778
779struct SuperBlob {
780 struct Blob blob;
fdb119ef
JF
781 uint32_t count;
782 struct BlobIndex index[];
c05d9758 783} _packed;
fdb119ef
JF
784
785struct CodeDirectory {
fdb119ef
JF
786 uint32_t version;
787 uint32_t flags;
788 uint32_t hashOffset;
789 uint32_t identOffset;
790 uint32_t nSpecialSlots;
791 uint32_t nCodeSlots;
792 uint32_t codeLimit;
793 uint8_t hashSize;
794 uint8_t hashType;
795 uint8_t spare1;
796 uint8_t pageSize;
797 uint32_t spare2;
c05d9758 798} _packed;
fdb119ef 799
a362a82f
JF
800extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
801
f65c321b 802static void sha1(uint8_t *hash, const void *data, size_t size) {
4d4682ef 803 SHA1(static_cast<const uint8_t *>(data), size, hash);
fdb119ef
JF
804}
805
0a033524 806struct CodesignAllocation {
4374152f
JF
807 FatMachHeader mach_header_;
808 uint32_t offset_;
809 uint32_t size_;
4d4682ef 810 uint32_t limit_;
4374152f 811 uint32_t alloc_;
e4b7adc1 812 uint32_t align_;
4374152f 813
e0098838 814 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
4374152f
JF
815 mach_header_(mach_header),
816 offset_(offset),
817 size_(size),
4d4682ef 818 limit_(limit),
e4b7adc1
JF
819 alloc_(alloc),
820 align_(align)
0a033524
JF
821 {
822 }
823};
824
dede6121
JF
825class File {
826 private:
827 int file_;
828
829 public:
830 File() :
831 file_(-1)
832 {
833 }
834
835 ~File() {
836 if (file_ != -1)
837 _syscall(close(file_));
838 }
839
cad40c43 840 void open(const char *path, int flags) {
dede6121 841 _assert(file_ == -1);
cad40c43 842 _syscall(file_ = ::open(path, flags));
dede6121
JF
843 }
844
845 int file() const {
846 return file_;
847 }
848};
849
850class Map {
851 private:
852 File file_;
853 void *data_;
854 size_t size_;
855
856 void clear() {
857 if (data_ == NULL)
858 return;
859 _syscall(munmap(data_, size_));
860 data_ = NULL;
861 size_ = 0;
862 }
863
864 public:
865 Map() :
866 data_(NULL),
867 size_(0)
868 {
869 }
870
cad40c43
JF
871 Map(const char *path, int oflag, int pflag, int mflag) :
872 Map()
873 {
874 open(path, oflag, pflag, mflag);
875 }
876
877 Map(const char *path, bool edit) :
878 Map()
879 {
880 open(path, edit);
dede6121
JF
881 }
882
883 ~Map() {
884 clear();
885 }
886
fac3d3e3
JF
887 bool empty() const {
888 return data_ == NULL;
889 }
890
cad40c43 891 void open(const char *path, int oflag, int pflag, int mflag) {
dede6121
JF
892 clear();
893
cad40c43 894 file_.open(path, oflag);
dede6121
JF
895 int file(file_.file());
896
897 struct stat stat;
898 _syscall(fstat(file, &stat));
899 size_ = stat.st_size;
900
cad40c43
JF
901 _syscall(data_ = mmap(NULL, size_, pflag, mflag, file, 0));
902 }
903
904 void open(const char *path, bool edit) {
905 if (edit)
906 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
907 else
908 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
909 }
910
911 void *data() const {
912 return data_;
913 }
914
915 size_t size() const {
916 return size_;
917 }
f4b2df35
JF
918
919 operator std::string() const {
920 return std::string(static_cast<char *>(data_), size_);
921 }
dede6121
JF
922};
923
e0098838 924// I wish Apple cared about providing quality toolchains :/
4d4682ef 925
e0098838
JF
926template <typename Function_>
927class Functor;
928
929template <typename Type_, typename... Args_>
930class Functor<Type_ (Args_...)> {
931 public:
932 virtual Type_ operator ()(Args_... args) const = 0;
e0098838
JF
933};
934
935template <typename Function_>
936class FunctorImpl;
937
938template <typename Value_, typename Type_, typename... Args_>
939class FunctorImpl<Type_ (Value_::*)(Args_...) const> :
940 public Functor<Type_ (Args_...)>
941{
942 private:
943 const Value_ *value_;
944
945 public:
e0098838
JF
946 FunctorImpl(const Value_ &value) :
947 value_(&value)
948 {
949 }
950
951 virtual Type_ operator ()(Args_... args) const {
952 return (*value_)(args...);
953 }
954};
955
956template <typename Function_>
957FunctorImpl<decltype(&Function_::operator())> fun(const Function_ &value) {
958 return value;
959}
960
f65c321b 961static 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 962 FatHeader source(idata, isize);
f4b2df35
JF
963
964 size_t offset(0);
965 if (source.IsFat())
966 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
967
968 std::vector<CodesignAllocation> allocations;
969 _foreach (mach_header, source.GetMachHeaders()) {
970 struct linkedit_data_command *signature(NULL);
971 struct symtab_command *symtab(NULL);
972
973 _foreach (load_command, mach_header.GetLoadCommands()) {
974 uint32_t cmd(mach_header.Swap(load_command->cmd));
975 if (false);
976 else if (cmd == LC_CODE_SIGNATURE)
977 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
978 else if (cmd == LC_SYMTAB)
979 symtab = reinterpret_cast<struct symtab_command *>(load_command);
980 }
981
982 size_t size;
983 if (signature == NULL)
984 size = mach_header.GetSize();
985 else {
986 size = mach_header.Swap(signature->dataoff);
987 _assert(size <= mach_header.GetSize());
988 }
989
990 if (symtab != NULL) {
991 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
992 _assert(end <= size);
993 _assert(end >= size - 0x10);
994 size = end;
995 }
996
e0098838 997 size_t alloc(allocate(size));
f4b2df35
JF
998
999 auto *fat_arch(mach_header.GetFatArch());
1000 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
1001 offset = Align(offset, 1 << align);
1002
4d4682ef
JF
1003 uint32_t limit(size);
1004 if (alloc != 0)
1005 limit = Align(limit, 0x10);
1006
e0098838 1007 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
f4b2df35 1008 offset += size + alloc;
b9652d6e 1009 offset = Align(offset, 0x10);
f4b2df35
JF
1010 }
1011
4d4682ef
JF
1012 size_t position(0);
1013
1014 if (source.IsFat()) {
1015 fat_header fat_header;
1016 fat_header.magic = Swap(FAT_MAGIC);
1017 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1018 put(output, &fat_header, sizeof(fat_header));
1019 position += sizeof(fat_header);
1020
1021 _foreach (allocation, allocations) {
1022 auto &mach_header(allocation.mach_header_);
1023
1024 fat_arch fat_arch;
1025 fat_arch.cputype = Swap(mach_header->cputype);
1026 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1027 fat_arch.offset = Swap(allocation.offset_);
1028 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1029 fat_arch.align = Swap(allocation.align_);
1030 put(output, &fat_arch, sizeof(fat_arch));
1031 position += sizeof(fat_arch);
1032 }
f4b2df35
JF
1033 }
1034
1035 _foreach (allocation, allocations) {
4d4682ef 1036 auto &mach_header(allocation.mach_header_);
f4b2df35 1037
4d4682ef
JF
1038 pad(output, allocation.offset_ - position);
1039 position = allocation.offset_;
f4b2df35 1040
4d4682ef 1041 std::vector<std::string> commands;
f4b2df35 1042
4d4682ef
JF
1043 _foreach (load_command, mach_header.GetLoadCommands()) {
1044 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1045
a7f01a65 1046 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1047 case LC_CODE_SIGNATURE:
1048 continue;
1049 break;
1050
1051 case LC_SEGMENT: {
1052 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1053 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1054 break;
1055 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1056 segment_command->filesize = size;
b9652d6e 1057 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1058 } break;
1059
1060 case LC_SEGMENT_64: {
1061 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1062 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1063 break;
1064 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1065 segment_command->filesize = size;
b9652d6e 1066 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1067 } break;
1068 }
f4b2df35 1069
4d4682ef 1070 commands.push_back(copy);
f4b2df35
JF
1071 }
1072
e0098838 1073 if (allocation.alloc_ != 0) {
4d4682ef
JF
1074 linkedit_data_command signature;
1075 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1076 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1077 signature.dataoff = mach_header.Swap(allocation.limit_);
1078 signature.datasize = mach_header.Swap(allocation.alloc_);
1079 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1080 }
f4b2df35 1081
4d4682ef 1082 size_t begin(position);
f4b2df35 1083
4d4682ef
JF
1084 uint32_t after(0);
1085 _foreach(command, commands)
1086 after += command.size();
f4b2df35 1087
4d4682ef 1088 std::stringbuf altern;
f4b2df35 1089
4d4682ef
JF
1090 struct mach_header header(*mach_header);
1091 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1092 header.sizeofcmds = mach_header.Swap(after);
1093 put(output, &header, sizeof(header));
1094 put(altern, &header, sizeof(header));
1095 position += sizeof(header);
f4b2df35 1096
4d4682ef
JF
1097 if (mach_header.Bits64()) {
1098 auto pad(mach_header.Swap(uint32_t(0)));
1099 put(output, &pad, sizeof(pad));
1100 put(altern, &pad, sizeof(pad));
1101 position += sizeof(pad);
1102 }
f4b2df35 1103
4d4682ef
JF
1104 _foreach(command, commands) {
1105 put(output, command.data(), command.size());
1106 put(altern, command.data(), command.size());
1107 position += command.size();
1108 }
f4b2df35 1109
4d4682ef
JF
1110 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1111 if (before > after) {
1112 pad(output, before - after);
1113 pad(altern, before - after);
1114 position += before - after;
1115 }
f4b2df35 1116
4d4682ef 1117 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1118
4d4682ef
JF
1119 std::string overlap(altern.str());
1120 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1121
4d4682ef
JF
1122 put(output, top + (position - begin), allocation.size_ - (position - begin));
1123 position = begin + allocation.size_;
f4b2df35 1124
4d4682ef
JF
1125 pad(output, allocation.limit_ - allocation.size_);
1126 position += allocation.limit_ - allocation.size_;
f4b2df35 1127
67205335
JF
1128 size_t saved(save(output, allocation.limit_, overlap, top));
1129 if (allocation.alloc_ > saved)
1130 pad(output, allocation.alloc_ - saved);
1131 position += allocation.alloc_;
e0098838
JF
1132 }
1133}
f4b2df35 1134
efad8a44
JF
1135typedef std::map<uint32_t, std::string> Blobs;
1136
bb591e2b
JF
1137static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1138 auto value(buffer.str());
1139 std::swap(blobs[slot], value);
1140}
1141
8f310b91
JF
1142static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1143 auto value(buffer.str());
1144 Blob blob;
1145 blob.magic = Swap(magic);
1146 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1147 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1148 std::swap(blobs[slot], value);
efad8a44
JF
1149}
1150
1151static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1152 size_t total(0);
1153 _foreach (blob, blobs)
1154 total += blob.second.size();
1155
1156 struct SuperBlob super;
1157 super.blob.magic = Swap(magic);
1158 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1159 super.count = Swap(uint32_t(blobs.size()));
1160 put(output, &super, sizeof(super));
1161
1162 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1163
1164 _foreach (blob, blobs) {
1165 BlobIndex index;
1166 index.type = Swap(blob.first);
1167 index.offset = Swap(uint32_t(offset));
1168 put(output, &index, sizeof(index));
1169 offset += blob.second.size();
1170 }
1171
1172 _foreach (blob, blobs)
1173 put(output, blob.second.data(), blob.second.size());
1174
1175 return offset;
1176}
1177
30c64adb
JF
1178class Buffer {
1179 private:
1180 BIO *bio_;
1181
1182 public:
1183 Buffer(BIO *bio) :
1184 bio_(bio)
1185 {
1186 _assert(bio_ != NULL);
1187 }
1188
1189 Buffer() :
1190 bio_(BIO_new(BIO_s_mem()))
1191 {
1192 }
1193
1194 Buffer(const char *data, size_t size) :
1195 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1196 {
1197 }
1198
1199 Buffer(const std::string &data) :
1200 Buffer(data.data(), data.size())
1201 {
1202 }
1203
1204 Buffer(PKCS7 *pkcs) :
1205 Buffer()
1206 {
1207 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1208 }
1209
1210 ~Buffer() {
1211 BIO_free_all(bio_);
1212 }
1213
1214 operator BIO *() const {
1215 return bio_;
1216 }
1217
1218 explicit operator std::string() const {
1219 char *data;
1220 auto size(BIO_get_mem_data(bio_, &data));
1221 return std::string(data, size);
1222 }
1223};
1224
1225class Stuff {
1226 private:
1227 PKCS12 *value_;
1228 EVP_PKEY *key_;
1229 X509 *cert_;
1230 STACK_OF(X509) *ca_;
1231
1232 public:
1233 Stuff(BIO *bio) :
1234 value_(d2i_PKCS12_bio(bio, NULL)),
1235 ca_(NULL)
1236 {
1237 _assert(value_ != NULL);
1238 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1239 _assert(key_ != NULL);
1240 _assert(cert_ != NULL);
1241 }
1242
1243 Stuff(const std::string &data) :
1244 Stuff(Buffer(data))
1245 {
1246 }
1247
1248 ~Stuff() {
1249 sk_X509_pop_free(ca_, X509_free);
1250 X509_free(cert_);
1251 EVP_PKEY_free(key_);
1252 PKCS12_free(value_);
1253 }
1254
1255 operator PKCS12 *() const {
1256 return value_;
1257 }
1258
1259 operator EVP_PKEY *() const {
1260 return key_;
1261 }
1262
1263 operator X509 *() const {
1264 return cert_;
1265 }
1266
1267 operator STACK_OF(X509) *() const {
1268 return ca_;
1269 }
1270};
1271
1272class Signature {
1273 private:
1274 PKCS7 *value_;
1275
1276 public:
1277 Signature(const Stuff &stuff, const Buffer &data) :
1278 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1279 {
1280 _assert(value_ != NULL);
1281 }
1282
1283 ~Signature() {
1284 PKCS7_free(value_);
1285 }
1286
1287 operator PKCS7 *() const {
1288 return value_;
1289 }
1290};
1291
1292void resign(void *idata, size_t isize, std::streambuf &output, const std::string &name, const std::string &entitlements, const std::string &key) {
e0098838
JF
1293 resign(idata, isize, output, fun([&](size_t size) -> size_t {
1294 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1295
e0098838 1296 uint32_t special(0);
f4b2df35 1297
e0098838
JF
1298 special = std::max(special, CSSLOT_REQUIREMENTS);
1299 alloc += sizeof(struct BlobIndex);
1300 alloc += 0xc;
f4b2df35 1301
faa1b1f8 1302 if (!entitlements.empty()) {
e0098838
JF
1303 special = std::max(special, CSSLOT_ENTITLEMENTS);
1304 alloc += sizeof(struct BlobIndex);
1305 alloc += sizeof(struct Blob);
1306 alloc += entitlements.size();
1307 }
f4b2df35 1308
e0098838
JF
1309 special = std::max(special, CSSLOT_CODEDIRECTORY);
1310 alloc += sizeof(struct BlobIndex);
1311 alloc += sizeof(struct Blob);
1312 alloc += sizeof(struct CodeDirectory);
7c171fd3 1313 alloc += name.size() + 1;
f4b2df35 1314
30c64adb
JF
1315 if (!key.empty()) {
1316 alloc += sizeof(struct BlobIndex);
1317 alloc += sizeof(struct Blob);
1318 // XXX: this is just a "sufficiently large number"
1319 alloc += 0x3000;
1320 }
1321
b9652d6e 1322 uint32_t normal((size + PageSize_ - 1) / PageSize_);
e0098838
JF
1323 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1324 return alloc;
1325 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
efad8a44 1326 Blobs blobs;
f4b2df35 1327
e0098838
JF
1328 if (true) {
1329 std::stringbuf data;
f4b2df35 1330
bb591e2b
JF
1331 Blobs requirements;
1332 put(data, CSMAGIC_REQUIREMENTS, requirements);
4d4682ef 1333
bb591e2b 1334 insert(blobs, CSSLOT_REQUIREMENTS, data);
e0098838 1335 }
4d4682ef 1336
faa1b1f8 1337 if (!entitlements.empty()) {
e0098838 1338 std::stringbuf data;
e0098838 1339 put(data, entitlements.data(), entitlements.size());
8f310b91 1340 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
e0098838
JF
1341 }
1342
1343 if (true) {
1344 std::stringbuf data;
1345
1346 uint32_t special(0);
1347 _foreach (blob, blobs)
1348 special = std::max(special, blob.first);
b9652d6e 1349 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
e0098838 1350
e0098838
JF
1351 CodeDirectory directory;
1352 directory.version = Swap(uint32_t(0x00020001));
1353 directory.flags = Swap(uint32_t(0));
8f310b91
JF
1354 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + name.size() + 1 + SHA_DIGEST_LENGTH * special));
1355 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
e0098838
JF
1356 directory.nSpecialSlots = Swap(special);
1357 directory.codeLimit = Swap(uint32_t(limit));
1358 directory.nCodeSlots = Swap(normal);
1359 directory.hashSize = SHA_DIGEST_LENGTH;
1360 directory.hashType = CS_HASHTYPE_SHA1;
1361 directory.spare1 = 0x00;
b9652d6e 1362 directory.pageSize = PageShift_;
e0098838
JF
1363 directory.spare2 = Swap(uint32_t(0));
1364 put(data, &directory, sizeof(directory));
1365
7c171fd3 1366 put(data, name.c_str(), name.size() + 1);
e0098838
JF
1367
1368 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1369 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1370
1371 memset(storage, 0, sizeof(*storage) * special);
4d4682ef
JF
1372
1373 _foreach (blob, blobs) {
e0098838
JF
1374 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1375 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
4d4682ef 1376 }
f4b2df35 1377
e0098838
JF
1378 if (normal != 1)
1379 for (size_t i = 0; i != normal - 1; ++i)
b9652d6e 1380 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
e0098838 1381 if (normal != 0)
b9652d6e 1382 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
f4b2df35 1383
e0098838
JF
1384 put(data, storage, sizeof(storage));
1385
8f310b91 1386 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
f4b2df35 1387 }
e0098838 1388
30c64adb
JF
1389 if (!key.empty()) {
1390 std::stringbuf data;
1391 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1392
1393 Stuff stuff(key);
1394 Buffer bio(sign);
1395
1396 Signature signature(stuff, sign);
1397 Buffer result(signature);
1398 std::string value(result);
1399 put(data, value.data(), value.size());
1400
1401 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1402 }
1403
efad8a44 1404 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
e0098838
JF
1405 }));
1406}
1407
f65c321b 1408static void resign(void *idata, size_t isize, std::streambuf &output) {
e0098838
JF
1409 resign(idata, isize, output, fun([](size_t size) -> size_t {
1410 return 0;
1411 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1412 return 0;
1413 }));
f4b2df35
JF
1414}
1415
a7f01a65 1416int main(int argc, char *argv[]) {
30c64adb
JF
1417 OpenSSL_add_all_algorithms();
1418
5525a5a7
JF
1419 union {
1420 uint16_t word;
1421 uint8_t byte[2];
1422 } endian = {1};
1423
1424 little_ = endian.byte[0];
1425
20e7eb29 1426 bool flag_r(false);
9c83be90 1427 bool flag_e(false);
a362a82f
JF
1428
1429 bool flag_T(false);
20c5f1e8 1430
fdb119ef 1431 bool flag_S(false);
20c5f1e8 1432 bool flag_s(false);
a362a82f 1433
c0cc1574 1434 bool flag_D(false);
c0cc1574 1435
8c417842
JF
1436 bool flag_A(false);
1437 bool flag_a(false);
1438
c0cc1574
JF
1439 uint32_t flag_CPUType(_not(uint32_t));
1440 uint32_t flag_CPUSubtype(_not(uint32_t));
1441
5d7ceb5d
JF
1442 const char *flag_I(NULL);
1443
a362a82f
JF
1444 bool timeh(false);
1445 uint32_t timev(0);
1446
4d4682ef 1447 Map entitlements;
30c64adb 1448 Map key;
c05d9758 1449
a362a82f
JF
1450 std::vector<std::string> files;
1451
a960f392
JF
1452 if (argc == 1) {
1453 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 1454 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
1455 fprintf(stderr, " %s -S cat\n", argv[0]);
1456 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1457 exit(0);
1458 }
1459
a362a82f
JF
1460 for (int argi(1); argi != argc; ++argi)
1461 if (argv[argi][0] != '-')
1462 files.push_back(argv[argi]);
1463 else switch (argv[argi][1]) {
fac3d3e3
JF
1464 case 'r':
1465 _assert(!flag_s);
1466 _assert(!flag_S);
1467 flag_r = true;
1468 break;
1469
9c83be90 1470 case 'e': flag_e = true; break;
c05d9758 1471
c0cc1574 1472 case 'D': flag_D = true; break;
c0cc1574 1473
8c417842
JF
1474 case 'a': flag_a = true; break;
1475
1476 case 'A':
fac3d3e3 1477 _assert(!flag_A);
8c417842
JF
1478 flag_A = true;
1479 if (argv[argi][2] != '\0') {
1480 const char *cpu = argv[argi] + 2;
1481 const char *colon = strchr(cpu, ':');
1482 _assert(colon != NULL);
1483 char *arge;
1484 flag_CPUType = strtoul(cpu, &arge, 0);
1485 _assert(arge == colon);
1486 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
1487 _assert(arge == argv[argi] + strlen(argv[argi]));
1488 }
1489 break;
1490
20c5f1e8 1491 case 's':
fac3d3e3 1492 _assert(!flag_r);
20c5f1e8
JF
1493 _assert(!flag_S);
1494 flag_s = true;
1495 break;
1496
c05d9758 1497 case 'S':
fac3d3e3 1498 _assert(!flag_r);
20c5f1e8 1499 _assert(!flag_s);
c05d9758
JF
1500 flag_S = true;
1501 if (argv[argi][2] != '\0') {
1502 const char *xml = argv[argi] + 2;
4d4682ef 1503 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
1504 }
1505 break;
a362a82f 1506
30c64adb
JF
1507 case 'K':
1508 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
1509 break;
1510
a362a82f
JF
1511 case 'T': {
1512 flag_T = true;
1513 if (argv[argi][2] == '-')
1514 timeh = true;
1515 else {
1516 char *arge;
1517 timev = strtoul(argv[argi] + 2, &arge, 0);
1518 _assert(arge == argv[argi] + strlen(argv[argi]));
1519 }
1520 } break;
1521
5d7ceb5d
JF
1522 case 'I': {
1523 flag_I = argv[argi] + 2;
1524 } break;
1525
a362a82f
JF
1526 default:
1527 goto usage;
1528 break;
1529 }
1530
fac3d3e3
JF
1531 _assert(flag_S || key.empty());
1532 _assert(flag_S || flag_I == NULL);
f4b2df35 1533
a362a82f
JF
1534 if (files.empty()) usage: {
1535 exit(0);
1536 }
1537
1538 size_t filei(0), filee(0);
1539 _foreach (file, files) try {
0a033524 1540 const char *path(file.c_str());
fdb119ef 1541 const char *base = strrchr(path, '/');
fdb119ef 1542
b7c20a6d 1543 std::string dir;
fdb119ef 1544 if (base != NULL)
b7c20a6d
JF
1545 dir.assign(path, base++ - path + 1);
1546 else
fdb119ef 1547 base = path;
fdb119ef 1548
5d7ceb5d 1549 const char *name(flag_I ?: base);
a7f01a65 1550 std::string temp;
5d7ceb5d 1551
cad40c43 1552 if (flag_S || flag_r) {
4d4682ef
JF
1553 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1554
a7f01a65 1555 temp = dir + "." + base + ".cs";
4d4682ef 1556 std::filebuf output;
a7f01a65 1557 _assert(output.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &output);
4d4682ef 1558
e0098838
JF
1559 if (flag_r)
1560 resign(input.data(), input.size(), output);
1561 else {
30c64adb 1562 resign(input.data(), input.size(), output, name, entitlements, key);
e0098838 1563 }
fdb119ef
JF
1564 }
1565
a7f01a65 1566 Map mapping(!temp.empty() ? temp.c_str() : path, flag_T || flag_s);
dede6121 1567 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 1568
0a033524 1569 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 1570 struct linkedit_data_command *signature(NULL);
7b496abd
JF
1571 struct encryption_info_command *encryption(NULL);
1572
8c417842
JF
1573 if (flag_A) {
1574 if (mach_header.GetCPUType() != flag_CPUType)
1575 continue;
1576 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1577 continue;
1578 }
1579
1580 if (flag_a)
1581 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1582
0a033524
JF
1583 _foreach (load_command, mach_header.GetLoadCommands()) {
1584 uint32_t cmd(mach_header.Swap(load_command->cmd));
1585
cad40c43 1586 if (false);
0a033524
JF
1587 else if (cmd == LC_CODE_SIGNATURE)
1588 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 1589 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 1590 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
cad40c43 1591 else if (cmd == LC_ID_DYLIB) {
0a033524 1592 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 1593
0a033524
JF
1594 if (flag_T) {
1595 uint32_t timed;
a362a82f 1596
0a033524
JF
1597 if (!timeh)
1598 timed = timev;
1599 else {
1600 dylib_command->dylib.timestamp = 0;
1601 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1602 }
a362a82f 1603
0a033524
JF
1604 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1605 }
7b496abd
JF
1606 }
1607 }
1608
7b496abd
JF
1609 if (flag_D) {
1610 _assert(encryption != NULL);
1611 encryption->cryptid = mach_header.Swap(0);
a362a82f 1612 }
a362a82f 1613
0a033524
JF
1614 if (flag_e) {
1615 _assert(signature != NULL);
9c83be90 1616
0a033524 1617 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 1618
0a033524
JF
1619 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1620 uint8_t *blob = top + data;
1621 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 1622
0a033524
JF
1623 for (size_t index(0); index != Swap(super->count); ++index)
1624 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1625 uint32_t begin = Swap(super->index[index].offset);
1626 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
b9652d6e 1627 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
0a033524
JF
1628 }
1629 }
9c83be90 1630
0a033524
JF
1631 if (flag_s) {
1632 _assert(signature != NULL);
20c5f1e8 1633
0a033524 1634 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 1635
0a033524
JF
1636 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1637 uint8_t *blob = top + data;
1638 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 1639
0a033524
JF
1640 for (size_t index(0); index != Swap(super->count); ++index)
1641 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1642 uint32_t begin = Swap(super->index[index].offset);
1643 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 1644
4d4682ef 1645 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 1646 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 1647
0a033524
JF
1648 if (pages != 1)
1649 for (size_t i = 0; i != pages - 1; ++i)
b9652d6e 1650 sha1(hashes[i], top + PageSize_ * i, PageSize_);
0a033524 1651 if (pages != 0)
b9652d6e 1652 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
0a033524
JF
1653 }
1654 }
fdb119ef
JF
1655 }
1656
a7f01a65 1657 if (!temp.empty()) {
31ad673b
JF
1658 struct stat info;
1659 _syscall(stat(path, &info));
a7f01a65
JF
1660#ifndef __WIN32__
1661 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1662#endif
1663 _syscall(chmod(temp.c_str(), info.st_mode));
fdb119ef 1664 _syscall(unlink(path));
a7f01a65 1665 _syscall(rename(temp.c_str(), path));
fdb119ef
JF
1666 }
1667
a362a82f
JF
1668 ++filei;
1669 } catch (const char *) {
1670 ++filee;
1671 ++filei;
1672 }
1673
1674 return filee;
1675}