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