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