1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
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.
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.
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/>.
43 #include <sys/types.h>
45 #include <openssl/err.h>
46 #include <openssl/pem.h>
47 #include <openssl/pkcs7.h>
48 #include <openssl/pkcs12.h>
51 #include <CommonCrypto/CommonDigest.h>
52 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
53 #define LDID_SHA1 CC_SHA1
54 #define LDID_SHA1_CTX CC_SHA1_CTX
55 #define LDID_SHA1_Init CC_SHA1_Init
56 #define LDID_SHA1_Update CC_SHA1_Update
57 #define LDID_SHA1_Final CC_SHA1_Final
59 #include <openssl/sha.h>
60 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
61 #define LDID_SHA1 SHA1
62 #define LDID_SHA1_CTX SHA_CTX
63 #define LDID_SHA1_Init SHA1_Init
64 #define LDID_SHA1_Update SHA1_Update
65 #define LDID_SHA1_Final SHA1_Final
68 #include <plist/plist.h>
72 #define _assert___(line) \
74 #define _assert__(line) \
77 #define _assert_(expr, format, ...) \
79 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
80 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
83 #define _assert(expr) \
84 _assert_(expr, "%s", #expr)
86 #define _syscall(expr, ...) [&] { for (;;) { \
88 if ((long) _value != -1) \
93 /* XXX: EINTR is included in this list to fix g++ */ \
94 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
95 if (error == success) \
96 return (decltype(expr)) -success; \
97 _assert_(false, "errno=%u", error); \
101 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
107 __attribute__((packed))
109 template <typename Type_
>
111 typedef typename
Type_::const_iterator Result
;
114 #define _foreach(item, list) \
115 for (bool _stop(true); _stop; ) \
116 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
117 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
118 for (bool _suck(true); _suck; _suck = false) \
119 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
124 template <typename Function_
>
132 Scope(const Function_
&function
) :
142 template <typename Function_
>
143 Scope
<Function_
> _scope(const Function_
&function
) {
144 return Scope
<Function_
>(function
);
147 #define _scope__(counter, function) \
148 __attribute__((__unused__)) \
149 const _Scope &_scope ## counter(_scope([&]function))
150 #define _scope_(counter, function) \
151 _scope__(counter, function)
152 #define _scope(function) \
153 _scope_(__COUNTER__, function)
160 #define FAT_MAGIC 0xcafebabe
161 #define FAT_CIGAM 0xbebafeca
181 #define MH_MAGIC 0xfeedface
182 #define MH_CIGAM 0xcefaedfe
184 #define MH_MAGIC_64 0xfeedfacf
185 #define MH_CIGAM_64 0xcffaedfe
187 #define MH_DYLDLINK 0x4
189 #define MH_OBJECT 0x1
190 #define MH_EXECUTE 0x2
192 #define MH_BUNDLE 0x8
193 #define MH_DYLIB_STUB 0x9
195 struct load_command
{
200 #define LC_REQ_DYLD uint32_t(0x80000000)
202 #define LC_SEGMENT uint32_t(0x01)
203 #define LC_SYMTAB uint32_t(0x02)
204 #define LC_DYSYMTAB uint32_t(0x0b)
205 #define LC_LOAD_DYLIB uint32_t(0x0c)
206 #define LC_ID_DYLIB uint32_t(0x0d)
207 #define LC_SEGMENT_64 uint32_t(0x19)
208 #define LC_UUID uint32_t(0x1b)
209 #define LC_CODE_SIGNATURE uint32_t(0x1d)
210 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
211 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
212 #define LC_ENCRYPTION_INFO uint32_t(0x21)
213 #define LC_DYLD_INFO uint32_t(0x22)
214 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
215 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
220 uint32_t current_version
;
221 uint32_t compatibility_version
;
224 struct dylib_command
{
230 struct uuid_command
{
236 struct symtab_command
{
245 struct dyld_info_command
{
249 uint32_t rebase_size
;
252 uint32_t weak_bind_off
;
253 uint32_t weak_bind_size
;
254 uint32_t lazy_bind_off
;
255 uint32_t lazy_bind_size
;
257 uint32_t export_size
;
260 struct dysymtab_command
{
273 uint32_t extrefsymoff
;
274 uint32_t nextrefsyms
;
275 uint32_t indirectsymoff
;
276 uint32_t nindirectsyms
;
283 struct dylib_table_of_contents
{
284 uint32_t symbol_index
;
285 uint32_t module_index
;
288 struct dylib_module
{
289 uint32_t module_name
;
298 uint32_t iinit_iterm
;
299 uint32_t ninit_nterm
;
300 uint32_t objc_module_info_addr
;
301 uint32_t objc_module_info_size
;
304 struct dylib_reference
{
309 struct relocation_info
{
311 uint32_t r_symbolnum
:24;
330 struct segment_command
{
344 struct segment_command_64
{
386 struct linkedit_data_command
{
393 struct encryption_info_command
{
401 #define BIND_OPCODE_MASK 0xf0
402 #define BIND_IMMEDIATE_MASK 0x0f
403 #define BIND_OPCODE_DONE 0x00
404 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
405 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
406 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
407 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
408 #define BIND_OPCODE_SET_TYPE_IMM 0x50
409 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
410 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
411 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
412 #define BIND_OPCODE_DO_BIND 0x90
413 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
414 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
415 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
417 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
418 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
421 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
422 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
425 inline void pad(std::streambuf
&stream
, size_t size
) {
427 memset(padding
, 0, size
);
428 put(stream
, padding
, size
);
431 template <typename Type_
>
432 Type_
Align(Type_ value
, size_t align
) {
439 static const uint8_t PageShift_(0x0c);
440 static const uint32_t PageSize_(1 << PageShift_
);
442 static inline uint16_t Swap_(uint16_t value
) {
444 ((value
>> 8) & 0x00ff) |
445 ((value
<< 8) & 0xff00);
448 static inline uint32_t Swap_(uint32_t value
) {
449 value
= ((value
>> 8) & 0x00ff00ff) |
450 ((value
<< 8) & 0xff00ff00);
451 value
= ((value
>> 16) & 0x0000ffff) |
452 ((value
<< 16) & 0xffff0000);
456 static inline uint64_t Swap_(uint64_t value
) {
457 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
458 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
459 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
463 static inline int16_t Swap_(int16_t value
) {
464 return Swap_(static_cast<uint16_t>(value
));
467 static inline int32_t Swap_(int32_t value
) {
468 return Swap_(static_cast<uint32_t>(value
));
471 static inline int64_t Swap_(int64_t value
) {
472 return Swap_(static_cast<uint64_t>(value
));
475 static bool little_(true);
477 static inline uint16_t Swap(uint16_t value
) {
478 return little_
? Swap_(value
) : value
;
481 static inline uint32_t Swap(uint32_t value
) {
482 return little_
? Swap_(value
) : value
;
485 static inline uint64_t Swap(uint64_t value
) {
486 return little_
? Swap_(value
) : value
;
489 static inline int16_t Swap(int16_t value
) {
490 return Swap(static_cast<uint16_t>(value
));
493 static inline int32_t Swap(int32_t value
) {
494 return Swap(static_cast<uint32_t>(value
));
497 static inline int64_t Swap(int64_t value
) {
498 return Swap(static_cast<uint64_t>(value
));
501 template <typename Target_
>
514 Swapped(bool swapped
) :
519 template <typename Type_
>
520 Type_
Swap(Type_ value
) const {
521 return swapped_
? Swap_(value
) : value
;
533 Data(void *base
, size_t size
) :
539 void *GetBase() const {
543 size_t GetSize() const {
554 struct mach_header
*mach_header_
;
555 struct load_command
*load_command_
;
558 MachHeader(void *base
, size_t size
) :
561 mach_header_
= (mach_header
*) base
;
563 switch (Swap(mach_header_
->magic
)) {
565 swapped_
= !swapped_
;
571 swapped_
= !swapped_
;
580 void *post
= mach_header_
+ 1;
582 post
= (uint32_t *) post
+ 1;
583 load_command_
= (struct load_command
*) post
;
586 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
587 Swap(mach_header_
->filetype
) == MH_DYLIB
||
588 Swap(mach_header_
->filetype
) == MH_BUNDLE
592 bool Bits64() const {
596 struct mach_header
*operator ->() const {
600 operator struct mach_header
*() const {
604 uint32_t GetCPUType() const {
605 return Swap(mach_header_
->cputype
);
608 uint32_t GetCPUSubtype() const {
609 return Swap(mach_header_
->cpusubtype
) & 0xff;
612 struct load_command
*GetLoadCommand() const {
613 return load_command_
;
616 std::vector
<struct load_command
*> GetLoadCommands() const {
617 std::vector
<struct load_command
*> load_commands
;
619 struct load_command
*load_command
= load_command_
;
620 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
621 load_commands
.push_back(load_command
);
622 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
625 return load_commands
;
628 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
629 std::vector
<struct segment_command
*> segment_commands
;
631 _foreach (load_command
, GetLoadCommands()) {
632 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
633 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
634 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
635 segment_commands
.push_back(segment_command
);
639 return segment_commands
;
642 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
643 std::vector
<struct segment_command_64
*> segment_commands
;
645 _foreach (load_command
, GetLoadCommands()) {
646 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
647 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
648 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
649 segment_commands
.push_back(segment_command
);
653 return segment_commands
;
656 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
657 std::vector
<section
*> sections
;
659 _foreach (segment
, GetSegments(segment_name
)) {
660 section
*section
= (struct section
*) (segment
+ 1);
663 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
664 if (strncmp(section
->sectname
, section_name
, 16) == 0)
665 sections
.push_back(section
);
673 template <typename Target_
>
674 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
675 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
678 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
679 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
680 segment_command
*segment_command
= (struct segment_command
*) load_command
;
681 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
684 section
*sections
= (struct section
*) (segment_command
+ 1);
687 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
688 section
*section
= §ions
[sect
];
689 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
690 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
691 //printf("0x%.8x %s\n", address, segment_command->segname);
692 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
698 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
701 return Pointer
<Target_
>(this);
704 template <typename Target_
>
705 Pointer
<Target_
> GetOffset(uint32_t offset
) {
706 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
710 class FatMachHeader
:
717 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
718 MachHeader(base
, size
),
723 fat_arch
*GetFatArch() const {
732 fat_header
*fat_header_
;
733 std::vector
<FatMachHeader
> mach_headers_
;
736 FatHeader(void *base
, size_t size
) :
739 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
741 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
742 swapped_
= !swapped_
;
744 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
746 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
748 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
749 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
751 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
752 uint32_t arch_offset
= Swap(fat_arch
->offset
);
753 uint32_t arch_size
= Swap(fat_arch
->size
);
754 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
760 std::vector
<FatMachHeader
> &GetMachHeaders() {
761 return mach_headers_
;
765 return fat_header_
!= NULL
;
768 struct fat_header
*operator ->() const {
772 operator struct fat_header
*() const {
777 template <typename Target_
>
780 const MachHeader
*framework_
;
781 const Target_
*pointer_
;
784 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
785 framework_(framework
),
790 operator const Target_
*() const {
794 const Target_
*operator ->() const {
798 Pointer
<Target_
> &operator ++() {
803 template <typename Value_
>
804 Value_
Swap(Value_ value
) {
805 return framework_
->Swap(value
);
809 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
810 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
811 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
812 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
813 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
814 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
815 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
816 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
818 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
819 #define CSSLOT_INFOSLOT uint32_t(0x00001)
820 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
821 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
822 #define CSSLOT_APPLICATION uint32_t(0x00004)
823 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
825 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
827 #define CS_HASHTYPE_SHA1 1
842 struct BlobIndex index
[];
845 struct CodeDirectory
{
849 uint32_t identOffset
;
850 uint32_t nSpecialSlots
;
860 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
862 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
863 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
866 struct CodesignAllocation
{
867 FatMachHeader mach_header_
;
874 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
875 mach_header_(mach_header
),
897 _syscall(close(file_
));
900 void open(const char *path
, int flags
) {
901 _assert(file_
== -1);
902 file_
= _syscall(::open(path
, flags
));
919 _syscall(munmap(data_
, size_
));
931 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
934 open(path
, oflag
, pflag
, mflag
);
937 Map(const std::string
&path
, bool edit
) :
948 return data_
== NULL
;
951 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
954 file_
.open(path
.c_str(), oflag
);
955 int file(file_
.file());
958 _syscall(fstat(file
, &stat
));
959 size_
= stat
.st_size
;
961 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
964 void open(const std::string
&path
, bool edit
) {
966 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
968 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
975 size_t size() const {
979 operator std::string() const {
980 return std::string(static_cast<char *>(data_
), size_
);
986 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
) {
987 FatHeader
source(const_cast<void *>(idata
), isize
);
991 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
993 std::vector
<CodesignAllocation
> allocations
;
994 _foreach (mach_header
, source
.GetMachHeaders()) {
995 struct linkedit_data_command
*signature(NULL
);
996 struct symtab_command
*symtab(NULL
);
998 _foreach (load_command
, mach_header
.GetLoadCommands()) {
999 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1001 else if (cmd
== LC_CODE_SIGNATURE
)
1002 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1003 else if (cmd
== LC_SYMTAB
)
1004 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1008 if (signature
== NULL
)
1009 size
= mach_header
.GetSize();
1011 size
= mach_header
.Swap(signature
->dataoff
);
1012 _assert(size
<= mach_header
.GetSize());
1015 if (symtab
!= NULL
) {
1016 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1017 _assert(end
<= size
);
1018 _assert(end
>= size
- 0x10);
1022 size_t alloc(allocate(size
));
1024 auto *fat_arch(mach_header
.GetFatArch());
1025 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1026 offset
= Align(offset
, 1 << align
);
1028 uint32_t limit(size
);
1030 limit
= Align(limit
, 0x10);
1032 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1033 offset
+= size
+ alloc
;
1034 offset
= Align(offset
, 0x10);
1039 if (source
.IsFat()) {
1040 fat_header fat_header
;
1041 fat_header
.magic
= Swap(FAT_MAGIC
);
1042 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1043 put(output
, &fat_header
, sizeof(fat_header
));
1044 position
+= sizeof(fat_header
);
1046 _foreach (allocation
, allocations
) {
1047 auto &mach_header(allocation
.mach_header_
);
1050 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1051 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1052 fat_arch
.offset
= Swap(allocation
.offset_
);
1053 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1054 fat_arch
.align
= Swap(allocation
.align_
);
1055 put(output
, &fat_arch
, sizeof(fat_arch
));
1056 position
+= sizeof(fat_arch
);
1060 _foreach (allocation
, allocations
) {
1061 auto &mach_header(allocation
.mach_header_
);
1063 pad(output
, allocation
.offset_
- position
);
1064 position
= allocation
.offset_
;
1066 std::vector
<std::string
> commands
;
1068 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1069 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1071 switch (mach_header
.Swap(load_command
->cmd
)) {
1072 case LC_CODE_SIGNATURE
:
1077 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1078 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1080 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1081 segment_command
->filesize
= size
;
1082 segment_command
->vmsize
= Align(size
, PageSize_
);
1085 case LC_SEGMENT_64
: {
1086 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1087 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1089 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1090 segment_command
->filesize
= size
;
1091 segment_command
->vmsize
= Align(size
, PageSize_
);
1095 commands
.push_back(copy
);
1098 if (allocation
.alloc_
!= 0) {
1099 linkedit_data_command signature
;
1100 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1101 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1102 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1103 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1104 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1107 size_t begin(position
);
1110 _foreach(command
, commands
)
1111 after
+= command
.size();
1113 std::stringbuf altern
;
1115 struct mach_header
header(*mach_header
);
1116 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1117 header
.sizeofcmds
= mach_header
.Swap(after
);
1118 put(output
, &header
, sizeof(header
));
1119 put(altern
, &header
, sizeof(header
));
1120 position
+= sizeof(header
);
1122 if (mach_header
.Bits64()) {
1123 auto pad(mach_header
.Swap(uint32_t(0)));
1124 put(output
, &pad
, sizeof(pad
));
1125 put(altern
, &pad
, sizeof(pad
));
1126 position
+= sizeof(pad
);
1129 _foreach(command
, commands
) {
1130 put(output
, command
.data(), command
.size());
1131 put(altern
, command
.data(), command
.size());
1132 position
+= command
.size();
1135 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1136 if (before
> after
) {
1137 pad(output
, before
- after
);
1138 pad(altern
, before
- after
);
1139 position
+= before
- after
;
1142 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1144 std::string
overlap(altern
.str());
1145 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1147 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1148 position
= begin
+ allocation
.size_
;
1150 pad(output
, allocation
.limit_
- allocation
.size_
);
1151 position
+= allocation
.limit_
- allocation
.size_
;
1153 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1154 if (allocation
.alloc_
> saved
)
1155 pad(output
, allocation
.alloc_
- saved
);
1156 position
+= allocation
.alloc_
;
1162 typedef std::map
<uint32_t, std::string
> Blobs
;
1164 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1165 auto value(buffer
.str());
1166 std::swap(blobs
[slot
], value
);
1169 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1170 auto value(buffer
.str());
1172 blob
.magic
= Swap(magic
);
1173 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1174 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1175 std::swap(blobs
[slot
], value
);
1178 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1180 _foreach (blob
, blobs
)
1181 total
+= blob
.second
.size();
1183 struct SuperBlob super
;
1184 super
.blob
.magic
= Swap(magic
);
1185 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1186 super
.count
= Swap(uint32_t(blobs
.size()));
1187 put(output
, &super
, sizeof(super
));
1189 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1191 _foreach (blob
, blobs
) {
1193 index
.type
= Swap(blob
.first
);
1194 index
.offset
= Swap(uint32_t(offset
));
1195 put(output
, &index
, sizeof(index
));
1196 offset
+= blob
.second
.size();
1199 _foreach (blob
, blobs
)
1200 put(output
, blob
.second
.data(), blob
.second
.size());
1213 _assert(bio_
!= NULL
);
1217 bio_(BIO_new(BIO_s_mem()))
1221 Buffer(const char *data
, size_t size
) :
1222 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1226 Buffer(const std::string
&data
) :
1227 Buffer(data
.data(), data
.size())
1231 Buffer(PKCS7
*pkcs
) :
1234 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1241 operator BIO
*() const {
1245 explicit operator std::string() const {
1247 auto size(BIO_get_mem_data(bio_
, &data
));
1248 return std::string(data
, size
);
1257 STACK_OF(X509
) *ca_
;
1261 value_(d2i_PKCS12_bio(bio
, NULL
)),
1264 _assert(value_
!= NULL
);
1265 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1266 _assert(key_
!= NULL
);
1267 _assert(cert_
!= NULL
);
1270 Stuff(const std::string
&data
) :
1276 sk_X509_pop_free(ca_
, X509_free
);
1278 EVP_PKEY_free(key_
);
1279 PKCS12_free(value_
);
1282 operator PKCS12
*() const {
1286 operator EVP_PKEY
*() const {
1290 operator X509
*() const {
1294 operator STACK_OF(X509
) *() const {
1304 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1305 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1307 _assert(value_
!= NULL
);
1314 operator PKCS7
*() const {
1320 public std::streambuf
1323 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1327 virtual int_type
overflow(int_type next
) {
1333 public std::streambuf
1336 std::vector
<char> &hash_
;
1337 LDID_SHA1_CTX context_
;
1340 HashBuffer(std::vector
<char> &hash
) :
1343 LDID_SHA1_Init(&context_
);
1347 hash_
.resize(LDID_SHA1_DIGEST_LENGTH
);
1348 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1351 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1352 LDID_SHA1_Update(&context_
, data
, size
);
1356 virtual int_type
overflow(int_type next
) {
1357 if (next
== traits_type::eof())
1369 std::streambuf
&buffer_
;
1372 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1378 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1379 _assert(HashBuffer::xsputn(data
, size
) == size
);
1380 return buffer_
.sputn(data
, size
);
1384 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1385 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1393 Split(const std::string
&path
) {
1394 size_t slash(path
.rfind('/'));
1395 if (slash
== std::string::npos
)
1398 dir
= path
.substr(0, slash
+ 1);
1399 base
= path
.substr(slash
+ 1);
1404 static void mkdir_p(const std::string
&path
) {
1408 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1411 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1414 auto slash(path
.rfind('/', path
.size() - 1));
1415 if (slash
== std::string::npos
)
1417 mkdir_p(path
.substr(0, slash
));
1420 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1421 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1423 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1427 static void Commit(const std::string
&path
, const std::string
&temp
) {
1429 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1431 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1433 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1436 _syscall(rename(temp
.c_str(), path
.c_str()));
1441 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
) {
1442 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1443 size_t alloc(sizeof(struct SuperBlob
));
1445 uint32_t special(0);
1447 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1448 alloc
+= sizeof(struct BlobIndex
);
1451 if (!entitlements
.empty()) {
1452 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1453 alloc
+= sizeof(struct BlobIndex
);
1454 alloc
+= sizeof(struct Blob
);
1455 alloc
+= entitlements
.size();
1458 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1459 alloc
+= sizeof(struct BlobIndex
);
1460 alloc
+= sizeof(struct Blob
);
1461 alloc
+= sizeof(struct CodeDirectory
);
1462 alloc
+= identifier
.size() + 1;
1465 alloc
+= sizeof(struct BlobIndex
);
1466 alloc
+= sizeof(struct Blob
);
1467 // XXX: this is just a "sufficiently large number"
1471 _foreach (slot
, slots
)
1472 special
= std::max(special
, slot
.first
);
1474 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1475 alloc
= Align(alloc
+ (special
+ normal
) * LDID_SHA1_DIGEST_LENGTH
, 16);
1477 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1481 std::stringbuf data
;
1484 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1486 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1489 if (!entitlements
.empty()) {
1490 std::stringbuf data
;
1491 put(data
, entitlements
.data(), entitlements
.size());
1492 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1496 std::stringbuf data
;
1498 uint32_t special(0);
1499 _foreach (blob
, blobs
)
1500 special
= std::max(special
, blob
.first
);
1501 _foreach (slot
, slots
)
1502 special
= std::max(special
, slot
.first
);
1503 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1505 CodeDirectory directory
;
1506 directory
.version
= Swap(uint32_t(0x00020001));
1507 directory
.flags
= Swap(uint32_t(0));
1508 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + identifier
.size() + 1 + LDID_SHA1_DIGEST_LENGTH
* special
));
1509 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1510 directory
.nSpecialSlots
= Swap(special
);
1511 directory
.codeLimit
= Swap(uint32_t(limit
));
1512 directory
.nCodeSlots
= Swap(normal
);
1513 directory
.hashSize
= LDID_SHA1_DIGEST_LENGTH
;
1514 directory
.hashType
= CS_HASHTYPE_SHA1
;
1515 directory
.spare1
= 0x00;
1516 directory
.pageSize
= PageShift_
;
1517 directory
.spare2
= Swap(uint32_t(0));
1518 put(data
, &directory
, sizeof(directory
));
1520 put(data
, identifier
.c_str(), identifier
.size() + 1);
1522 uint8_t storage
[special
+ normal
][LDID_SHA1_DIGEST_LENGTH
];
1523 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = storage
+ special
;
1525 memset(storage
, 0, sizeof(*storage
) * special
);
1527 _foreach (blob
, blobs
) {
1528 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1529 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1532 _foreach (slot
, slots
) {
1533 _assert(sizeof(*hashes
) == slot
.second
.size());
1534 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1538 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1539 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1541 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1543 put(data
, storage
, sizeof(storage
));
1545 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1549 std::stringbuf data
;
1550 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1555 Signature
signature(stuff
, sign
);
1556 Buffer
result(signature
);
1557 std::string
value(result
);
1558 put(data
, value
.data(), value
.size());
1560 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1563 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1567 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1568 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1570 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1575 std::string
DiskFolder::Path(const std::string
&path
) {
1576 return path_
+ "/" + path
;
1579 DiskFolder::DiskFolder(const std::string
&path
) :
1584 DiskFolder::~DiskFolder() {
1585 if (!std::uncaught_exception())
1586 for (const auto &commit
: commit_
)
1587 Commit(commit
.first
, commit
.second
);
1590 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
) {
1591 std::string
path(Path(root
) + base
);
1593 DIR *dir(opendir(path
.c_str()));
1594 _assert(dir
!= NULL
);
1595 _scope({ _syscall(closedir(dir
)); });
1597 while (auto child
= readdir(dir
)) {
1598 std::string
name(child
->d_name
);
1599 if (name
== "." || name
== "..")
1601 if (Starts(name
, ".ldid."))
1608 _syscall(stat(path
.c_str(), &info
));
1610 else if (S_ISDIR(info
.st_mode
))
1612 else if (S_ISREG(info
.st_mode
))
1615 _assert_(false, "st_mode=%x", info
.st_mode
);
1617 switch (child
->d_type
) {
1625 _assert_(false, "d_type=%u", child
->d_type
);
1630 Find(root
, base
+ name
+ "/", code
);
1632 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1633 std::string
access(root
+ base
+ name
);
1634 _assert_(Open(access
, fun([&](std::streambuf
&data
) {
1637 })), "open(): %s", access
.c_str());
1642 void DiskFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1644 auto from(Path(path
));
1645 commit_
[from
] = Temporary(save
, from
);
1649 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1651 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1654 _assert(result
== &data
);
1659 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1660 Find(path
, "", code
);
1663 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1669 void SubFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1670 return parent_
.Save(path_
+ path
, code
);
1673 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1674 return parent_
.Open(path_
+ path
, code
);
1677 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1678 return parent_
.Find(path_
+ path
, code
);
1681 UnionFolder::UnionFolder(Folder
&parent
) :
1686 void UnionFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1687 return parent_
.Save(path
, code
);
1690 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1691 auto file(files_
.find(path
));
1692 if (file
== files_
.end())
1693 return parent_
.Open(path
, code
);
1695 auto &data(file
->second
);
1696 data
.pubseekpos(0, std::ios::in
);
1701 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1702 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1703 if (files_
.find(name
) == files_
.end())
1707 for (auto &file
: files_
)
1708 code(file
.first
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1709 parent_
.Save(file
.first
, fun([&](std::streambuf
&save
) {
1710 file
.second
.pubseekpos(0, std::ios::in
);
1711 code(file
.second
, save
);
1716 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1720 size_t writ(source
.sgetn(data
, sizeof(data
)));
1723 _assert(target
.sputn(data
, writ
) == writ
);
1729 static plist_t
plist(const std::string
&data
) {
1730 plist_t
plist(NULL
);
1731 if (Starts(data
, "bplist00"))
1732 plist_from_bin(data
.data(), data
.size(), &plist
);
1734 plist_from_xml(data
.data(), data
.size(), &plist
);
1735 _assert(plist
!= NULL
);
1739 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1740 std::stringbuf data
;
1742 auto node(plist(data
.str()));
1743 _scope({ plist_free(node
); });
1744 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1748 static std::string
plist_s(plist_t node
) {
1749 _assert(node
!= NULL
);
1750 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1752 plist_get_string_val(node
, &data
);
1753 _scope({ free(data
); });
1770 Expression(const std::string
&code
) {
1771 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1778 bool operator ()(const std::string
&data
) const {
1779 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1780 if (value
== REG_NOMATCH
)
1782 _assert_(value
== 0, "regexec()");
1792 mutable std::auto_ptr
<Expression
> regex_
;
1794 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1801 Rule(const Rule
&rhs
) :
1802 weight_(rhs
.weight_
),
1808 void Compile() const {
1809 regex_
.reset(new Expression(code_
));
1812 bool operator ()(const std::string
&data
) const {
1813 _assert(regex_
.get() != NULL
);
1814 return (*regex_
)(data
);
1817 bool operator <(const Rule
&rhs
) const {
1818 if (weight_
> rhs
.weight_
)
1820 if (weight_
< rhs
.weight_
)
1822 return mode_
> rhs
.mode_
;
1827 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1828 return lhs
->code_
< rhs
->code_
;
1832 std::string
Bundle(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, std::vector
<char>> &remote
, const std::string
&entitlements
) {
1833 std::string executable
;
1834 std::string identifier
;
1836 static const std::string
info("Info.plist");
1838 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
) {
1839 plist_d(buffer
, fun([&](plist_t node
) {
1840 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1841 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1843 })), "open(): Info.plist");
1845 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1847 auto &rules1(versions
[""]);
1848 auto &rules2(versions
["2"]);
1850 static const std::string
signature("_CodeSignature/CodeResources");
1852 folder
.Open(signature
, fun([&](std::streambuf
&buffer
) {
1853 plist_d(buffer
, fun([&](plist_t node
) {
1854 // XXX: maybe attempt to preserve existing rules
1859 rules1
.insert(Rule
{1, NoMode
, "^"});
1860 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1861 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1862 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1863 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1864 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1868 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1869 rules2
.insert(Rule
{20, NoMode
, "^"});
1870 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1871 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1872 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1873 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1874 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1875 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1876 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1877 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1878 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1879 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1880 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1881 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1884 std::map
<std::string
, std::vector
<char>> local
;
1886 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1888 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1891 auto bundle(root
+ Split(name
).dir
);
1892 SubFolder
subfolder(folder
, bundle
);
1893 Bundle(bundle
, subfolder
, key
, local
, "");
1896 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1897 if (name
== executable
|| name
== signature
)
1900 auto &hash(local
[name
]);
1904 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1905 HashProxy
proxy(hash
, save
);
1909 _assert(hash
.size() == LDID_SHA1_DIGEST_LENGTH
);
1912 auto plist(plist_new_dict());
1913 _scope({ plist_free(plist
); });
1915 for (const auto &version
: versions
) {
1916 auto files(plist_new_dict());
1917 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
1919 for (const auto &rule
: version
.second
)
1922 for (const auto &hash
: local
)
1923 for (const auto &rule
: version
.second
)
1924 if (rule(hash
.first
)) {
1925 if (rule
.mode_
== NoMode
)
1926 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
1927 else if (rule
.mode_
== OptionalMode
) {
1928 auto entry(plist_new_dict());
1929 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
1930 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1931 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
1938 for (const auto &version
: versions
) {
1939 auto rules(plist_new_dict());
1940 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
1942 std::multiset
<const Rule
*, RuleCode
> ordered
;
1943 for (const auto &rule
: version
.second
)
1944 ordered
.insert(&rule
);
1946 for (const auto &rule
: ordered
)
1947 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
1948 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
1950 auto entry(plist_new_dict());
1951 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
1953 switch (rule
->mode_
) {
1957 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
1960 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1963 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
1966 plist_dict_set_item(entry
, "top", plist_new_bool(true));
1970 if (rule
->weight_
>= 10000)
1971 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
1972 else if (rule
->weight_
!= 1)
1973 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
1977 folder
.Save(signature
, fun([&](std::streambuf
&save
) {
1978 HashProxy
proxy(local
[signature
], save
);
1981 plist_to_xml(plist
, &xml
, &size
);
1982 _scope({ free(xml
); });
1983 put(proxy
, xml
, size
);
1986 folder
.Open(executable
, fun([&](std::streambuf
&buffer
) {
1987 // XXX: this is a miserable fail
1988 std::stringbuf temp
;
1990 auto data(temp
.str());
1992 folder
.Save(executable
, fun([&](std::streambuf
&save
) {
1994 slots
[1] = local
.at(info
);
1995 slots
[3] = local
.at(signature
);
1997 HashProxy
proxy(local
[executable
], save
);
1998 Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, key
, slots
);
2002 for (const auto &hash
: local
)
2003 remote
[root
+ hash
.first
] = hash
.second
;
2010 int main(int argc
, char *argv
[]) {
2011 OpenSSL_add_all_algorithms();
2018 little_
= endian
.byte
[0];
2033 uint32_t flag_CPUType(_not(uint32_t));
2034 uint32_t flag_CPUSubtype(_not(uint32_t));
2036 const char *flag_I(NULL
);
2045 std::vector
<std::string
> files
;
2048 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2049 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2050 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2051 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2055 for (int argi(1); argi
!= argc
; ++argi
)
2056 if (argv
[argi
][0] != '-')
2057 files
.push_back(argv
[argi
]);
2058 else switch (argv
[argi
][1]) {
2065 case 'e': flag_e
= true; break;
2068 const char *slot
= argv
[argi
] + 2;
2069 const char *colon
= strchr(slot
, ':');
2070 _assert(colon
!= NULL
);
2071 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2073 unsigned number(strtoul(slot
, &arge
, 0));
2074 _assert(arge
== colon
);
2075 std::vector
<char> &hash(slots
[number
]);
2076 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
2077 sha1(reinterpret_cast<uint8_t *>(hash
.data()), file
.data(), file
.size());
2080 case 'D': flag_D
= true; break;
2082 case 'a': flag_a
= true; break;
2087 if (argv
[argi
][2] != '\0') {
2088 const char *cpu
= argv
[argi
] + 2;
2089 const char *colon
= strchr(cpu
, ':');
2090 _assert(colon
!= NULL
);
2092 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2093 _assert(arge
== colon
);
2094 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2095 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2109 if (argv
[argi
][2] != '\0') {
2110 const char *xml
= argv
[argi
] + 2;
2111 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2116 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2121 if (argv
[argi
][2] == '-')
2125 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2126 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2131 flag_I
= argv
[argi
] + 2;
2139 _assert(flag_S
|| key
.empty());
2140 _assert(flag_S
|| flag_I
== NULL
);
2142 if (files
.empty()) usage
: {
2146 size_t filei(0), filee(0);
2147 _foreach (file
, files
) try {
2148 std::string
path(file
);
2151 _syscall(stat(path
.c_str(), &info
));
2153 if (S_ISDIR(info
.st_mode
)) {
2155 ldid::DiskFolder
folder(path
);
2156 std::map
<std::string
, std::vector
<char>> hashes
;
2157 path
+= "/" + Bundle("", folder
, key
, hashes
, entitlements
);
2158 } else if (flag_S
|| flag_r
) {
2159 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2161 std::filebuf output
;
2163 auto temp(Temporary(output
, split
));
2166 ldid::Unsign(input
.data(), input
.size(), output
);
2168 std::string
identifier(flag_I
?: split
.base
.c_str());
2169 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2175 Map
mapping(path
, flag_T
|| flag_s
);
2176 FatHeader
fat_header(mapping
.data(), mapping
.size());
2178 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2179 struct linkedit_data_command
*signature(NULL
);
2180 struct encryption_info_command
*encryption(NULL
);
2183 if (mach_header
.GetCPUType() != flag_CPUType
)
2185 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2190 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2192 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2193 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2196 else if (cmd
== LC_CODE_SIGNATURE
)
2197 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2198 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2199 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2200 else if (cmd
== LC_ID_DYLIB
) {
2201 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2209 dylib_command
->dylib
.timestamp
= 0;
2210 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2213 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2219 _assert(encryption
!= NULL
);
2220 encryption
->cryptid
= mach_header
.Swap(0);
2224 _assert(signature
!= NULL
);
2226 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2228 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2229 uint8_t *blob
= top
+ data
;
2230 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2232 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2233 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2234 uint32_t begin
= Swap(super
->index
[index
].offset
);
2235 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2236 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2241 _assert(signature
!= NULL
);
2243 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2245 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2246 uint8_t *blob
= top
+ data
;
2247 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2249 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2250 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2251 uint32_t begin
= Swap(super
->index
[index
].offset
);
2252 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2254 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2255 uint32_t pages
= Swap(directory
->nCodeSlots
);
2258 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2259 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2261 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2267 } catch (const char *) {