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