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>
46 #include <openssl/err.h>
47 #include <openssl/pem.h>
48 #include <openssl/pkcs7.h>
49 #include <openssl/pkcs12.h>
53 #include <CommonCrypto/CommonDigest.h>
54 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
55 #define LDID_SHA1 CC_SHA1
56 #define LDID_SHA1_CTX CC_SHA1_CTX
57 #define LDID_SHA1_Init CC_SHA1_Init
58 #define LDID_SHA1_Update CC_SHA1_Update
59 #define LDID_SHA1_Final CC_SHA1_Final
61 #include <openssl/sha.h>
62 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
63 #define LDID_SHA1 SHA1
64 #define LDID_SHA1_CTX SHA_CTX
65 #define LDID_SHA1_Init SHA1_Init
66 #define LDID_SHA1_Update SHA1_Update
67 #define LDID_SHA1_Final SHA1_Final
71 #include <plist/plist.h>
76 #define _assert___(line) \
78 #define _assert__(line) \
82 #define _assert_(expr, format, ...) \
84 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
85 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
88 // XXX: this is not acceptable
89 #define _assert_(expr, format, ...) \
91 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
96 #define _assert(expr) \
97 _assert_(expr, "%s", #expr)
99 #define _syscall(expr, ...) [&] { for (;;) { \
101 if ((long) _value != -1) \
104 if (error == EINTR) \
106 /* XXX: EINTR is included in this list to fix g++ */ \
107 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
108 if (error == success) \
109 return (decltype(expr)) -success; \
110 _assert_(false, "errno=%u", error); \
114 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
120 __attribute__((packed))
122 template <typename Type_
>
124 typedef typename
Type_::const_iterator Result
;
127 #define _foreach(item, list) \
128 for (bool _stop(true); _stop; ) \
129 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
130 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
131 for (bool _suck(true); _suck; _suck = false) \
132 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
137 template <typename Function_
>
145 Scope(const Function_
&function
) :
155 template <typename Function_
>
156 Scope
<Function_
> _scope(const Function_
&function
) {
157 return Scope
<Function_
>(function
);
160 #define _scope__(counter, function) \
161 __attribute__((__unused__)) \
162 const _Scope &_scope ## counter(_scope([&]function))
163 #define _scope_(counter, function) \
164 _scope__(counter, function)
165 #define _scope(function) \
166 _scope_(__COUNTER__, function)
168 #define CPU_ARCH_MASK uint32_t(0xff000000)
169 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
171 #define CPU_TYPE_ANY uint32_t(-1)
172 #define CPU_TYPE_VAX uint32_t( 1)
173 #define CPU_TYPE_MC680x0 uint32_t( 6)
174 #define CPU_TYPE_X86 uint32_t( 7)
175 #define CPU_TYPE_MC98000 uint32_t(10)
176 #define CPU_TYPE_HPPA uint32_t(11)
177 #define CPU_TYPE_ARM uint32_t(12)
178 #define CPU_TYPE_MC88000 uint32_t(13)
179 #define CPU_TYPE_SPARC uint32_t(14)
180 #define CPU_TYPE_I860 uint32_t(15)
181 #define CPU_TYPE_POWERPC uint32_t(18)
183 #define CPU_TYPE_I386 CPU_TYPE_X86
185 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
186 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
187 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
194 #define FAT_MAGIC 0xcafebabe
195 #define FAT_CIGAM 0xbebafeca
215 #define MH_MAGIC 0xfeedface
216 #define MH_CIGAM 0xcefaedfe
218 #define MH_MAGIC_64 0xfeedfacf
219 #define MH_CIGAM_64 0xcffaedfe
221 #define MH_DYLDLINK 0x4
223 #define MH_OBJECT 0x1
224 #define MH_EXECUTE 0x2
226 #define MH_BUNDLE 0x8
227 #define MH_DYLIB_STUB 0x9
229 struct load_command
{
234 #define LC_REQ_DYLD uint32_t(0x80000000)
236 #define LC_SEGMENT uint32_t(0x01)
237 #define LC_SYMTAB uint32_t(0x02)
238 #define LC_DYSYMTAB uint32_t(0x0b)
239 #define LC_LOAD_DYLIB uint32_t(0x0c)
240 #define LC_ID_DYLIB uint32_t(0x0d)
241 #define LC_SEGMENT_64 uint32_t(0x19)
242 #define LC_UUID uint32_t(0x1b)
243 #define LC_CODE_SIGNATURE uint32_t(0x1d)
244 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
245 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
246 #define LC_ENCRYPTION_INFO uint32_t(0x21)
247 #define LC_DYLD_INFO uint32_t(0x22)
248 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
249 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
264 uint32_t current_version
;
265 uint32_t compatibility_version
;
268 struct dylib_command
{
274 struct uuid_command
{
280 struct symtab_command
{
289 struct dyld_info_command
{
293 uint32_t rebase_size
;
296 uint32_t weak_bind_off
;
297 uint32_t weak_bind_size
;
298 uint32_t lazy_bind_off
;
299 uint32_t lazy_bind_size
;
301 uint32_t export_size
;
304 struct dysymtab_command
{
317 uint32_t extrefsymoff
;
318 uint32_t nextrefsyms
;
319 uint32_t indirectsymoff
;
320 uint32_t nindirectsyms
;
327 struct dylib_table_of_contents
{
328 uint32_t symbol_index
;
329 uint32_t module_index
;
332 struct dylib_module
{
333 uint32_t module_name
;
342 uint32_t iinit_iterm
;
343 uint32_t ninit_nterm
;
344 uint32_t objc_module_info_addr
;
345 uint32_t objc_module_info_size
;
348 struct dylib_reference
{
353 struct relocation_info
{
355 uint32_t r_symbolnum
:24;
374 struct segment_command
{
388 struct segment_command_64
{
431 struct linkedit_data_command
{
438 struct encryption_info_command
{
446 #define BIND_OPCODE_MASK 0xf0
447 #define BIND_IMMEDIATE_MASK 0x0f
448 #define BIND_OPCODE_DONE 0x00
449 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
450 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
451 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
452 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
453 #define BIND_OPCODE_SET_TYPE_IMM 0x50
454 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
455 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
456 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
457 #define BIND_OPCODE_DO_BIND 0x90
458 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
459 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
460 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
462 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
463 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
466 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
467 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
470 inline void pad(std::streambuf
&stream
, size_t size
) {
472 memset(padding
, 0, size
);
473 put(stream
, padding
, size
);
476 template <typename Type_
>
477 Type_
Align(Type_ value
, size_t align
) {
484 static const uint8_t PageShift_(0x0c);
485 static const uint32_t PageSize_(1 << PageShift_
);
487 static inline uint16_t Swap_(uint16_t value
) {
489 ((value
>> 8) & 0x00ff) |
490 ((value
<< 8) & 0xff00);
493 static inline uint32_t Swap_(uint32_t value
) {
494 value
= ((value
>> 8) & 0x00ff00ff) |
495 ((value
<< 8) & 0xff00ff00);
496 value
= ((value
>> 16) & 0x0000ffff) |
497 ((value
<< 16) & 0xffff0000);
501 static inline uint64_t Swap_(uint64_t value
) {
502 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
503 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
504 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
508 static inline int16_t Swap_(int16_t value
) {
509 return Swap_(static_cast<uint16_t>(value
));
512 static inline int32_t Swap_(int32_t value
) {
513 return Swap_(static_cast<uint32_t>(value
));
516 static inline int64_t Swap_(int64_t value
) {
517 return Swap_(static_cast<uint64_t>(value
));
520 static bool little_(true);
522 static inline uint16_t Swap(uint16_t value
) {
523 return little_
? Swap_(value
) : value
;
526 static inline uint32_t Swap(uint32_t value
) {
527 return little_
? Swap_(value
) : value
;
530 static inline uint64_t Swap(uint64_t value
) {
531 return little_
? Swap_(value
) : value
;
534 static inline int16_t Swap(int16_t value
) {
535 return Swap(static_cast<uint16_t>(value
));
538 static inline int32_t Swap(int32_t value
) {
539 return Swap(static_cast<uint32_t>(value
));
542 static inline int64_t Swap(int64_t value
) {
543 return Swap(static_cast<uint64_t>(value
));
556 Swapped(bool swapped
) :
561 template <typename Type_
>
562 Type_
Swap(Type_ value
) const {
563 return swapped_
? Swap_(value
) : value
;
575 Data(void *base
, size_t size
) :
581 void *GetBase() const {
585 size_t GetSize() const {
596 struct mach_header
*mach_header_
;
597 struct load_command
*load_command_
;
600 MachHeader(void *base
, size_t size
) :
603 mach_header_
= (mach_header
*) base
;
605 switch (Swap(mach_header_
->magic
)) {
607 swapped_
= !swapped_
;
613 swapped_
= !swapped_
;
622 void *post
= mach_header_
+ 1;
624 post
= (uint32_t *) post
+ 1;
625 load_command_
= (struct load_command
*) post
;
628 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
629 Swap(mach_header_
->filetype
) == MH_DYLIB
||
630 Swap(mach_header_
->filetype
) == MH_BUNDLE
634 bool Bits64() const {
638 struct mach_header
*operator ->() const {
642 operator struct mach_header
*() const {
646 uint32_t GetCPUType() const {
647 return Swap(mach_header_
->cputype
);
650 uint32_t GetCPUSubtype() const {
651 return Swap(mach_header_
->cpusubtype
) & 0xff;
654 struct load_command
*GetLoadCommand() const {
655 return load_command_
;
658 std::vector
<struct load_command
*> GetLoadCommands() const {
659 std::vector
<struct load_command
*> load_commands
;
661 struct load_command
*load_command
= load_command_
;
662 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
663 load_commands
.push_back(load_command
);
664 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
667 return load_commands
;
670 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
671 _foreach (load_command
, GetLoadCommands())
672 switch (Swap(load_command
->cmd
)) {
674 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
675 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
676 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
677 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
678 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
681 case LC_SEGMENT_64
: {
682 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
683 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
684 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
685 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
686 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
691 template <typename Target_
>
692 Target_
*GetOffset(uint32_t offset
) const {
693 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
697 class FatMachHeader
:
704 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
705 MachHeader(base
, size
),
710 fat_arch
*GetFatArch() const {
719 fat_header
*fat_header_
;
720 std::vector
<FatMachHeader
> mach_headers_
;
723 FatHeader(void *base
, size_t size
) :
726 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
728 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
729 swapped_
= !swapped_
;
731 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
733 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
735 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
736 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
738 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
739 uint32_t arch_offset
= Swap(fat_arch
->offset
);
740 uint32_t arch_size
= Swap(fat_arch
->size
);
741 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
747 std::vector
<FatMachHeader
> &GetMachHeaders() {
748 return mach_headers_
;
752 return fat_header_
!= NULL
;
755 struct fat_header
*operator ->() const {
759 operator struct fat_header
*() const {
764 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
765 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
766 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
767 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
768 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
769 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
770 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
771 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
773 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
774 #define CSSLOT_INFOSLOT uint32_t(0x00001)
775 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
776 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
777 #define CSSLOT_APPLICATION uint32_t(0x00004)
778 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
780 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
782 #define CS_HASHTYPE_SHA1 1
797 struct BlobIndex index
[];
800 struct CodeDirectory
{
804 uint32_t identOffset
;
805 uint32_t nSpecialSlots
;
816 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
819 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
820 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
823 static void sha1(std::vector
<char> &hash
, const void *data
, size_t size
) {
824 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
825 sha1(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
828 struct CodesignAllocation
{
829 FatMachHeader mach_header_
;
836 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
837 mach_header_(mach_header
),
860 _syscall(close(file_
));
863 void open(const char *path
, int flags
) {
864 _assert(file_
== -1);
865 file_
= _syscall(::open(path
, flags
));
882 _syscall(munmap(data_
, size_
));
894 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
897 open(path
, oflag
, pflag
, mflag
);
900 Map(const std::string
&path
, bool edit
) :
911 return data_
== NULL
;
914 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
917 file_
.open(path
.c_str(), oflag
);
918 int file(file_
.file());
921 _syscall(fstat(file
, &stat
));
922 size_
= stat
.st_size
;
924 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
927 void open(const std::string
&path
, bool edit
) {
929 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
931 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
938 size_t size() const {
942 operator std::string() const {
943 return std::string(static_cast<char *>(data_
), size_
);
950 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, std::streambuf
&output
, size_t, const std::string
&, const char *)> &save
) {
951 FatHeader
source(const_cast<void *>(idata
), isize
);
955 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
957 std::vector
<CodesignAllocation
> allocations
;
958 _foreach (mach_header
, source
.GetMachHeaders()) {
959 struct linkedit_data_command
*signature(NULL
);
960 struct symtab_command
*symtab(NULL
);
962 _foreach (load_command
, mach_header
.GetLoadCommands()) {
963 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
965 else if (cmd
== LC_CODE_SIGNATURE
)
966 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
967 else if (cmd
== LC_SYMTAB
)
968 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
972 if (signature
== NULL
)
973 size
= mach_header
.GetSize();
975 size
= mach_header
.Swap(signature
->dataoff
);
976 _assert(size
<= mach_header
.GetSize());
979 if (symtab
!= NULL
) {
980 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
981 _assert(end
<= size
);
982 _assert(end
>= size
- 0x10);
986 size_t alloc(allocate(mach_header
, size
));
988 auto *fat_arch(mach_header
.GetFatArch());
991 if (fat_arch
!= NULL
)
992 align
= source
.Swap(fat_arch
->align
);
993 else switch (mach_header
.GetCPUType()) {
994 case CPU_TYPE_POWERPC
:
995 case CPU_TYPE_POWERPC64
:
997 case CPU_TYPE_X86_64
:
1001 case CPU_TYPE_ARM64
:
1009 offset
= Align(offset
, 1 << align
);
1011 uint32_t limit(size
);
1013 limit
= Align(limit
, 0x10);
1015 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1016 offset
+= size
+ alloc
;
1017 offset
= Align(offset
, 0x10);
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
);
1029 _foreach (allocation
, allocations
) {
1030 auto &mach_header(allocation
.mach_header_
);
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
);
1043 _foreach (allocation
, allocations
) {
1044 auto &mach_header(allocation
.mach_header_
);
1046 pad(output
, allocation
.offset_
- position
);
1047 position
= allocation
.offset_
;
1049 std::vector
<std::string
> commands
;
1051 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1052 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1054 switch (mach_header
.Swap(load_command
->cmd
)) {
1055 case LC_CODE_SIGNATURE
:
1060 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1061 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
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
, 1 << allocation
.align_
);
1068 case LC_SEGMENT_64
: {
1069 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1070 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
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
, 1 << allocation
.align_
);
1078 commands
.push_back(copy
);
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
)));
1090 size_t begin(position
);
1093 _foreach(command
, commands
)
1094 after
+= command
.size();
1096 std::stringbuf altern
;
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
);
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
);
1112 _foreach(command
, commands
) {
1113 put(output
, command
.data(), command
.size());
1114 put(altern
, command
.data(), command
.size());
1115 position
+= command
.size();
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
;
1125 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1127 std::string
overlap(altern
.str());
1128 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1130 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1131 position
= begin
+ allocation
.size_
;
1133 pad(output
, allocation
.limit_
- allocation
.size_
);
1134 position
+= allocation
.limit_
- allocation
.size_
;
1136 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
));
1137 if (allocation
.alloc_
> saved
)
1138 pad(output
, allocation
.alloc_
- saved
);
1139 position
+= allocation
.alloc_
;
1145 typedef std::map
<uint32_t, std::string
> Blobs
;
1147 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1148 auto value(buffer
.str());
1149 std::swap(blobs
[slot
], value
);
1152 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1153 auto value(buffer
.str());
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
);
1161 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1163 _foreach (blob
, blobs
)
1164 total
+= blob
.second
.size();
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
));
1172 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1174 _foreach (blob
, blobs
) {
1176 index
.type
= Swap(blob
.first
);
1177 index
.offset
= Swap(uint32_t(offset
));
1178 put(output
, &index
, sizeof(index
));
1179 offset
+= blob
.second
.size();
1182 _foreach (blob
, blobs
)
1183 put(output
, blob
.second
.data(), blob
.second
.size());
1188 #ifndef LDID_NOSMIME
1197 _assert(bio_
!= NULL
);
1201 bio_(BIO_new(BIO_s_mem()))
1205 Buffer(const char *data
, size_t size
) :
1206 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1210 Buffer(const std::string
&data
) :
1211 Buffer(data
.data(), data
.size())
1215 Buffer(PKCS7
*pkcs
) :
1218 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1225 operator BIO
*() const {
1229 explicit operator std::string() const {
1231 auto size(BIO_get_mem_data(bio_
, &data
));
1232 return std::string(data
, size
);
1241 STACK_OF(X509
) *ca_
;
1245 value_(d2i_PKCS12_bio(bio
, NULL
)),
1248 _assert(value_
!= NULL
);
1249 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1250 _assert(key_
!= NULL
);
1251 _assert(cert_
!= NULL
);
1254 Stuff(const std::string
&data
) :
1260 sk_X509_pop_free(ca_
, X509_free
);
1262 EVP_PKEY_free(key_
);
1263 PKCS12_free(value_
);
1266 operator PKCS12
*() const {
1270 operator EVP_PKEY
*() const {
1274 operator X509
*() const {
1278 operator STACK_OF(X509
) *() const {
1288 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1289 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1291 _assert(value_
!= NULL
);
1298 operator PKCS7
*() const {
1305 public std::streambuf
1308 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1312 virtual int_type
overflow(int_type next
) {
1318 public std::streambuf
1321 std::vector
<char> &hash_
;
1322 LDID_SHA1_CTX context_
;
1325 HashBuffer(std::vector
<char> &hash
) :
1328 LDID_SHA1_Init(&context_
);
1332 hash_
.resize(LDID_SHA1_DIGEST_LENGTH
);
1333 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1336 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1337 LDID_SHA1_Update(&context_
, data
, size
);
1341 virtual int_type
overflow(int_type next
) {
1342 if (next
== traits_type::eof())
1354 std::streambuf
&buffer_
;
1357 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1363 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1364 _assert(HashBuffer::xsputn(data
, size
) == size
);
1365 return buffer_
.sputn(data
, size
);
1369 #ifndef LDID_NOTOOLS
1370 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1371 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1379 Split(const std::string
&path
) {
1380 size_t slash(path
.rfind('/'));
1381 if (slash
== std::string::npos
)
1384 dir
= path
.substr(0, slash
+ 1);
1385 base
= path
.substr(slash
+ 1);
1390 static void mkdir_p(const std::string
&path
) {
1394 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1397 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1400 auto slash(path
.rfind('/', path
.size() - 1));
1401 if (slash
== std::string::npos
)
1403 mkdir_p(path
.substr(0, slash
));
1406 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1407 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1409 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1413 static void Commit(const std::string
&path
, const std::string
&temp
) {
1415 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1417 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1419 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1422 _syscall(rename(temp
.c_str(), path
.c_str()));
1428 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
) {
1429 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1430 size_t alloc(sizeof(struct SuperBlob
));
1432 uint32_t special(0);
1434 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1435 alloc
+= sizeof(struct BlobIndex
);
1438 if (!entitlements
.empty()) {
1439 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1440 alloc
+= sizeof(struct BlobIndex
);
1441 alloc
+= sizeof(struct Blob
);
1442 alloc
+= entitlements
.size();
1445 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1446 alloc
+= sizeof(struct BlobIndex
);
1447 alloc
+= sizeof(struct Blob
);
1448 alloc
+= sizeof(struct CodeDirectory
);
1449 alloc
+= identifier
.size() + 1;
1452 alloc
+= sizeof(struct BlobIndex
);
1453 alloc
+= sizeof(struct Blob
);
1454 // XXX: this is just a "sufficiently large number"
1458 _foreach (slot
, slots
)
1459 special
= std::max(special
, slot
.first
);
1461 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1462 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1463 special
= std::max(special
, CSSLOT_INFOSLOT
);
1466 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1467 alloc
= Align(alloc
+ (special
+ normal
) * LDID_SHA1_DIGEST_LENGTH
, 16);
1469 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1473 std::stringbuf data
;
1476 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1478 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1481 if (!entitlements
.empty()) {
1482 std::stringbuf data
;
1483 put(data
, entitlements
.data(), entitlements
.size());
1484 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1488 std::stringbuf data
;
1492 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1493 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1494 sha1(posts
[CSSLOT_INFOSLOT
], data
, size
);
1497 uint32_t special(0);
1498 _foreach (blob
, blobs
)
1499 special
= std::max(special
, blob
.first
);
1500 _foreach (slot
, posts
)
1501 special
= std::max(special
, slot
.first
);
1502 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1504 CodeDirectory directory
;
1505 directory
.version
= Swap(uint32_t(0x00020001));
1506 directory
.flags
= Swap(uint32_t(0));
1507 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + identifier
.size() + 1 + LDID_SHA1_DIGEST_LENGTH
* special
));
1508 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1509 directory
.nSpecialSlots
= Swap(special
);
1510 directory
.codeLimit
= Swap(uint32_t(limit
));
1511 directory
.nCodeSlots
= Swap(normal
);
1512 directory
.hashSize
= LDID_SHA1_DIGEST_LENGTH
;
1513 directory
.hashType
= CS_HASHTYPE_SHA1
;
1514 directory
.spare1
= 0x00;
1515 directory
.pageSize
= PageShift_
;
1516 directory
.spare2
= Swap(uint32_t(0));
1517 put(data
, &directory
, sizeof(directory
));
1519 put(data
, identifier
.c_str(), identifier
.size() + 1);
1521 uint8_t storage
[special
+ normal
][LDID_SHA1_DIGEST_LENGTH
];
1522 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = storage
+ special
;
1524 memset(storage
, 0, sizeof(*storage
) * special
);
1526 _foreach (blob
, blobs
) {
1527 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1528 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1531 _foreach (slot
, posts
) {
1532 _assert(sizeof(*hashes
) == slot
.second
.size());
1533 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1537 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1538 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1540 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1542 put(data
, storage
, sizeof(storage
));
1544 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1547 #ifndef LDID_NOSMIME
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
);
1564 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1568 #ifndef LDID_NOTOOLS
1569 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1570 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1572 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1577 std::string
DiskFolder::Path(const std::string
&path
) {
1578 return path_
+ "/" + path
;
1581 DiskFolder::DiskFolder(const std::string
&path
) :
1586 DiskFolder::~DiskFolder() {
1587 if (!std::uncaught_exception())
1588 for (const auto &commit
: commit_
)
1589 Commit(commit
.first
, commit
.second
);
1592 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
) {
1593 std::string
path(Path(root
) + base
);
1595 DIR *dir(opendir(path
.c_str()));
1596 _assert(dir
!= NULL
);
1597 _scope({ _syscall(closedir(dir
)); });
1599 while (auto child
= readdir(dir
)) {
1600 std::string
name(child
->d_name
);
1601 if (name
== "." || name
== "..")
1603 if (Starts(name
, ".ldid."))
1610 _syscall(stat(path
.c_str(), &info
));
1612 else if (S_ISDIR(info
.st_mode
))
1614 else if (S_ISREG(info
.st_mode
))
1617 _assert_(false, "st_mode=%x", info
.st_mode
);
1619 switch (child
->d_type
) {
1627 _assert_(false, "d_type=%u", child
->d_type
);
1632 Find(root
, base
+ name
+ "/", code
);
1634 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1635 std::string
access(root
+ base
+ name
);
1636 _assert_(Open(access
, fun([&](std::streambuf
&data
) {
1639 })), "open(): %s", access
.c_str());
1644 void DiskFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1646 auto from(Path(path
));
1647 commit_
[from
] = Temporary(save
, from
);
1651 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1653 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1656 _assert(result
== &data
);
1661 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1662 Find(path
, "", code
);
1666 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1672 void SubFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1673 return parent_
.Save(path_
+ path
, code
);
1676 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1677 return parent_
.Open(path_
+ path
, code
);
1680 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1681 return parent_
.Find(path_
+ path
, code
);
1684 UnionFolder::UnionFolder(Folder
&parent
) :
1689 void UnionFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1690 return parent_
.Save(path
, code
);
1693 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1694 auto file(files_
.find(path
));
1695 if (file
== files_
.end())
1696 return parent_
.Open(path
, code
);
1698 auto &data(file
->second
);
1699 data
.pubseekpos(0, std::ios::in
);
1704 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1705 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1706 if (files_
.find(path
+ name
) == files_
.end())
1710 for (auto &file
: files_
)
1711 if (file
.first
.size() >= path
.size() && file
.first
.substr(0, path
.size()) == path
)
1712 code(file
.first
.substr(path
.size()), fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1713 parent_
.Save(file
.first
, fun([&](std::streambuf
&save
) {
1714 file
.second
.pubseekpos(0, std::ios::in
);
1715 code(file
.second
, save
);
1720 #ifndef LDID_NOTOOLS
1721 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1725 size_t writ(source
.sgetn(data
, sizeof(data
)));
1728 _assert(target
.sputn(data
, writ
) == writ
);
1734 #ifndef LDID_NOPLIST
1735 static plist_t
plist(const std::string
&data
) {
1736 plist_t
plist(NULL
);
1737 if (Starts(data
, "bplist00"))
1738 plist_from_bin(data
.data(), data
.size(), &plist
);
1740 plist_from_xml(data
.data(), data
.size(), &plist
);
1741 _assert(plist
!= NULL
);
1745 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1746 std::stringbuf data
;
1748 auto node(plist(data
.str()));
1749 _scope({ plist_free(node
); });
1750 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1754 static std::string
plist_s(plist_t node
) {
1755 _assert(node
!= NULL
);
1756 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1758 plist_get_string_val(node
, &data
);
1759 _scope({ free(data
); });
1777 Expression(const std::string
&code
) {
1778 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1785 bool operator ()(const std::string
&data
) const {
1786 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1787 if (value
== REG_NOMATCH
)
1789 _assert_(value
== 0, "regexec()");
1799 mutable std::auto_ptr
<Expression
> regex_
;
1801 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1808 Rule(const Rule
&rhs
) :
1809 weight_(rhs
.weight_
),
1815 void Compile() const {
1816 regex_
.reset(new Expression(code_
));
1819 bool operator ()(const std::string
&data
) const {
1820 _assert(regex_
.get() != NULL
);
1821 return (*regex_
)(data
);
1824 bool operator <(const Rule
&rhs
) const {
1825 if (weight_
> rhs
.weight_
)
1827 if (weight_
< rhs
.weight_
)
1829 return mode_
> rhs
.mode_
;
1834 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1835 return lhs
->code_
< rhs
->code_
;
1839 #ifndef LDID_NOPLIST
1840 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
) {
1841 std::string executable
;
1842 std::string identifier
;
1844 static const std::string
info("Info.plist");
1846 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
) {
1847 plist_d(buffer
, fun([&](plist_t node
) {
1848 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1849 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1851 })), "open(): Info.plist");
1853 static const std::string
directory("_CodeSignature/");
1854 static const std::string
signature(directory
+ "CodeResources");
1856 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1858 auto &rules1(versions
[""]);
1859 auto &rules2(versions
["2"]);
1861 folder
.Open(signature
, fun([&](std::streambuf
&buffer
) {
1862 plist_d(buffer
, fun([&](plist_t node
) {
1863 // XXX: maybe attempt to preserve existing rules
1868 rules1
.insert(Rule
{1, NoMode
, "^"});
1869 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1870 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1871 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1872 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1873 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1877 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1878 rules2
.insert(Rule
{20, NoMode
, "^"});
1879 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1880 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1881 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1882 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1883 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1884 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1885 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1886 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1887 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1888 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1889 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1890 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1893 std::map
<std::string
, std::vector
<char>> local
;
1895 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1897 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1900 auto bundle(root
+ Split(name
).dir
);
1901 SubFolder
subfolder(folder
, bundle
);
1902 Bundle(bundle
, subfolder
, key
, local
, "");
1905 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1906 // BundleDiskRep::adjustResources -> builder.addExclusion
1907 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
1910 auto &hash(local
[name
]);
1914 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1915 HashProxy
proxy(hash
, save
);
1919 _assert(hash
.size() == LDID_SHA1_DIGEST_LENGTH
);
1922 auto plist(plist_new_dict());
1923 _scope({ plist_free(plist
); });
1925 for (const auto &version
: versions
) {
1926 auto files(plist_new_dict());
1927 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
1929 for (const auto &rule
: version
.second
)
1932 for (const auto &hash
: local
)
1933 for (const auto &rule
: version
.second
)
1934 if (rule(hash
.first
)) {
1935 if (rule
.mode_
== NoMode
)
1936 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
1937 else if (rule
.mode_
== OptionalMode
) {
1938 auto entry(plist_new_dict());
1939 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
1940 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1941 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
1948 for (const auto &version
: versions
) {
1949 auto rules(plist_new_dict());
1950 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
1952 std::multiset
<const Rule
*, RuleCode
> ordered
;
1953 for (const auto &rule
: version
.second
)
1954 ordered
.insert(&rule
);
1956 for (const auto &rule
: ordered
)
1957 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
1958 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
1960 auto entry(plist_new_dict());
1961 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
1963 switch (rule
->mode_
) {
1967 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
1970 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1973 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
1976 plist_dict_set_item(entry
, "top", plist_new_bool(true));
1980 if (rule
->weight_
>= 10000)
1981 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
1982 else if (rule
->weight_
!= 1)
1983 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
1987 folder
.Save(signature
, fun([&](std::streambuf
&save
) {
1988 HashProxy
proxy(local
[signature
], save
);
1991 plist_to_xml(plist
, &xml
, &size
);
1992 _scope({ free(xml
); });
1993 put(proxy
, xml
, size
);
1996 folder
.Open(executable
, fun([&](std::streambuf
&buffer
) {
1997 // XXX: this is a miserable fail
1998 std::stringbuf temp
;
2000 auto data(temp
.str());
2002 folder
.Save(executable
, fun([&](std::streambuf
&save
) {
2004 slots
[1] = local
.at(info
);
2005 slots
[3] = local
.at(signature
);
2007 HashProxy
proxy(local
[executable
], save
);
2008 Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, key
, slots
);
2012 for (const auto &hash
: local
)
2013 remote
[root
+ hash
.first
] = hash
.second
;
2022 #ifndef LDID_NOTOOLS
2023 int main(int argc
, char *argv
[]) {
2024 #ifndef LDID_NOSMIME
2025 OpenSSL_add_all_algorithms();
2033 little_
= endian
.byte
[0];
2038 #ifndef LDID_NOFLAGT
2052 uint32_t flag_CPUType(_not(uint32_t));
2053 uint32_t flag_CPUSubtype(_not(uint32_t));
2055 const char *flag_I(NULL
);
2057 #ifndef LDID_NOFLAGT
2066 std::vector
<std::string
> files
;
2069 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2070 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2071 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2072 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2076 for (int argi(1); argi
!= argc
; ++argi
)
2077 if (argv
[argi
][0] != '-')
2078 files
.push_back(argv
[argi
]);
2079 else switch (argv
[argi
][1]) {
2086 case 'e': flag_e
= true; break;
2089 const char *slot
= argv
[argi
] + 2;
2090 const char *colon
= strchr(slot
, ':');
2091 _assert(colon
!= NULL
);
2092 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2094 unsigned number(strtoul(slot
, &arge
, 0));
2095 _assert(arge
== colon
);
2096 sha1(slots
[number
], file
.data(), file
.size());
2099 case 'D': flag_D
= true; break;
2101 case 'a': flag_a
= true; break;
2106 if (argv
[argi
][2] != '\0') {
2107 const char *cpu
= argv
[argi
] + 2;
2108 const char *colon
= strchr(cpu
, ':');
2109 _assert(colon
!= NULL
);
2111 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2112 _assert(arge
== colon
);
2113 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2114 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2128 if (argv
[argi
][2] != '\0') {
2129 const char *xml
= argv
[argi
] + 2;
2130 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2135 if (argv
[argi
][2] != '\0')
2136 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2139 #ifndef LDID_NOFLAGT
2142 if (argv
[argi
][2] == '-')
2146 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2147 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2157 flag_I
= argv
[argi
] + 2;
2165 _assert(flag_S
|| key
.empty());
2166 _assert(flag_S
|| flag_I
== NULL
);
2168 if (files
.empty()) usage
: {
2172 size_t filei(0), filee(0);
2173 _foreach (file
, files
) try {
2174 std::string
path(file
);
2177 _syscall(stat(path
.c_str(), &info
));
2179 if (S_ISDIR(info
.st_mode
)) {
2180 #ifndef LDID_NOPLIST
2182 ldid::DiskFolder
folder(path
);
2183 std::map
<std::string
, std::vector
<char>> hashes
;
2184 path
+= "/" + Bundle("", folder
, key
, hashes
, entitlements
);
2188 } else if (flag_S
|| flag_r
) {
2189 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2191 std::filebuf output
;
2193 auto temp(Temporary(output
, split
));
2196 ldid::Unsign(input
.data(), input
.size(), output
);
2198 std::string
identifier(flag_I
?: split
.base
.c_str());
2199 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2206 #ifndef LDID_NOFLAGT
2213 Map
mapping(path
, modify
);
2214 FatHeader
fat_header(mapping
.data(), mapping
.size());
2216 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2217 struct linkedit_data_command
*signature(NULL
);
2218 struct encryption_info_command
*encryption(NULL
);
2221 if (mach_header
.GetCPUType() != flag_CPUType
)
2223 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2228 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2230 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2231 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2234 else if (cmd
== LC_CODE_SIGNATURE
)
2235 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2236 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2237 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2238 else if (cmd
== LC_LOAD_DYLIB
) {
2239 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2240 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2242 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2245 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2246 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2250 #ifndef LDID_NOFLAGT
2251 else if (cmd
== LC_ID_DYLIB
) {
2252 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2260 dylib_command
->dylib
.timestamp
= 0;
2261 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2264 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2271 _assert(encryption
!= NULL
);
2272 encryption
->cryptid
= mach_header
.Swap(0);
2276 _assert(signature
!= NULL
);
2278 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2280 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2281 uint8_t *blob
= top
+ data
;
2282 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2284 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2285 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2286 uint32_t begin
= Swap(super
->index
[index
].offset
);
2287 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2288 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2293 _assert(signature
!= NULL
);
2295 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2297 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2298 uint8_t *blob
= top
+ data
;
2299 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2301 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2302 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2303 uint32_t begin
= Swap(super
->index
[index
].offset
);
2304 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2306 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2307 uint32_t pages
= Swap(directory
->nCodeSlots
);
2310 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2311 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2313 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2319 } catch (const char *) {