]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Finish implementating application bundle codesign.
[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 25#include <fstream>
23c11ee8
JF
26#include <iostream>
27#include <set>
4d4682ef 28#include <sstream>
a362a82f
JF
29#include <string>
30#include <vector>
31
fa59c178 32#include <errno.h>
dede6121 33#include <fcntl.h>
23c11ee8
JF
34#include <fts.h>
35#include <regex.h>
fa59c178
JF
36#include <stdbool.h>
37#include <stdint.h>
a7f01a65 38#include <unistd.h>
dede6121
JF
39
40#include <sys/mman.h>
41#include <sys/stat.h>
23c11ee8 42#include <sys/types.h>
dede6121 43
30c64adb
JF
44#include <openssl/err.h>
45#include <openssl/pem.h>
46#include <openssl/pkcs7.h>
47#include <openssl/pkcs12.h>
a50bb1be
JF
48#include <openssl/sha.h>
49
23fff9c8 50#include <plist/plist++.h>
15babeef 51
a0c715e9
JF
52#include "ldid.hpp"
53
fa59c178
JF
54#define _assert___(line) \
55 #line
56#define _assert__(line) \
57 _assert___(line)
fa59c178 58
eff987d2 59#define _assert_(expr, format, ...) \
fa59c178 60 do if (!(expr)) { \
eff987d2
JF
61 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
62 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
fa59c178
JF
63 } while (false)
64
eff987d2
JF
65#define _assert(expr) \
66 _assert_(expr, "%s", #expr)
67
23c11ee8
JF
68#define _syscall(expr, ...) [&] { for (;;) { \
69 auto _value(expr); \
70 if ((long) _value != -1) \
71 return _value; \
72 int error(errno); \
73 if (error == EINTR) \
74 continue; \
75 for (auto success : (long[]) {__VA_ARGS__}) \
76 if (error == success) \
77 return (decltype(expr)) -success; \
78 _assert_(false, "errno=%u", error); \
79} }()
fa59c178
JF
80
81#define _trace() \
82 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
83
84#define _not(type) \
85 ((type) ~ (type) 0)
86
87#define _packed \
88 __attribute__((packed))
89
90template <typename Type_>
91struct Iterator_ {
92 typedef typename Type_::const_iterator Result;
93};
94
95#define _foreach(item, list) \
96 for (bool _stop(true); _stop; ) \
97 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
98 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
99 for (bool _suck(true); _suck; _suck = false) \
100 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
101
23c11ee8
JF
102class _Scope {
103};
104
105template <typename Function_>
106class Scope :
107 public _Scope
108{
109 private:
110 Function_ function_;
111
112 public:
113 Scope(const Function_ &function) :
114 function_(function)
115 {
116 }
117
118 ~Scope() {
119 function_();
120 }
121};
122
123template <typename Function_>
124Scope<Function_> _scope(const Function_ &function) {
125 return Scope<Function_>(function);
126}
127
128#define _scope__(counter, function) \
129 __attribute__((__unused__)) \
130 const _Scope &_scope ## counter(_scope([&]function))
131#define _scope_(counter, function) \
132 _scope__(counter, function)
133#define _scope(function) \
134 _scope_(__COUNTER__, function)
135
a362a82f
JF
136struct fat_header {
137 uint32_t magic;
138 uint32_t nfat_arch;
c05d9758 139} _packed;
a362a82f
JF
140
141#define FAT_MAGIC 0xcafebabe
142#define FAT_CIGAM 0xbebafeca
143
144struct fat_arch {
145 uint32_t cputype;
146 uint32_t cpusubtype;
147 uint32_t offset;
148 uint32_t size;
149 uint32_t align;
c05d9758 150} _packed;
a362a82f
JF
151
152struct mach_header {
153 uint32_t magic;
154 uint32_t cputype;
04802ab1 155 uint32_t cpusubtype;
a362a82f
JF
156 uint32_t filetype;
157 uint32_t ncmds;
158 uint32_t sizeofcmds;
159 uint32_t flags;
c05d9758 160} _packed;
a362a82f 161
fdb119ef 162#define MH_MAGIC 0xfeedface
a362a82f
JF
163#define MH_CIGAM 0xcefaedfe
164
3cbc6463
JF
165#define MH_MAGIC_64 0xfeedfacf
166#define MH_CIGAM_64 0xcffaedfe
167
82813bde
JF
168#define MH_DYLDLINK 0x4
169
4a864785 170#define MH_OBJECT 0x1
efd6cd4a
JF
171#define MH_EXECUTE 0x2
172#define MH_DYLIB 0x6
173#define MH_BUNDLE 0x8
174#define MH_DYLIB_STUB 0x9
a362a82f
JF
175
176struct load_command {
177 uint32_t cmd;
178 uint32_t cmdsize;
c05d9758 179} _packed;
a362a82f 180
4a57e66c
JF
181#define LC_REQ_DYLD uint32_t(0x80000000)
182
183#define LC_SEGMENT uint32_t(0x01)
184#define LC_SYMTAB uint32_t(0x02)
185#define LC_DYSYMTAB uint32_t(0x0b)
186#define LC_LOAD_DYLIB uint32_t(0x0c)
187#define LC_ID_DYLIB uint32_t(0x0d)
289ccbbc 188#define LC_SEGMENT_64 uint32_t(0x19)
4a57e66c
JF
189#define LC_UUID uint32_t(0x1b)
190#define LC_CODE_SIGNATURE uint32_t(0x1d)
191#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
192#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
c0cc1574 193#define LC_ENCRYPTION_INFO uint32_t(0x21)
4a57e66c
JF
194#define LC_DYLD_INFO uint32_t(0x22)
195#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
843aea8c 196#define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
a362a82f
JF
197
198struct dylib {
199 uint32_t name;
200 uint32_t timestamp;
201 uint32_t current_version;
202 uint32_t compatibility_version;
c05d9758 203} _packed;
a362a82f
JF
204
205struct dylib_command {
206 uint32_t cmd;
207 uint32_t cmdsize;
208 struct dylib dylib;
c05d9758 209} _packed;
a362a82f
JF
210
211struct uuid_command {
212 uint32_t cmd;
213 uint32_t cmdsize;
214 uint8_t uuid[16];
c05d9758 215} _packed;
a362a82f 216
20e7eb29
JF
217struct symtab_command {
218 uint32_t cmd;
219 uint32_t cmdsize;
220 uint32_t symoff;
221 uint32_t nsyms;
222 uint32_t stroff;
223 uint32_t strsize;
224} _packed;
225
4a57e66c
JF
226struct dyld_info_command {
227 uint32_t cmd;
228 uint32_t cmdsize;
229 uint32_t rebase_off;
230 uint32_t rebase_size;
231 uint32_t bind_off;
232 uint32_t bind_size;
233 uint32_t weak_bind_off;
234 uint32_t weak_bind_size;
235 uint32_t lazy_bind_off;
236 uint32_t lazy_bind_size;
237 uint32_t export_off;
238 uint32_t export_size;
239} _packed;
240
241struct dysymtab_command {
242 uint32_t cmd;
243 uint32_t cmdsize;
244 uint32_t ilocalsym;
245 uint32_t nlocalsym;
246 uint32_t iextdefsym;
247 uint32_t nextdefsym;
248 uint32_t iundefsym;
249 uint32_t nundefsym;
250 uint32_t tocoff;
251 uint32_t ntoc;
252 uint32_t modtaboff;
253 uint32_t nmodtab;
254 uint32_t extrefsymoff;
255 uint32_t nextrefsyms;
256 uint32_t indirectsymoff;
257 uint32_t nindirectsyms;
258 uint32_t extreloff;
259 uint32_t nextrel;
260 uint32_t locreloff;
261 uint32_t nlocrel;
262} _packed;
263
264struct dylib_table_of_contents {
265 uint32_t symbol_index;
266 uint32_t module_index;
267} _packed;
268
269struct dylib_module {
270 uint32_t module_name;
271 uint32_t iextdefsym;
272 uint32_t nextdefsym;
273 uint32_t irefsym;
274 uint32_t nrefsym;
275 uint32_t ilocalsym;
276 uint32_t nlocalsym;
277 uint32_t iextrel;
278 uint32_t nextrel;
279 uint32_t iinit_iterm;
280 uint32_t ninit_nterm;
281 uint32_t objc_module_info_addr;
282 uint32_t objc_module_info_size;
283} _packed;
284
285struct dylib_reference {
286 uint32_t isym:24;
287 uint32_t flags:8;
288} _packed;
289
290struct relocation_info {
291 int32_t r_address;
292 uint32_t r_symbolnum:24;
293 uint32_t r_pcrel:1;
294 uint32_t r_length:2;
295 uint32_t r_extern:1;
296 uint32_t r_type:4;
297} _packed;
298
299struct nlist {
300 union {
301 char *n_name;
302 int32_t n_strx;
303 } n_un;
304
305 uint8_t n_type;
306 uint8_t n_sect;
307 uint8_t n_desc;
308 uint32_t n_value;
309} _packed;
310
6e83315b
JF
311struct segment_command {
312 uint32_t cmd;
313 uint32_t cmdsize;
314 char segname[16];
315 uint32_t vmaddr;
316 uint32_t vmsize;
317 uint32_t fileoff;
318 uint32_t filesize;
319 uint32_t maxprot;
320 uint32_t initprot;
321 uint32_t nsects;
322 uint32_t flags;
429e34a5 323} _packed;
6e83315b 324
289ccbbc
JF
325struct segment_command_64 {
326 uint32_t cmd;
327 uint32_t cmdsize;
328 char segname[16];
329 uint64_t vmaddr;
330 uint64_t vmsize;
331 uint64_t fileoff;
332 uint64_t filesize;
333 uint32_t maxprot;
334 uint32_t initprot;
335 uint32_t nsects;
336 uint32_t flags;
429e34a5 337} _packed;
289ccbbc 338
6e83315b
JF
339struct section {
340 char sectname[16];
341 char segname[16];
342 uint32_t addr;
343 uint32_t size;
344 uint32_t offset;
345 uint32_t align;
346 uint32_t reloff;
347 uint32_t nreloc;
348 uint32_t flags;
349 uint32_t reserved1;
350 uint32_t reserved2;
429e34a5 351} _packed;
6e83315b 352
289ccbbc
JF
353struct section_64 {
354 char sectname[16];
355 char segname[16];
356 uint64_t addr;
357 uint64_t size;
358 uint32_t offset;
359 uint32_t align;
360 uint32_t reloff;
361 uint32_t nreloc;
362 uint32_t flags;
363 uint32_t reserved1;
364 uint32_t reserved2;
429e34a5 365} _packed;
289ccbbc 366
fdb119ef
JF
367struct linkedit_data_command {
368 uint32_t cmd;
369 uint32_t cmdsize;
370 uint32_t dataoff;
371 uint32_t datasize;
c05d9758 372} _packed;
fdb119ef 373
c0cc1574
JF
374struct encryption_info_command {
375 uint32_t cmd;
376 uint32_t cmdsize;
377 uint32_t cryptoff;
378 uint32_t cryptsize;
379 uint32_t cryptid;
380} _packed;
381
4a864785
JF
382#define BIND_OPCODE_MASK 0xf0
383#define BIND_IMMEDIATE_MASK 0x0f
384#define BIND_OPCODE_DONE 0x00
385#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
386#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
387#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
388#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
389#define BIND_OPCODE_SET_TYPE_IMM 0x50
390#define BIND_OPCODE_SET_ADDEND_SLEB 0x60
391#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
392#define BIND_OPCODE_ADD_ADDR_ULEB 0x80
393#define BIND_OPCODE_DO_BIND 0x90
394#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
395#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
396#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
397
4d4682ef
JF
398inline void get(std::streambuf &stream, void *data, size_t size) {
399 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
400}
401
402inline void put(std::streambuf &stream, const void *data, size_t size) {
403 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
404}
405
406inline void pad(std::streambuf &stream, size_t size) {
407 char padding[size];
408 memset(padding, 0, size);
409 put(stream, padding, size);
410}
411
4374152f
JF
412template <typename Type_>
413Type_ Align(Type_ value, size_t align) {
414 value += align - 1;
415 value /= align;
416 value *= align;
417 return value;
418}
419
b9652d6e
JF
420static const uint8_t PageShift_(0x0c);
421static const uint32_t PageSize_(1 << PageShift_);
422
f65c321b 423static inline uint16_t Swap_(uint16_t value) {
fdb119ef
JF
424 return
425 ((value >> 8) & 0x00ff) |
426 ((value << 8) & 0xff00);
427}
428
f65c321b 429static inline uint32_t Swap_(uint32_t value) {
fdb119ef
JF
430 value = ((value >> 8) & 0x00ff00ff) |
431 ((value << 8) & 0xff00ff00);
432 value = ((value >> 16) & 0x0000ffff) |
433 ((value << 16) & 0xffff0000);
434 return value;
435}
436
f65c321b 437static inline uint64_t Swap_(uint64_t value) {
4374152f
JF
438 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
439 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
440 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
441 return value;
442}
443
f65c321b 444static inline int16_t Swap_(int16_t value) {
fdb119ef
JF
445 return Swap_(static_cast<uint16_t>(value));
446}
447
f65c321b 448static inline int32_t Swap_(int32_t value) {
fdb119ef
JF
449 return Swap_(static_cast<uint32_t>(value));
450}
451
f65c321b 452static inline int64_t Swap_(int64_t value) {
4374152f
JF
453 return Swap_(static_cast<uint64_t>(value));
454}
455
f65c321b 456static bool little_(true);
5525a5a7 457
f65c321b 458static inline uint16_t Swap(uint16_t value) {
5525a5a7 459 return little_ ? Swap_(value) : value;
fdb119ef
JF
460}
461
f65c321b 462static inline uint32_t Swap(uint32_t value) {
5525a5a7 463 return little_ ? Swap_(value) : value;
fdb119ef
JF
464}
465
f65c321b 466static inline uint64_t Swap(uint64_t value) {
4374152f
JF
467 return little_ ? Swap_(value) : value;
468}
469
f65c321b 470static inline int16_t Swap(int16_t value) {
fdb119ef
JF
471 return Swap(static_cast<uint16_t>(value));
472}
473
f65c321b 474static inline int32_t Swap(int32_t value) {
fdb119ef
JF
475 return Swap(static_cast<uint32_t>(value));
476}
477
f65c321b 478static inline int64_t Swap(int64_t value) {
4374152f
JF
479 return Swap(static_cast<uint64_t>(value));
480}
481
6e83315b
JF
482template <typename Target_>
483class Pointer;
484
4d4682ef 485class Swapped {
0a033524 486 protected:
a362a82f
JF
487 bool swapped_;
488
4d4682ef 489 Swapped() :
0a033524
JF
490 swapped_(false)
491 {
492 }
493
4d4682ef
JF
494 public:
495 Swapped(bool swapped) :
496 swapped_(swapped)
497 {
a362a82f
JF
498 }
499
4d4682ef
JF
500 template <typename Type_>
501 Type_ Swap(Type_ value) const {
4374152f
JF
502 return swapped_ ? Swap_(value) : value;
503 }
4d4682ef 504};
4374152f 505
4d4682ef
JF
506class Data :
507 public Swapped
508{
509 private:
510 void *base_;
511 size_t size_;
a362a82f 512
4d4682ef
JF
513 public:
514 Data(void *base, size_t size) :
515 base_(base),
516 size_(size)
517 {
4374152f
JF
518 }
519
0a033524
JF
520 void *GetBase() const {
521 return base_;
522 }
a362a82f 523
0a033524
JF
524 size_t GetSize() const {
525 return size_;
526 }
527};
a362a82f 528
0a033524
JF
529class MachHeader :
530 public Data
531{
532 private:
533 bool bits64_;
534
535 struct mach_header *mach_header_;
536 struct load_command *load_command_;
537
538 public:
539 MachHeader(void *base, size_t size) :
540 Data(base, size)
541 {
542 mach_header_ = (mach_header *) base;
a362a82f 543
3cbc6463
JF
544 switch (Swap(mach_header_->magic)) {
545 case MH_CIGAM:
546 swapped_ = !swapped_;
547 case MH_MAGIC:
548 bits64_ = false;
549 break;
550
551 case MH_CIGAM_64:
552 swapped_ = !swapped_;
553 case MH_MAGIC_64:
554 bits64_ = true;
555 break;
556
557 default:
558 _assert(false);
559 }
560
561 void *post = mach_header_ + 1;
562 if (bits64_)
563 post = (uint32_t *) post + 1;
564 load_command_ = (struct load_command *) post;
a362a82f
JF
565
566 _assert(
567 Swap(mach_header_->filetype) == MH_EXECUTE ||
568 Swap(mach_header_->filetype) == MH_DYLIB ||
569 Swap(mach_header_->filetype) == MH_BUNDLE
570 );
571 }
572
4d4682ef
JF
573 bool Bits64() const {
574 return bits64_;
575 }
576
afbb7c8e
JF
577 struct mach_header *operator ->() const {
578 return mach_header_;
579 }
580
4374152f
JF
581 operator struct mach_header *() const {
582 return mach_header_;
583 }
584
04802ab1
JF
585 uint32_t GetCPUType() const {
586 return Swap(mach_header_->cputype);
587 }
588
4374152f 589 uint32_t GetCPUSubtype() const {
04802ab1
JF
590 return Swap(mach_header_->cpusubtype) & 0xff;
591 }
592
4374152f
JF
593 struct load_command *GetLoadCommand() const {
594 return load_command_;
595 }
596
0a033524 597 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
598 std::vector<struct load_command *> load_commands;
599
3cbc6463 600 struct load_command *load_command = load_command_;
a362a82f
JF
601 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
602 load_commands.push_back(load_command);
603 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
604 }
605
606 return load_commands;
607 }
6e83315b 608
6f340f51 609 std::vector<segment_command *> GetSegments(const char *segment_name) const {
6e83315b
JF
610 std::vector<struct segment_command *> segment_commands;
611
289ccbbc 612 _foreach (load_command, GetLoadCommands()) {
0a033524
JF
613 if (Swap(load_command->cmd) == LC_SEGMENT) {
614 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
615 if (strncmp(segment_command->segname, segment_name, 16) == 0)
616 segment_commands.push_back(segment_command);
617 }
289ccbbc
JF
618 }
619
620 return segment_commands;
621 }
622
4374152f 623 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
289ccbbc
JF
624 std::vector<struct segment_command_64 *> segment_commands;
625
626 _foreach (load_command, GetLoadCommands()) {
627 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
628 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
629 if (strncmp(segment_command->segname, segment_name, 16) == 0)
630 segment_commands.push_back(segment_command);
631 }
632 }
6e83315b
JF
633
634 return segment_commands;
635 }
636
6f340f51 637 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
6e83315b
JF
638 std::vector<section *> sections;
639
640 _foreach (segment, GetSegments(segment_name)) {
0a033524 641 section *section = (struct section *) (segment + 1);
6e83315b
JF
642
643 uint32_t sect;
0a033524 644 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
645 if (strncmp(section->sectname, section_name, 16) == 0)
646 sections.push_back(section);
647 ++section;
648 }
649 }
650
651 return sections;
652 }
653
654 template <typename Target_>
0a033524 655 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
656 load_command *load_command = (struct load_command *) (mach_header_ + 1);
657 uint32_t cmd;
658
659 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
660 if (Swap(load_command->cmd) == LC_SEGMENT) {
661 segment_command *segment_command = (struct segment_command *) load_command;
662 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
663 goto next_command;
664
665 section *sections = (struct section *) (segment_command + 1);
666
667 uint32_t sect;
668 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
669 section *section = &sections[sect];
670 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
671 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
672 //printf("0x%.8x %s\n", address, segment_command->segname);
673 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
674 }
675 }
676 }
677
678 next_command:
679 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
680 }
681
682 return Pointer<Target_>(this);
683 }
684
685 template <typename Target_>
686 Pointer<Target_> GetOffset(uint32_t offset) {
687 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
688 }
689};
690
289ccbbc
JF
691class FatMachHeader :
692 public MachHeader
693{
694 private:
695 fat_arch *fat_arch_;
696
697 public:
698 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
699 MachHeader(base, size),
700 fat_arch_(fat_arch)
701 {
702 }
703
704 fat_arch *GetFatArch() const {
705 return fat_arch_;
706 }
707};
708
0a033524
JF
709class FatHeader :
710 public Data
711{
712 private:
713 fat_header *fat_header_;
289ccbbc 714 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
715
716 public:
717 FatHeader(void *base, size_t size) :
718 Data(base, size)
719 {
720 fat_header_ = reinterpret_cast<struct fat_header *>(base);
721
722 if (Swap(fat_header_->magic) == FAT_CIGAM) {
723 swapped_ = !swapped_;
724 goto fat;
725 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
726 fat_header_ = NULL;
289ccbbc 727 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
728 } else fat: {
729 size_t fat_narch = Swap(fat_header_->nfat_arch);
730 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
731 size_t arch;
732 for (arch = 0; arch != fat_narch; ++arch) {
733 uint32_t arch_offset = Swap(fat_arch->offset);
734 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 735 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
736 ++fat_arch;
737 }
738 }
739 }
740
289ccbbc 741 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
742 return mach_headers_;
743 }
20e7eb29
JF
744
745 bool IsFat() const {
746 return fat_header_ != NULL;
747 }
6b38c173
JF
748
749 struct fat_header *operator ->() const {
750 return fat_header_;
751 }
4374152f
JF
752
753 operator struct fat_header *() const {
754 return fat_header_;
755 }
0a033524
JF
756};
757
6e83315b
JF
758template <typename Target_>
759class Pointer {
760 private:
0a033524 761 const MachHeader *framework_;
6e83315b
JF
762 const Target_ *pointer_;
763
764 public:
0a033524 765 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
766 framework_(framework),
767 pointer_(pointer)
768 {
769 }
770
771 operator const Target_ *() const {
772 return pointer_;
773 }
774
775 const Target_ *operator ->() const {
776 return pointer_;
777 }
778
779 Pointer<Target_> &operator ++() {
780 ++pointer_;
781 return *this;
782 }
783
784 template <typename Value_>
785 Value_ Swap(Value_ value) {
786 return framework_->Swap(value);
787 }
a362a82f
JF
788};
789
4d4682ef
JF
790#define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
791#define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
792#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
793#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
794#define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
795#define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
796#define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
797#define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
c05d9758 798
4d4682ef
JF
799#define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
800#define CSSLOT_INFOSLOT uint32_t(0x00001)
801#define CSSLOT_REQUIREMENTS uint32_t(0x00002)
802#define CSSLOT_RESOURCEDIR uint32_t(0x00003)
803#define CSSLOT_APPLICATION uint32_t(0x00004)
804#define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
805
806#define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
807
808#define CS_HASHTYPE_SHA1 1
fdb119ef
JF
809
810struct BlobIndex {
811 uint32_t type;
812 uint32_t offset;
c05d9758 813} _packed;
fdb119ef 814
c05d9758 815struct Blob {
fdb119ef
JF
816 uint32_t magic;
817 uint32_t length;
c05d9758
JF
818} _packed;
819
820struct SuperBlob {
821 struct Blob blob;
fdb119ef
JF
822 uint32_t count;
823 struct BlobIndex index[];
c05d9758 824} _packed;
fdb119ef
JF
825
826struct CodeDirectory {
fdb119ef
JF
827 uint32_t version;
828 uint32_t flags;
829 uint32_t hashOffset;
830 uint32_t identOffset;
831 uint32_t nSpecialSlots;
832 uint32_t nCodeSlots;
833 uint32_t codeLimit;
834 uint8_t hashSize;
835 uint8_t hashType;
836 uint8_t spare1;
837 uint8_t pageSize;
838 uint32_t spare2;
c05d9758 839} _packed;
fdb119ef 840
a362a82f
JF
841extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
842
f65c321b 843static void sha1(uint8_t *hash, const void *data, size_t size) {
4d4682ef 844 SHA1(static_cast<const uint8_t *>(data), size, hash);
fdb119ef
JF
845}
846
0a033524 847struct CodesignAllocation {
4374152f
JF
848 FatMachHeader mach_header_;
849 uint32_t offset_;
850 uint32_t size_;
4d4682ef 851 uint32_t limit_;
4374152f 852 uint32_t alloc_;
e4b7adc1 853 uint32_t align_;
4374152f 854
e0098838 855 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
4374152f
JF
856 mach_header_(mach_header),
857 offset_(offset),
858 size_(size),
4d4682ef 859 limit_(limit),
e4b7adc1
JF
860 alloc_(alloc),
861 align_(align)
0a033524
JF
862 {
863 }
864};
865
dede6121
JF
866class File {
867 private:
868 int file_;
869
870 public:
871 File() :
872 file_(-1)
873 {
874 }
875
876 ~File() {
877 if (file_ != -1)
878 _syscall(close(file_));
879 }
880
cad40c43 881 void open(const char *path, int flags) {
dede6121 882 _assert(file_ == -1);
fc7a76da 883 file_ = _syscall(::open(path, flags));
dede6121
JF
884 }
885
886 int file() const {
887 return file_;
888 }
889};
890
891class Map {
892 private:
893 File file_;
894 void *data_;
895 size_t size_;
896
897 void clear() {
898 if (data_ == NULL)
899 return;
900 _syscall(munmap(data_, size_));
901 data_ = NULL;
902 size_ = 0;
903 }
904
905 public:
906 Map() :
907 data_(NULL),
908 size_(0)
909 {
910 }
911
d4187e53 912 Map(const std::string &path, int oflag, int pflag, int mflag) :
cad40c43
JF
913 Map()
914 {
915 open(path, oflag, pflag, mflag);
916 }
917
d4187e53 918 Map(const std::string &path, bool edit) :
cad40c43
JF
919 Map()
920 {
921 open(path, edit);
dede6121
JF
922 }
923
924 ~Map() {
925 clear();
926 }
927
fac3d3e3
JF
928 bool empty() const {
929 return data_ == NULL;
930 }
931
d4187e53 932 void open(const std::string &path, int oflag, int pflag, int mflag) {
dede6121
JF
933 clear();
934
d4187e53 935 file_.open(path.c_str(), oflag);
dede6121
JF
936 int file(file_.file());
937
938 struct stat stat;
939 _syscall(fstat(file, &stat));
940 size_ = stat.st_size;
941
fc7a76da 942 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
cad40c43
JF
943 }
944
d4187e53 945 void open(const std::string &path, bool edit) {
cad40c43
JF
946 if (edit)
947 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
948 else
949 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
950 }
951
952 void *data() const {
953 return data_;
954 }
955
956 size_t size() const {
957 return size_;
958 }
f4b2df35
JF
959
960 operator std::string() const {
961 return std::string(static_cast<char *>(data_), size_);
962 }
dede6121
JF
963};
964
a0c715e9
JF
965namespace ldid {
966
ffdd1183
JF
967static void Allocate(const 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) {
968 FatHeader source(const_cast<void *>(idata), isize);
f4b2df35
JF
969
970 size_t offset(0);
971 if (source.IsFat())
972 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
973
974 std::vector<CodesignAllocation> allocations;
975 _foreach (mach_header, source.GetMachHeaders()) {
976 struct linkedit_data_command *signature(NULL);
977 struct symtab_command *symtab(NULL);
978
979 _foreach (load_command, mach_header.GetLoadCommands()) {
980 uint32_t cmd(mach_header.Swap(load_command->cmd));
981 if (false);
982 else if (cmd == LC_CODE_SIGNATURE)
983 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
984 else if (cmd == LC_SYMTAB)
985 symtab = reinterpret_cast<struct symtab_command *>(load_command);
986 }
987
988 size_t size;
989 if (signature == NULL)
990 size = mach_header.GetSize();
991 else {
992 size = mach_header.Swap(signature->dataoff);
993 _assert(size <= mach_header.GetSize());
994 }
995
996 if (symtab != NULL) {
997 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
998 _assert(end <= size);
999 _assert(end >= size - 0x10);
1000 size = end;
1001 }
1002
e0098838 1003 size_t alloc(allocate(size));
f4b2df35
JF
1004
1005 auto *fat_arch(mach_header.GetFatArch());
1006 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
1007 offset = Align(offset, 1 << align);
1008
4d4682ef
JF
1009 uint32_t limit(size);
1010 if (alloc != 0)
1011 limit = Align(limit, 0x10);
1012
e0098838 1013 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
f4b2df35 1014 offset += size + alloc;
b9652d6e 1015 offset = Align(offset, 0x10);
f4b2df35
JF
1016 }
1017
4d4682ef
JF
1018 size_t position(0);
1019
1020 if (source.IsFat()) {
1021 fat_header fat_header;
1022 fat_header.magic = Swap(FAT_MAGIC);
1023 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1024 put(output, &fat_header, sizeof(fat_header));
1025 position += sizeof(fat_header);
1026
1027 _foreach (allocation, allocations) {
1028 auto &mach_header(allocation.mach_header_);
1029
1030 fat_arch fat_arch;
1031 fat_arch.cputype = Swap(mach_header->cputype);
1032 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1033 fat_arch.offset = Swap(allocation.offset_);
1034 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1035 fat_arch.align = Swap(allocation.align_);
1036 put(output, &fat_arch, sizeof(fat_arch));
1037 position += sizeof(fat_arch);
1038 }
f4b2df35
JF
1039 }
1040
1041 _foreach (allocation, allocations) {
4d4682ef 1042 auto &mach_header(allocation.mach_header_);
f4b2df35 1043
4d4682ef
JF
1044 pad(output, allocation.offset_ - position);
1045 position = allocation.offset_;
f4b2df35 1046
4d4682ef 1047 std::vector<std::string> commands;
f4b2df35 1048
4d4682ef
JF
1049 _foreach (load_command, mach_header.GetLoadCommands()) {
1050 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1051
a7f01a65 1052 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1053 case LC_CODE_SIGNATURE:
1054 continue;
1055 break;
1056
1057 case LC_SEGMENT: {
1058 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1059 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1060 break;
1061 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1062 segment_command->filesize = size;
b9652d6e 1063 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1064 } break;
1065
1066 case LC_SEGMENT_64: {
1067 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1068 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1069 break;
1070 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1071 segment_command->filesize = size;
b9652d6e 1072 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1073 } break;
1074 }
f4b2df35 1075
4d4682ef 1076 commands.push_back(copy);
f4b2df35
JF
1077 }
1078
e0098838 1079 if (allocation.alloc_ != 0) {
4d4682ef
JF
1080 linkedit_data_command signature;
1081 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1082 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1083 signature.dataoff = mach_header.Swap(allocation.limit_);
1084 signature.datasize = mach_header.Swap(allocation.alloc_);
1085 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1086 }
f4b2df35 1087
4d4682ef 1088 size_t begin(position);
f4b2df35 1089
4d4682ef
JF
1090 uint32_t after(0);
1091 _foreach(command, commands)
1092 after += command.size();
f4b2df35 1093
4d4682ef 1094 std::stringbuf altern;
f4b2df35 1095
4d4682ef
JF
1096 struct mach_header header(*mach_header);
1097 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1098 header.sizeofcmds = mach_header.Swap(after);
1099 put(output, &header, sizeof(header));
1100 put(altern, &header, sizeof(header));
1101 position += sizeof(header);
f4b2df35 1102
4d4682ef
JF
1103 if (mach_header.Bits64()) {
1104 auto pad(mach_header.Swap(uint32_t(0)));
1105 put(output, &pad, sizeof(pad));
1106 put(altern, &pad, sizeof(pad));
1107 position += sizeof(pad);
1108 }
f4b2df35 1109
4d4682ef
JF
1110 _foreach(command, commands) {
1111 put(output, command.data(), command.size());
1112 put(altern, command.data(), command.size());
1113 position += command.size();
1114 }
f4b2df35 1115
4d4682ef
JF
1116 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1117 if (before > after) {
1118 pad(output, before - after);
1119 pad(altern, before - after);
1120 position += before - after;
1121 }
f4b2df35 1122
4d4682ef 1123 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1124
4d4682ef
JF
1125 std::string overlap(altern.str());
1126 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1127
4d4682ef
JF
1128 put(output, top + (position - begin), allocation.size_ - (position - begin));
1129 position = begin + allocation.size_;
f4b2df35 1130
4d4682ef
JF
1131 pad(output, allocation.limit_ - allocation.size_);
1132 position += allocation.limit_ - allocation.size_;
f4b2df35 1133
67205335
JF
1134 size_t saved(save(output, allocation.limit_, overlap, top));
1135 if (allocation.alloc_ > saved)
1136 pad(output, allocation.alloc_ - saved);
1137 position += allocation.alloc_;
e0098838
JF
1138 }
1139}
f4b2df35 1140
a0c715e9
JF
1141}
1142
efad8a44
JF
1143typedef std::map<uint32_t, std::string> Blobs;
1144
bb591e2b
JF
1145static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1146 auto value(buffer.str());
1147 std::swap(blobs[slot], value);
1148}
1149
8f310b91
JF
1150static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1151 auto value(buffer.str());
1152 Blob blob;
1153 blob.magic = Swap(magic);
1154 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1155 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1156 std::swap(blobs[slot], value);
efad8a44
JF
1157}
1158
1159static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1160 size_t total(0);
1161 _foreach (blob, blobs)
1162 total += blob.second.size();
1163
1164 struct SuperBlob super;
1165 super.blob.magic = Swap(magic);
1166 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1167 super.count = Swap(uint32_t(blobs.size()));
1168 put(output, &super, sizeof(super));
1169
1170 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1171
1172 _foreach (blob, blobs) {
1173 BlobIndex index;
1174 index.type = Swap(blob.first);
1175 index.offset = Swap(uint32_t(offset));
1176 put(output, &index, sizeof(index));
1177 offset += blob.second.size();
1178 }
1179
1180 _foreach (blob, blobs)
1181 put(output, blob.second.data(), blob.second.size());
1182
1183 return offset;
1184}
1185
30c64adb
JF
1186class Buffer {
1187 private:
1188 BIO *bio_;
1189
1190 public:
1191 Buffer(BIO *bio) :
1192 bio_(bio)
1193 {
1194 _assert(bio_ != NULL);
1195 }
1196
1197 Buffer() :
1198 bio_(BIO_new(BIO_s_mem()))
1199 {
1200 }
1201
1202 Buffer(const char *data, size_t size) :
1203 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1204 {
1205 }
1206
1207 Buffer(const std::string &data) :
1208 Buffer(data.data(), data.size())
1209 {
1210 }
1211
1212 Buffer(PKCS7 *pkcs) :
1213 Buffer()
1214 {
1215 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1216 }
1217
1218 ~Buffer() {
1219 BIO_free_all(bio_);
1220 }
1221
1222 operator BIO *() const {
1223 return bio_;
1224 }
1225
1226 explicit operator std::string() const {
1227 char *data;
1228 auto size(BIO_get_mem_data(bio_, &data));
1229 return std::string(data, size);
1230 }
1231};
1232
1233class Stuff {
1234 private:
1235 PKCS12 *value_;
1236 EVP_PKEY *key_;
1237 X509 *cert_;
1238 STACK_OF(X509) *ca_;
1239
1240 public:
1241 Stuff(BIO *bio) :
1242 value_(d2i_PKCS12_bio(bio, NULL)),
1243 ca_(NULL)
1244 {
1245 _assert(value_ != NULL);
1246 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1247 _assert(key_ != NULL);
1248 _assert(cert_ != NULL);
1249 }
1250
1251 Stuff(const std::string &data) :
1252 Stuff(Buffer(data))
1253 {
1254 }
1255
1256 ~Stuff() {
1257 sk_X509_pop_free(ca_, X509_free);
1258 X509_free(cert_);
1259 EVP_PKEY_free(key_);
1260 PKCS12_free(value_);
1261 }
1262
1263 operator PKCS12 *() const {
1264 return value_;
1265 }
1266
1267 operator EVP_PKEY *() const {
1268 return key_;
1269 }
1270
1271 operator X509 *() const {
1272 return cert_;
1273 }
1274
1275 operator STACK_OF(X509) *() const {
1276 return ca_;
1277 }
1278};
1279
1280class Signature {
1281 private:
1282 PKCS7 *value_;
1283
1284 public:
1285 Signature(const Stuff &stuff, const Buffer &data) :
1286 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1287 {
1288 _assert(value_ != NULL);
1289 }
1290
1291 ~Signature() {
1292 PKCS7_free(value_);
1293 }
1294
1295 operator PKCS7 *() const {
1296 return value_;
1297 }
1298};
1299
23c11ee8
JF
1300class NullBuffer :
1301 public std::streambuf
1302{
1303 public:
1304 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1305 return size;
1306 }
1307
1308 virtual int_type overflow(int_type next) {
1309 return next;
1310 }
1311};
1312
1313class HashBuffer :
1314 public std::streambuf
1315{
1316 private:
1317 std::vector<char> &hash_;
1318 SHA_CTX context_;
1319
1320 public:
1321 HashBuffer(std::vector<char> &hash) :
1322 hash_(hash)
1323 {
1324 SHA1_Init(&context_);
1325 }
1326
1327 ~HashBuffer() {
1328 hash_.resize(SHA_DIGEST_LENGTH);
1329 SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
1330 }
1331
1332 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1333 SHA1_Update(&context_, data, size);
1334 return size;
1335 }
1336
1337 virtual int_type overflow(int_type next) {
1338 if (next == traits_type::eof())
1339 return sync();
1340 char value(next);
1341 xsputn(&value, 1);
1342 return next;
1343 }
1344};
1345
1346class HashProxy :
1347 public HashBuffer
1348{
1349 private:
1350 std::streambuf &buffer_;
1351
1352 public:
1353 HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
1354 HashBuffer(hash),
1355 buffer_(buffer)
1356 {
1357 }
1358
1359 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1360 _assert(HashBuffer::xsputn(data, size) == size);
1361 return buffer_.sputn(data, size);
1362 }
1363};
1364
1365static bool Starts(const std::string &lhs, const std::string &rhs) {
1366 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1367}
1368
1369class Split {
1370 public:
1371 std::string dir;
1372 std::string base;
1373
1374 Split(const std::string &path) {
1375 size_t slash(path.rfind('/'));
1376 if (slash == std::string::npos)
1377 base = path;
1378 else {
1379 dir = path.substr(0, slash + 1);
1380 base = path.substr(slash + 1);
1381 }
1382 }
1383};
1384
1385static void mkdir_p(const std::string &path) {
1386 if (path.empty())
1387 return;
1388 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1389 return;
1390 auto slash(path.rfind('/', path.size() - 1));
1391 if (slash == std::string::npos)
1392 return;
1393 mkdir_p(path.substr(0, slash));
1394}
1395
1396static std::string Temporary(std::filebuf &file, const Split &split) {
1397 std::string temp(split.dir + ".ldid." + split.base);
1398 mkdir_p(split.dir);
1399 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1400 return temp;
1401}
1402
d4187e53
JF
1403static void Commit(const std::string &path, const std::string &temp) {
1404 struct stat info;
23c11ee8 1405 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
d4187e53 1406#ifndef __WIN32__
23c11ee8 1407 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
d4187e53 1408#endif
23c11ee8
JF
1409 _syscall(chmod(temp.c_str(), info.st_mode));
1410 }
1411
d4187e53
JF
1412 _syscall(rename(temp.c_str(), path.c_str()));
1413}
1414
a0c715e9 1415namespace ldid {
e57b1f91 1416
ffdd1183 1417void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
a0c715e9 1418 Allocate(idata, isize, output, fun([&](size_t size) -> size_t {
e0098838 1419 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1420
e0098838 1421 uint32_t special(0);
f4b2df35 1422
e0098838
JF
1423 special = std::max(special, CSSLOT_REQUIREMENTS);
1424 alloc += sizeof(struct BlobIndex);
1425 alloc += 0xc;
f4b2df35 1426
faa1b1f8 1427 if (!entitlements.empty()) {
e0098838
JF
1428 special = std::max(special, CSSLOT_ENTITLEMENTS);
1429 alloc += sizeof(struct BlobIndex);
1430 alloc += sizeof(struct Blob);
1431 alloc += entitlements.size();
1432 }
f4b2df35 1433
e0098838
JF
1434 special = std::max(special, CSSLOT_CODEDIRECTORY);
1435 alloc += sizeof(struct BlobIndex);
1436 alloc += sizeof(struct Blob);
1437 alloc += sizeof(struct CodeDirectory);
ffdd1183 1438 alloc += identifier.size() + 1;
f4b2df35 1439
30c64adb
JF
1440 if (!key.empty()) {
1441 alloc += sizeof(struct BlobIndex);
1442 alloc += sizeof(struct Blob);
1443 // XXX: this is just a "sufficiently large number"
1444 alloc += 0x3000;
1445 }
1446
e57b1f91
JF
1447 _foreach (slot, slots)
1448 special = std::max(special, slot.first);
1449
b9652d6e 1450 uint32_t normal((size + PageSize_ - 1) / PageSize_);
e0098838
JF
1451 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1452 return alloc;
1453 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
efad8a44 1454 Blobs blobs;
f4b2df35 1455
e0098838
JF
1456 if (true) {
1457 std::stringbuf data;
f4b2df35 1458
bb591e2b
JF
1459 Blobs requirements;
1460 put(data, CSMAGIC_REQUIREMENTS, requirements);
4d4682ef 1461
bb591e2b 1462 insert(blobs, CSSLOT_REQUIREMENTS, data);
e0098838 1463 }
4d4682ef 1464
faa1b1f8 1465 if (!entitlements.empty()) {
e0098838 1466 std::stringbuf data;
e0098838 1467 put(data, entitlements.data(), entitlements.size());
8f310b91 1468 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
e0098838
JF
1469 }
1470
1471 if (true) {
1472 std::stringbuf data;
1473
1474 uint32_t special(0);
1475 _foreach (blob, blobs)
1476 special = std::max(special, blob.first);
e57b1f91
JF
1477 _foreach (slot, slots)
1478 special = std::max(special, slot.first);
b9652d6e 1479 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
e0098838 1480
e0098838
JF
1481 CodeDirectory directory;
1482 directory.version = Swap(uint32_t(0x00020001));
1483 directory.flags = Swap(uint32_t(0));
ffdd1183 1484 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + SHA_DIGEST_LENGTH * special));
8f310b91 1485 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
e0098838
JF
1486 directory.nSpecialSlots = Swap(special);
1487 directory.codeLimit = Swap(uint32_t(limit));
1488 directory.nCodeSlots = Swap(normal);
1489 directory.hashSize = SHA_DIGEST_LENGTH;
1490 directory.hashType = CS_HASHTYPE_SHA1;
1491 directory.spare1 = 0x00;
b9652d6e 1492 directory.pageSize = PageShift_;
e0098838
JF
1493 directory.spare2 = Swap(uint32_t(0));
1494 put(data, &directory, sizeof(directory));
1495
ffdd1183 1496 put(data, identifier.c_str(), identifier.size() + 1);
e0098838
JF
1497
1498 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1499 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1500
1501 memset(storage, 0, sizeof(*storage) * special);
4d4682ef
JF
1502
1503 _foreach (blob, blobs) {
e0098838
JF
1504 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1505 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
4d4682ef 1506 }
f4b2df35 1507
e57b1f91
JF
1508 _foreach (slot, slots) {
1509 _assert(sizeof(*hashes) == slot.second.size());
1510 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1511 }
1512
e0098838
JF
1513 if (normal != 1)
1514 for (size_t i = 0; i != normal - 1; ++i)
b9652d6e 1515 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
e0098838 1516 if (normal != 0)
b9652d6e 1517 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
f4b2df35 1518
e0098838
JF
1519 put(data, storage, sizeof(storage));
1520
8f310b91 1521 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
f4b2df35 1522 }
e0098838 1523
30c64adb
JF
1524 if (!key.empty()) {
1525 std::stringbuf data;
1526 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1527
1528 Stuff stuff(key);
1529 Buffer bio(sign);
1530
1531 Signature signature(stuff, sign);
1532 Buffer result(signature);
1533 std::string value(result);
1534 put(data, value.data(), value.size());
1535
1536 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1537 }
1538
efad8a44 1539 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
e0098838
JF
1540 }));
1541}
1542
a0c715e9
JF
1543static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1544 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
e0098838
JF
1545 return 0;
1546 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1547 return 0;
1548 }));
f4b2df35
JF
1549}
1550
23c11ee8
JF
1551std::string DiskFolder::Path(const std::string &path) {
1552 return path_ + "/" + path;
1553}
1554
1555DiskFolder::DiskFolder(const std::string &path) :
1556 path_(path)
1557{
1558}
1559
1560DiskFolder::~DiskFolder() {
1561 if (!std::uncaught_exception())
1562 for (const auto &commit : commit_)
1563 Commit(commit.first, commit.second);
1564}
1565
1566void DiskFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1567 std::filebuf save;
1568 auto from(Path(path));
1569 commit_[from] = Temporary(save, from);
1570 code(save);
1571}
1572
1573bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1574 std::filebuf data;
1575 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1576 if (result == NULL)
1577 return false;
1578 _assert(result == &data);
1579 code(data);
1580 return true;
1581}
1582
1583void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1584 auto root(Path(path));
1585
1586 FTS *fts(fts_open((char *[]) {const_cast<char *>(root.c_str()), NULL}, FTS_PHYSICAL | FTS_NOCHDIR, NULL));
1587 _assert(fts != NULL);
1588 _scope({ fts_close(fts); });
1589
1590 while (FTSENT *entry = fts_read(fts)) {
1591 _assert(entry->fts_pathlen >= root.size());
1592 _assert(strncmp(entry->fts_path, root.c_str(), root.size()) == 0);
1593 if (entry->fts_pathlen == root.size())
1594 continue;
1595
1596 _assert(entry->fts_path[root.size()] == '/');
1597 std::string name(entry->fts_path + root.size() + 1);
1598
1599 if (Starts(Split(name).base, ".ldid."))
1600 continue;
1601
1602 switch (auto info = entry->fts_info) {
1603 case FTS_D:
1604 case FTS_DP:
1605 break;
1606
1607 case FTS_F: {
1608 code(name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1609 std::string access(path + name);
1610 _assert_(Open(access, fun([&](std::streambuf &data) {
1611 NullBuffer save;
1612 code(data, save);
1613 })), "open(): %s", access.c_str());
1614 }));
1615 } break;
1616
1617 default:
1618 _assert_(false, "fts_info=%u", info);
1619 }
1620 }
1621}
1622
1623SubFolder::SubFolder(Folder *parent, const std::string &path) :
1624 parent_(parent),
1625 path_(path)
1626{
1627}
1628
1629void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1630 return parent_->Save(path_ + path, code);
1631}
1632
1633bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1634 return parent_->Open(path_ + path, code);
1635}
1636
1637void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1638 return parent_->Find(path_ + path, code);
1639}
1640
1641static size_t copy(std::streambuf &source, std::streambuf &target) {
1642 size_t total(0);
1643 for (;;) {
1644 char data[4096];
1645 size_t writ(source.sgetn(data, sizeof(data)));
1646 if (writ == 0)
1647 break;
1648 _assert(target.sputn(data, writ) == writ);
1649 total += writ;
1650 }
1651 return total;
1652}
1653
1654static PList::Structure *plist(const std::string &data) {
1655 if (!Starts(data, "bplist00"))
1656 return PList::Structure::FromXml(data);
1657 std::vector<char> bytes(data.data(), data.data() + data.size());
1658 return PList::Structure::FromBin(bytes);
1659}
1660
1661static void plist_d(std::streambuf &buffer, const Functor<void (PList::Dictionary *)> &code) {
1662 std::stringbuf data;
1663 copy(buffer, data);
1664 PList::Structure *structure(plist(data.str()));
1665 _scope({ delete structure; });
1666 auto dictionary(dynamic_cast<PList::Dictionary *>(structure));
1667 _assert(dictionary != NULL);
1668 code(dictionary);
1669}
1670
1671static std::string plist_s(PList::Node *node) {
1672 auto value(dynamic_cast<PList::String *>(node));
1673 _assert(value != NULL);
1674 return value->GetValue();
1675}
1676
1677enum Mode {
1678 NoMode,
1679 OptionalMode,
1680 OmitMode,
1681 NestedMode,
1682 TopMode,
1683};
1684
1685class Expression {
1686 private:
1687 regex_t regex_;
1688
1689 public:
1690 Expression(const std::string &code) {
1691 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1692 }
1693
1694 ~Expression() {
1695 regfree(&regex_);
1696 }
1697
1698 bool operator ()(const std::string &data) const {
1699 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1700 if (value == REG_NOMATCH)
1701 return false;
1702 _assert_(value == 0, "regexec()");
1703 return true;
1704 }
1705};
1706
1707struct Rule {
1708 unsigned weight_;
1709 Mode mode_;
1710 std::string code_;
1711
1712 mutable std::auto_ptr<Expression> regex_;
1713
1714 Rule(unsigned weight, Mode mode, const std::string &code) :
1715 weight_(weight),
1716 mode_(mode),
1717 code_(code)
1718 {
1719 }
1720
1721 Rule(const Rule &rhs) :
1722 weight_(rhs.weight_),
1723 mode_(rhs.mode_),
1724 code_(rhs.code_)
1725 {
1726 }
1727
1728 void Compile() const {
1729 regex_.reset(new Expression(code_));
1730 }
1731
1732 bool operator ()(const std::string &data) const {
1733 _assert(regex_.get() != NULL);
1734 return (*regex_)(data);
1735 }
1736
1737 bool operator <(const Rule &rhs) const {
1738 if (weight_ > rhs.weight_)
1739 return true;
1740 if (weight_ < rhs.weight_)
1741 return false;
1742 return mode_ > rhs.mode_;
1743 }
1744};
1745
1746struct RuleCode {
1747 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1748 return lhs->code_ < rhs->code_;
1749 }
1750};
1751
1752std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, std::vector<char>> &remote) {
1753 std::string executable;
1754 std::string identifier;
1755
1756 static const std::string info("Info.plist");
1757
1758 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
1759 plist_d(buffer, fun([&](PList::Dictionary *dictionary) {
1760 executable = plist_s(((*dictionary)["CFBundleExecutable"]));
1761 identifier = plist_s(((*dictionary)["CFBundleIdentifier"]));
1762 }));
1763 })), "open(): Info.plist");
1764
1765 std::map<std::string, std::multiset<Rule>> versions;
1766
1767 auto &rules1(versions[""]);
1768 auto &rules2(versions["2"]);
1769
1770 static const std::string signature("_CodeSignature/CodeResources");
1771
1772 folder.Open(signature, fun([&](std::streambuf &buffer) {
1773 plist_d(buffer, fun([&](PList::Dictionary *dictionary) {
1774 // XXX: maybe attempt to preserve existing rules
1775 }));
1776 }));
1777
1778 if (true) {
1779 rules1.insert(Rule{1, NoMode, "^"});
1780 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1781 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1782 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1783 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1784 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1785 }
1786
1787 if (true) {
1788 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1789 rules2.insert(Rule{20, NoMode, "^"});
1790 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1791 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1792 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1793 rules2.insert(Rule{1, NoMode, "^.*"});
1794 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1795 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1796 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1797 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1798 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1799 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1800 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1801 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1802 }
1803
1804 std::map<std::string, std::vector<char>> local;
1805
1806 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1807
1808 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1809 if (!nested(name))
1810 return;
1811 auto bundle(root + Split(name).dir);
1812 SubFolder subfolder(&folder, bundle);
1813 Bundle(bundle, subfolder, key, local);
1814 }));
1815
1816 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1817 if (name == executable || name == signature)
1818 return;
1819
1820 auto &hash(local[name]);
1821 if (!hash.empty())
1822 return;
1823
1824 code(fun([&](std::streambuf &data, std::streambuf &save) {
1825 HashProxy proxy(hash, save);
1826 copy(data, proxy);
1827 }));
1828
1829 _assert(hash.size() == SHA_DIGEST_LENGTH);
1830 }));
1831
1832 PList::Dictionary plist;
1833
1834 for (const auto &version : versions) {
1835 PList::Dictionary files;
1836
1837 for (const auto &rule : version.second)
1838 rule.Compile();
1839
1840 for (const auto &hash : local)
1841 for (const auto &rule : version.second)
1842 if (rule(hash.first)) {
1843 if (rule.mode_ == NoMode)
1844 files.Set(hash.first, PList::Data(hash.second));
1845 else if (rule.mode_ == OptionalMode) {
1846 PList::Dictionary entry;
1847 entry.Set("hash", PList::Data(hash.second));
1848 entry.Set("optional", PList::Boolean(true));
1849 files.Set(hash.first, entry);
1850 }
1851
1852 break;
1853 }
1854
1855 plist.Set("files" + version.first, files);
1856 }
1857
1858 for (const auto &version : versions) {
1859 PList::Dictionary rules;
1860
1861 std::multiset<const Rule *, RuleCode> ordered;
1862 for (const auto &rule : version.second)
1863 ordered.insert(&rule);
1864
1865 for (const auto &rule : ordered)
1866 if (rule->weight_ == 1 && rule->mode_ == NoMode)
1867 rules.Set(rule->code_, PList::Boolean(true));
1868 else {
1869 PList::Dictionary entry;
1870
1871 switch (rule->mode_) {
1872 case NoMode:
1873 break;
1874 case OmitMode:
1875 entry.Set("omit", PList::Boolean(true));
1876 break;
1877 case OptionalMode:
1878 entry.Set("optional", PList::Boolean(true));
1879 break;
1880 case NestedMode:
1881 entry.Set("nested", PList::Boolean(true));
1882 break;
1883 case TopMode:
1884 entry.Set("top", PList::Boolean(true));
1885 break;
1886 }
1887
1888 if (rule->weight_ >= 10000)
1889 entry.Set("weight", PList::Integer(rule->weight_));
1890 else if (rule->weight_ != 1)
1891 entry.Set("weight", PList::Real(rule->weight_));
1892
1893 rules.Set(rule->code_, entry);
1894 }
1895
1896 plist.Set("rules" + version.first, rules);
1897 }
1898
1899 folder.Save(signature, fun([&](std::streambuf &save) {
1900 HashProxy proxy(local[signature], save);
1901 auto xml(plist.ToXml());
1902 put(proxy, xml.data(), xml.size());
1903 }));
1904
1905 folder.Open(executable, fun([&](std::streambuf &buffer) {
1906 // XXX: this is a miserable fail
1907 std::stringbuf temp;
1908 copy(buffer, temp);
1909 auto data(temp.str());
1910
1911 folder.Save(executable, fun([&](std::streambuf &save) {
1912 Slots slots;
1913 slots[1] = local.at(info);
1914 slots[3] = local.at(signature);
1915
1916 HashProxy proxy(local[executable], save);
1917 Sign(data.data(), data.size(), proxy, identifier, "", key, slots);
1918 }));
1919 }));
1920
1921 for (const auto &hash : local)
1922 remote[root + hash.first] = hash.second;
1923
1924 return executable;
1925}
1926
a0c715e9
JF
1927}
1928
a7f01a65 1929int main(int argc, char *argv[]) {
30c64adb
JF
1930 OpenSSL_add_all_algorithms();
1931
5525a5a7
JF
1932 union {
1933 uint16_t word;
1934 uint8_t byte[2];
1935 } endian = {1};
1936
1937 little_ = endian.byte[0];
1938
20e7eb29 1939 bool flag_r(false);
9c83be90 1940 bool flag_e(false);
a362a82f
JF
1941
1942 bool flag_T(false);
20c5f1e8 1943
fdb119ef 1944 bool flag_S(false);
20c5f1e8 1945 bool flag_s(false);
a362a82f 1946
c0cc1574 1947 bool flag_D(false);
c0cc1574 1948
8c417842
JF
1949 bool flag_A(false);
1950 bool flag_a(false);
1951
c0cc1574
JF
1952 uint32_t flag_CPUType(_not(uint32_t));
1953 uint32_t flag_CPUSubtype(_not(uint32_t));
1954
5d7ceb5d
JF
1955 const char *flag_I(NULL);
1956
a362a82f
JF
1957 bool timeh(false);
1958 uint32_t timev(0);
1959
4d4682ef 1960 Map entitlements;
30c64adb 1961 Map key;
a0c715e9 1962 ldid::Slots slots;
c05d9758 1963
a362a82f
JF
1964 std::vector<std::string> files;
1965
a960f392
JF
1966 if (argc == 1) {
1967 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 1968 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
1969 fprintf(stderr, " %s -S cat\n", argv[0]);
1970 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1971 exit(0);
1972 }
1973
a362a82f
JF
1974 for (int argi(1); argi != argc; ++argi)
1975 if (argv[argi][0] != '-')
1976 files.push_back(argv[argi]);
1977 else switch (argv[argi][1]) {
fac3d3e3
JF
1978 case 'r':
1979 _assert(!flag_s);
1980 _assert(!flag_S);
1981 flag_r = true;
1982 break;
1983
9c83be90 1984 case 'e': flag_e = true; break;
c05d9758 1985
e57b1f91
JF
1986 case 'E': {
1987 const char *slot = argv[argi] + 2;
1988 const char *colon = strchr(slot, ':');
1989 _assert(colon != NULL);
1990 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
1991 char *arge;
1992 unsigned number(strtoul(slot, &arge, 0));
1993 _assert(arge == colon);
23c11ee8 1994 std::vector<char> &hash(slots[number]);
e57b1f91 1995 hash.resize(SHA_DIGEST_LENGTH);
23c11ee8 1996 sha1(reinterpret_cast<uint8_t *>(hash.data()), file.data(), file.size());
e57b1f91
JF
1997 } break;
1998
c0cc1574 1999 case 'D': flag_D = true; break;
c0cc1574 2000
8c417842
JF
2001 case 'a': flag_a = true; break;
2002
2003 case 'A':
fac3d3e3 2004 _assert(!flag_A);
8c417842
JF
2005 flag_A = true;
2006 if (argv[argi][2] != '\0') {
2007 const char *cpu = argv[argi] + 2;
2008 const char *colon = strchr(cpu, ':');
2009 _assert(colon != NULL);
2010 char *arge;
2011 flag_CPUType = strtoul(cpu, &arge, 0);
2012 _assert(arge == colon);
2013 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2014 _assert(arge == argv[argi] + strlen(argv[argi]));
2015 }
2016 break;
2017
20c5f1e8 2018 case 's':
fac3d3e3 2019 _assert(!flag_r);
20c5f1e8
JF
2020 _assert(!flag_S);
2021 flag_s = true;
2022 break;
2023
c05d9758 2024 case 'S':
fac3d3e3 2025 _assert(!flag_r);
20c5f1e8 2026 _assert(!flag_s);
c05d9758
JF
2027 flag_S = true;
2028 if (argv[argi][2] != '\0') {
2029 const char *xml = argv[argi] + 2;
4d4682ef 2030 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
2031 }
2032 break;
a362a82f 2033
30c64adb
JF
2034 case 'K':
2035 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2036 break;
2037
a362a82f
JF
2038 case 'T': {
2039 flag_T = true;
2040 if (argv[argi][2] == '-')
2041 timeh = true;
2042 else {
2043 char *arge;
2044 timev = strtoul(argv[argi] + 2, &arge, 0);
2045 _assert(arge == argv[argi] + strlen(argv[argi]));
2046 }
2047 } break;
2048
5d7ceb5d
JF
2049 case 'I': {
2050 flag_I = argv[argi] + 2;
2051 } break;
2052
a362a82f
JF
2053 default:
2054 goto usage;
2055 break;
2056 }
2057
fac3d3e3
JF
2058 _assert(flag_S || key.empty());
2059 _assert(flag_S || flag_I == NULL);
f4b2df35 2060
a362a82f
JF
2061 if (files.empty()) usage: {
2062 exit(0);
2063 }
2064
2065 size_t filei(0), filee(0);
2066 _foreach (file, files) try {
d4187e53 2067 std::string path(file);
5d7ceb5d 2068
23c11ee8
JF
2069 struct stat info;
2070 _syscall(stat(path.c_str(), &info));
8762082f 2071
23c11ee8
JF
2072 if (S_ISDIR(info.st_mode)) {
2073 _assert(!flag_r);
2074 ldid::DiskFolder folder(path);
2075 std::map<std::string, std::vector<char>> hashes;
2076 path += "/" + Bundle("", folder, key, hashes);
2077 } else if (flag_S || flag_r) {
2078 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
8762082f 2079
4d4682ef 2080 std::filebuf output;
23c11ee8
JF
2081 Split split(path);
2082 auto temp(Temporary(output, split));
4d4682ef 2083
e0098838 2084 if (flag_r)
a0c715e9 2085 ldid::Unsign(input.data(), input.size(), output);
8762082f 2086 else {
23c11ee8 2087 std::string identifier(flag_I ?: split.base.c_str());
ffdd1183 2088 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
8762082f 2089 }
34f4c1d8 2090
d4187e53 2091 Commit(path, temp);
fdb119ef
JF
2092 }
2093
34f4c1d8 2094 Map mapping(path, flag_T || flag_s);
dede6121 2095 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 2096
0a033524 2097 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 2098 struct linkedit_data_command *signature(NULL);
7b496abd
JF
2099 struct encryption_info_command *encryption(NULL);
2100
8c417842
JF
2101 if (flag_A) {
2102 if (mach_header.GetCPUType() != flag_CPUType)
2103 continue;
2104 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2105 continue;
2106 }
2107
2108 if (flag_a)
2109 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2110
0a033524
JF
2111 _foreach (load_command, mach_header.GetLoadCommands()) {
2112 uint32_t cmd(mach_header.Swap(load_command->cmd));
2113
cad40c43 2114 if (false);
0a033524
JF
2115 else if (cmd == LC_CODE_SIGNATURE)
2116 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 2117 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 2118 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
cad40c43 2119 else if (cmd == LC_ID_DYLIB) {
0a033524 2120 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 2121
0a033524
JF
2122 if (flag_T) {
2123 uint32_t timed;
a362a82f 2124
0a033524
JF
2125 if (!timeh)
2126 timed = timev;
2127 else {
2128 dylib_command->dylib.timestamp = 0;
2129 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2130 }
a362a82f 2131
0a033524
JF
2132 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2133 }
7b496abd
JF
2134 }
2135 }
2136
7b496abd
JF
2137 if (flag_D) {
2138 _assert(encryption != NULL);
2139 encryption->cryptid = mach_header.Swap(0);
a362a82f 2140 }
a362a82f 2141
0a033524
JF
2142 if (flag_e) {
2143 _assert(signature != NULL);
9c83be90 2144
0a033524 2145 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 2146
0a033524
JF
2147 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2148 uint8_t *blob = top + data;
2149 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 2150
0a033524
JF
2151 for (size_t index(0); index != Swap(super->count); ++index)
2152 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2153 uint32_t begin = Swap(super->index[index].offset);
2154 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
b9652d6e 2155 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
0a033524
JF
2156 }
2157 }
9c83be90 2158
0a033524
JF
2159 if (flag_s) {
2160 _assert(signature != NULL);
20c5f1e8 2161
0a033524 2162 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 2163
0a033524
JF
2164 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2165 uint8_t *blob = top + data;
2166 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 2167
0a033524
JF
2168 for (size_t index(0); index != Swap(super->count); ++index)
2169 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2170 uint32_t begin = Swap(super->index[index].offset);
2171 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 2172
4d4682ef 2173 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 2174 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 2175
0a033524
JF
2176 if (pages != 1)
2177 for (size_t i = 0; i != pages - 1; ++i)
b9652d6e 2178 sha1(hashes[i], top + PageSize_ * i, PageSize_);
0a033524 2179 if (pages != 0)
b9652d6e 2180 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
0a033524
JF
2181 }
2182 }
fdb119ef
JF
2183 }
2184
a362a82f
JF
2185 ++filei;
2186 } catch (const char *) {
2187 ++filee;
2188 ++filei;
2189 }
2190
2191 return filee;
2192}