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