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