]> git.saurik.com Git - ldid.git/blob - ldid.cpp
68fdf7d6af33b0d2884c85d606b6067b36e8229c
[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 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1391 return;
1392 auto slash(path.rfind('/', path.size() - 1));
1393 if (slash == std::string::npos)
1394 return;
1395 mkdir_p(path.substr(0, slash));
1396 }
1397
1398 static std::string Temporary(std::filebuf &file, const Split &split) {
1399 std::string temp(split.dir + ".ldid." + split.base);
1400 mkdir_p(split.dir);
1401 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1402 return temp;
1403 }
1404
1405 static void Commit(const std::string &path, const std::string &temp) {
1406 struct stat info;
1407 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1408 #ifndef __WIN32__
1409 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1410 #endif
1411 _syscall(chmod(temp.c_str(), info.st_mode));
1412 }
1413
1414 _syscall(rename(temp.c_str(), path.c_str()));
1415 }
1416
1417 namespace ldid {
1418
1419 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) {
1420 Allocate(idata, isize, output, fun([&](size_t size) -> size_t {
1421 size_t alloc(sizeof(struct SuperBlob));
1422
1423 uint32_t special(0);
1424
1425 special = std::max(special, CSSLOT_REQUIREMENTS);
1426 alloc += sizeof(struct BlobIndex);
1427 alloc += 0xc;
1428
1429 if (!entitlements.empty()) {
1430 special = std::max(special, CSSLOT_ENTITLEMENTS);
1431 alloc += sizeof(struct BlobIndex);
1432 alloc += sizeof(struct Blob);
1433 alloc += entitlements.size();
1434 }
1435
1436 special = std::max(special, CSSLOT_CODEDIRECTORY);
1437 alloc += sizeof(struct BlobIndex);
1438 alloc += sizeof(struct Blob);
1439 alloc += sizeof(struct CodeDirectory);
1440 alloc += identifier.size() + 1;
1441
1442 if (!key.empty()) {
1443 alloc += sizeof(struct BlobIndex);
1444 alloc += sizeof(struct Blob);
1445 // XXX: this is just a "sufficiently large number"
1446 alloc += 0x3000;
1447 }
1448
1449 _foreach (slot, slots)
1450 special = std::max(special, slot.first);
1451
1452 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1453 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1454 return alloc;
1455 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1456 Blobs blobs;
1457
1458 if (true) {
1459 std::stringbuf data;
1460
1461 Blobs requirements;
1462 put(data, CSMAGIC_REQUIREMENTS, requirements);
1463
1464 insert(blobs, CSSLOT_REQUIREMENTS, data);
1465 }
1466
1467 if (!entitlements.empty()) {
1468 std::stringbuf data;
1469 put(data, entitlements.data(), entitlements.size());
1470 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1471 }
1472
1473 if (true) {
1474 std::stringbuf data;
1475
1476 uint32_t special(0);
1477 _foreach (blob, blobs)
1478 special = std::max(special, blob.first);
1479 _foreach (slot, slots)
1480 special = std::max(special, slot.first);
1481 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1482
1483 CodeDirectory directory;
1484 directory.version = Swap(uint32_t(0x00020001));
1485 directory.flags = Swap(uint32_t(0));
1486 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + SHA_DIGEST_LENGTH * special));
1487 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
1488 directory.nSpecialSlots = Swap(special);
1489 directory.codeLimit = Swap(uint32_t(limit));
1490 directory.nCodeSlots = Swap(normal);
1491 directory.hashSize = SHA_DIGEST_LENGTH;
1492 directory.hashType = CS_HASHTYPE_SHA1;
1493 directory.spare1 = 0x00;
1494 directory.pageSize = PageShift_;
1495 directory.spare2 = Swap(uint32_t(0));
1496 put(data, &directory, sizeof(directory));
1497
1498 put(data, identifier.c_str(), identifier.size() + 1);
1499
1500 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1501 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1502
1503 memset(storage, 0, sizeof(*storage) * special);
1504
1505 _foreach (blob, blobs) {
1506 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1507 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
1508 }
1509
1510 _foreach (slot, slots) {
1511 _assert(sizeof(*hashes) == slot.second.size());
1512 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1513 }
1514
1515 if (normal != 1)
1516 for (size_t i = 0; i != normal - 1; ++i)
1517 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1518 if (normal != 0)
1519 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1520
1521 put(data, storage, sizeof(storage));
1522
1523 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
1524 }
1525
1526 if (!key.empty()) {
1527 std::stringbuf data;
1528 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1529
1530 Stuff stuff(key);
1531 Buffer bio(sign);
1532
1533 Signature signature(stuff, sign);
1534 Buffer result(signature);
1535 std::string value(result);
1536 put(data, value.data(), value.size());
1537
1538 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1539 }
1540
1541 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1542 }));
1543 }
1544
1545 static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1546 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
1547 return 0;
1548 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1549 return 0;
1550 }));
1551 }
1552
1553 std::string DiskFolder::Path(const std::string &path) {
1554 return path_ + "/" + path;
1555 }
1556
1557 DiskFolder::DiskFolder(const std::string &path) :
1558 path_(path)
1559 {
1560 }
1561
1562 DiskFolder::~DiskFolder() {
1563 if (!std::uncaught_exception())
1564 for (const auto &commit : commit_)
1565 Commit(commit.first, commit.second);
1566 }
1567
1568 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) {
1569 std::string path(Path(root) + base);
1570
1571 DIR *dir(opendir(path.c_str()));
1572 _assert(dir != NULL);
1573 _scope({ _syscall(closedir(dir)); });
1574
1575 while (auto child = readdir(dir)) {
1576 std::string name(child->d_name);
1577 if (name == "." || name == "..")
1578 continue;
1579 if (Starts(name, ".ldid."))
1580 continue;
1581
1582 switch (child->d_type) {
1583 case DT_DIR:
1584 Find(root, base + name + "/", code);
1585 break;
1586
1587 case DT_REG:
1588 code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1589 std::string access(root + base + name);
1590 _assert_(Open(access, fun([&](std::streambuf &data) {
1591 NullBuffer save;
1592 code(data, save);
1593 })), "open(): %s", access.c_str());
1594 }));
1595 break;
1596
1597 default:
1598 _assert_(false, "d_type=%u", child->d_type);
1599 break;
1600 }
1601 }
1602 }
1603
1604 void DiskFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1605 std::filebuf save;
1606 auto from(Path(path));
1607 commit_[from] = Temporary(save, from);
1608 code(save);
1609 }
1610
1611 bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1612 std::filebuf data;
1613 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1614 if (result == NULL)
1615 return false;
1616 _assert(result == &data);
1617 code(data);
1618 return true;
1619 }
1620
1621 void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1622 Find(path, "", code);
1623 }
1624
1625 SubFolder::SubFolder(Folder *parent, const std::string &path) :
1626 parent_(parent),
1627 path_(path)
1628 {
1629 }
1630
1631 void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1632 return parent_->Save(path_ + path, code);
1633 }
1634
1635 bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1636 return parent_->Open(path_ + path, code);
1637 }
1638
1639 void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1640 return parent_->Find(path_ + path, code);
1641 }
1642
1643 static size_t copy(std::streambuf &source, std::streambuf &target) {
1644 size_t total(0);
1645 for (;;) {
1646 char data[4096];
1647 size_t writ(source.sgetn(data, sizeof(data)));
1648 if (writ == 0)
1649 break;
1650 _assert(target.sputn(data, writ) == writ);
1651 total += writ;
1652 }
1653 return total;
1654 }
1655
1656 static PList::Structure *plist(const std::string &data) {
1657 if (!Starts(data, "bplist00"))
1658 return PList::Structure::FromXml(data);
1659 std::vector<char> bytes(data.data(), data.data() + data.size());
1660 return PList::Structure::FromBin(bytes);
1661 }
1662
1663 static void plist_d(std::streambuf &buffer, const Functor<void (PList::Dictionary *)> &code) {
1664 std::stringbuf data;
1665 copy(buffer, data);
1666 PList::Structure *structure(plist(data.str()));
1667 _scope({ delete structure; });
1668 auto dictionary(dynamic_cast<PList::Dictionary *>(structure));
1669 _assert(dictionary != NULL);
1670 code(dictionary);
1671 }
1672
1673 static std::string plist_s(PList::Node *node) {
1674 auto value(dynamic_cast<PList::String *>(node));
1675 _assert(value != NULL);
1676 return value->GetValue();
1677 }
1678
1679 enum Mode {
1680 NoMode,
1681 OptionalMode,
1682 OmitMode,
1683 NestedMode,
1684 TopMode,
1685 };
1686
1687 class Expression {
1688 private:
1689 regex_t regex_;
1690
1691 public:
1692 Expression(const std::string &code) {
1693 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1694 }
1695
1696 ~Expression() {
1697 regfree(&regex_);
1698 }
1699
1700 bool operator ()(const std::string &data) const {
1701 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1702 if (value == REG_NOMATCH)
1703 return false;
1704 _assert_(value == 0, "regexec()");
1705 return true;
1706 }
1707 };
1708
1709 struct Rule {
1710 unsigned weight_;
1711 Mode mode_;
1712 std::string code_;
1713
1714 mutable std::auto_ptr<Expression> regex_;
1715
1716 Rule(unsigned weight, Mode mode, const std::string &code) :
1717 weight_(weight),
1718 mode_(mode),
1719 code_(code)
1720 {
1721 }
1722
1723 Rule(const Rule &rhs) :
1724 weight_(rhs.weight_),
1725 mode_(rhs.mode_),
1726 code_(rhs.code_)
1727 {
1728 }
1729
1730 void Compile() const {
1731 regex_.reset(new Expression(code_));
1732 }
1733
1734 bool operator ()(const std::string &data) const {
1735 _assert(regex_.get() != NULL);
1736 return (*regex_)(data);
1737 }
1738
1739 bool operator <(const Rule &rhs) const {
1740 if (weight_ > rhs.weight_)
1741 return true;
1742 if (weight_ < rhs.weight_)
1743 return false;
1744 return mode_ > rhs.mode_;
1745 }
1746 };
1747
1748 struct RuleCode {
1749 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1750 return lhs->code_ < rhs->code_;
1751 }
1752 };
1753
1754 std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, std::vector<char>> &remote) {
1755 std::string executable;
1756 std::string identifier;
1757
1758 static const std::string info("Info.plist");
1759
1760 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
1761 plist_d(buffer, fun([&](PList::Dictionary *dictionary) {
1762 executable = plist_s(((*dictionary)["CFBundleExecutable"]));
1763 identifier = plist_s(((*dictionary)["CFBundleIdentifier"]));
1764 }));
1765 })), "open(): Info.plist");
1766
1767 std::map<std::string, std::multiset<Rule>> versions;
1768
1769 auto &rules1(versions[""]);
1770 auto &rules2(versions["2"]);
1771
1772 static const std::string signature("_CodeSignature/CodeResources");
1773
1774 folder.Open(signature, fun([&](std::streambuf &buffer) {
1775 plist_d(buffer, fun([&](PList::Dictionary *dictionary) {
1776 // XXX: maybe attempt to preserve existing rules
1777 }));
1778 }));
1779
1780 if (true) {
1781 rules1.insert(Rule{1, NoMode, "^"});
1782 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1783 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1784 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1785 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1786 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1787 }
1788
1789 if (true) {
1790 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1791 rules2.insert(Rule{20, NoMode, "^"});
1792 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1793 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1794 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1795 rules2.insert(Rule{1, NoMode, "^.*"});
1796 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1797 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1798 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1799 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1800 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1801 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1802 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1803 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1804 }
1805
1806 std::map<std::string, std::vector<char>> local;
1807
1808 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1809
1810 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1811 if (!nested(name))
1812 return;
1813 auto bundle(root + Split(name).dir);
1814 SubFolder subfolder(&folder, bundle);
1815 Bundle(bundle, subfolder, key, local);
1816 }));
1817
1818 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1819 if (name == executable || name == signature)
1820 return;
1821
1822 auto &hash(local[name]);
1823 if (!hash.empty())
1824 return;
1825
1826 code(fun([&](std::streambuf &data, std::streambuf &save) {
1827 HashProxy proxy(hash, save);
1828 copy(data, proxy);
1829 }));
1830
1831 _assert(hash.size() == SHA_DIGEST_LENGTH);
1832 }));
1833
1834 PList::Dictionary plist;
1835
1836 for (const auto &version : versions) {
1837 PList::Dictionary files;
1838
1839 for (const auto &rule : version.second)
1840 rule.Compile();
1841
1842 for (const auto &hash : local)
1843 for (const auto &rule : version.second)
1844 if (rule(hash.first)) {
1845 if (rule.mode_ == NoMode)
1846 files.Set(hash.first, PList::Data(hash.second));
1847 else if (rule.mode_ == OptionalMode) {
1848 PList::Dictionary entry;
1849 entry.Set("hash", PList::Data(hash.second));
1850 entry.Set("optional", PList::Boolean(true));
1851 files.Set(hash.first, entry);
1852 }
1853
1854 break;
1855 }
1856
1857 plist.Set("files" + version.first, files);
1858 }
1859
1860 for (const auto &version : versions) {
1861 PList::Dictionary rules;
1862
1863 std::multiset<const Rule *, RuleCode> ordered;
1864 for (const auto &rule : version.second)
1865 ordered.insert(&rule);
1866
1867 for (const auto &rule : ordered)
1868 if (rule->weight_ == 1 && rule->mode_ == NoMode)
1869 rules.Set(rule->code_, PList::Boolean(true));
1870 else {
1871 PList::Dictionary entry;
1872
1873 switch (rule->mode_) {
1874 case NoMode:
1875 break;
1876 case OmitMode:
1877 entry.Set("omit", PList::Boolean(true));
1878 break;
1879 case OptionalMode:
1880 entry.Set("optional", PList::Boolean(true));
1881 break;
1882 case NestedMode:
1883 entry.Set("nested", PList::Boolean(true));
1884 break;
1885 case TopMode:
1886 entry.Set("top", PList::Boolean(true));
1887 break;
1888 }
1889
1890 if (rule->weight_ >= 10000)
1891 entry.Set("weight", PList::Integer(rule->weight_));
1892 else if (rule->weight_ != 1)
1893 entry.Set("weight", PList::Real(rule->weight_));
1894
1895 rules.Set(rule->code_, entry);
1896 }
1897
1898 plist.Set("rules" + version.first, rules);
1899 }
1900
1901 folder.Save(signature, fun([&](std::streambuf &save) {
1902 HashProxy proxy(local[signature], save);
1903 auto xml(plist.ToXml());
1904 put(proxy, xml.data(), xml.size());
1905 }));
1906
1907 folder.Open(executable, fun([&](std::streambuf &buffer) {
1908 // XXX: this is a miserable fail
1909 std::stringbuf temp;
1910 copy(buffer, temp);
1911 auto data(temp.str());
1912
1913 folder.Save(executable, fun([&](std::streambuf &save) {
1914 Slots slots;
1915 slots[1] = local.at(info);
1916 slots[3] = local.at(signature);
1917
1918 HashProxy proxy(local[executable], save);
1919 Sign(data.data(), data.size(), proxy, identifier, "", key, slots);
1920 }));
1921 }));
1922
1923 for (const auto &hash : local)
1924 remote[root + hash.first] = hash.second;
1925
1926 return executable;
1927 }
1928
1929 }
1930
1931 int main(int argc, char *argv[]) {
1932 OpenSSL_add_all_algorithms();
1933
1934 union {
1935 uint16_t word;
1936 uint8_t byte[2];
1937 } endian = {1};
1938
1939 little_ = endian.byte[0];
1940
1941 bool flag_r(false);
1942 bool flag_e(false);
1943
1944 bool flag_T(false);
1945
1946 bool flag_S(false);
1947 bool flag_s(false);
1948
1949 bool flag_D(false);
1950
1951 bool flag_A(false);
1952 bool flag_a(false);
1953
1954 uint32_t flag_CPUType(_not(uint32_t));
1955 uint32_t flag_CPUSubtype(_not(uint32_t));
1956
1957 const char *flag_I(NULL);
1958
1959 bool timeh(false);
1960 uint32_t timev(0);
1961
1962 Map entitlements;
1963 Map key;
1964 ldid::Slots slots;
1965
1966 std::vector<std::string> files;
1967
1968 if (argc == 1) {
1969 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
1970 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
1971 fprintf(stderr, " %s -S cat\n", argv[0]);
1972 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1973 exit(0);
1974 }
1975
1976 for (int argi(1); argi != argc; ++argi)
1977 if (argv[argi][0] != '-')
1978 files.push_back(argv[argi]);
1979 else switch (argv[argi][1]) {
1980 case 'r':
1981 _assert(!flag_s);
1982 _assert(!flag_S);
1983 flag_r = true;
1984 break;
1985
1986 case 'e': flag_e = true; break;
1987
1988 case 'E': {
1989 const char *slot = argv[argi] + 2;
1990 const char *colon = strchr(slot, ':');
1991 _assert(colon != NULL);
1992 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
1993 char *arge;
1994 unsigned number(strtoul(slot, &arge, 0));
1995 _assert(arge == colon);
1996 std::vector<char> &hash(slots[number]);
1997 hash.resize(SHA_DIGEST_LENGTH);
1998 sha1(reinterpret_cast<uint8_t *>(hash.data()), file.data(), file.size());
1999 } break;
2000
2001 case 'D': flag_D = true; break;
2002
2003 case 'a': flag_a = true; break;
2004
2005 case 'A':
2006 _assert(!flag_A);
2007 flag_A = true;
2008 if (argv[argi][2] != '\0') {
2009 const char *cpu = argv[argi] + 2;
2010 const char *colon = strchr(cpu, ':');
2011 _assert(colon != NULL);
2012 char *arge;
2013 flag_CPUType = strtoul(cpu, &arge, 0);
2014 _assert(arge == colon);
2015 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2016 _assert(arge == argv[argi] + strlen(argv[argi]));
2017 }
2018 break;
2019
2020 case 's':
2021 _assert(!flag_r);
2022 _assert(!flag_S);
2023 flag_s = true;
2024 break;
2025
2026 case 'S':
2027 _assert(!flag_r);
2028 _assert(!flag_s);
2029 flag_S = true;
2030 if (argv[argi][2] != '\0') {
2031 const char *xml = argv[argi] + 2;
2032 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2033 }
2034 break;
2035
2036 case 'K':
2037 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2038 break;
2039
2040 case 'T': {
2041 flag_T = true;
2042 if (argv[argi][2] == '-')
2043 timeh = true;
2044 else {
2045 char *arge;
2046 timev = strtoul(argv[argi] + 2, &arge, 0);
2047 _assert(arge == argv[argi] + strlen(argv[argi]));
2048 }
2049 } break;
2050
2051 case 'I': {
2052 flag_I = argv[argi] + 2;
2053 } break;
2054
2055 default:
2056 goto usage;
2057 break;
2058 }
2059
2060 _assert(flag_S || key.empty());
2061 _assert(flag_S || flag_I == NULL);
2062
2063 if (files.empty()) usage: {
2064 exit(0);
2065 }
2066
2067 size_t filei(0), filee(0);
2068 _foreach (file, files) try {
2069 std::string path(file);
2070
2071 struct stat info;
2072 _syscall(stat(path.c_str(), &info));
2073
2074 if (S_ISDIR(info.st_mode)) {
2075 _assert(!flag_r);
2076 ldid::DiskFolder folder(path);
2077 std::map<std::string, std::vector<char>> hashes;
2078 path += "/" + Bundle("", folder, key, hashes);
2079 } else if (flag_S || flag_r) {
2080 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2081
2082 std::filebuf output;
2083 Split split(path);
2084 auto temp(Temporary(output, split));
2085
2086 if (flag_r)
2087 ldid::Unsign(input.data(), input.size(), output);
2088 else {
2089 std::string identifier(flag_I ?: split.base.c_str());
2090 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
2091 }
2092
2093 Commit(path, temp);
2094 }
2095
2096 Map mapping(path, flag_T || flag_s);
2097 FatHeader fat_header(mapping.data(), mapping.size());
2098
2099 _foreach (mach_header, fat_header.GetMachHeaders()) {
2100 struct linkedit_data_command *signature(NULL);
2101 struct encryption_info_command *encryption(NULL);
2102
2103 if (flag_A) {
2104 if (mach_header.GetCPUType() != flag_CPUType)
2105 continue;
2106 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2107 continue;
2108 }
2109
2110 if (flag_a)
2111 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2112
2113 _foreach (load_command, mach_header.GetLoadCommands()) {
2114 uint32_t cmd(mach_header.Swap(load_command->cmd));
2115
2116 if (false);
2117 else if (cmd == LC_CODE_SIGNATURE)
2118 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2119 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2120 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2121 else if (cmd == LC_ID_DYLIB) {
2122 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2123
2124 if (flag_T) {
2125 uint32_t timed;
2126
2127 if (!timeh)
2128 timed = timev;
2129 else {
2130 dylib_command->dylib.timestamp = 0;
2131 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2132 }
2133
2134 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2135 }
2136 }
2137 }
2138
2139 if (flag_D) {
2140 _assert(encryption != NULL);
2141 encryption->cryptid = mach_header.Swap(0);
2142 }
2143
2144 if (flag_e) {
2145 _assert(signature != NULL);
2146
2147 uint32_t data = mach_header.Swap(signature->dataoff);
2148
2149 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2150 uint8_t *blob = top + data;
2151 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2152
2153 for (size_t index(0); index != Swap(super->count); ++index)
2154 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2155 uint32_t begin = Swap(super->index[index].offset);
2156 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2157 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2158 }
2159 }
2160
2161 if (flag_s) {
2162 _assert(signature != NULL);
2163
2164 uint32_t data = mach_header.Swap(signature->dataoff);
2165
2166 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2167 uint8_t *blob = top + data;
2168 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2169
2170 for (size_t index(0); index != Swap(super->count); ++index)
2171 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2172 uint32_t begin = Swap(super->index[index].offset);
2173 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
2174
2175 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2176 uint32_t pages = Swap(directory->nCodeSlots);
2177
2178 if (pages != 1)
2179 for (size_t i = 0; i != pages - 1; ++i)
2180 sha1(hashes[i], top + PageSize_ * i, PageSize_);
2181 if (pages != 0)
2182 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
2183 }
2184 }
2185 }
2186
2187 ++filei;
2188 } catch (const char *) {
2189 ++filee;
2190 ++filei;
2191 }
2192
2193 return filee;
2194 }