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