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