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