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
;
813 uint32_t scatterOffset
;
814 uint32_t teamIDOffset
;
816 uint64_t codeLimit64
;
820 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
823 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
824 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
827 static void sha1(std::vector
<char> &hash
, const void *data
, size_t size
) {
828 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
829 sha1(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
832 struct CodesignAllocation
{
833 FatMachHeader mach_header_
;
840 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
841 mach_header_(mach_header
),
864 _syscall(close(file_
));
867 void open(const char *path
, int flags
) {
868 _assert(file_
== -1);
869 file_
= _syscall(::open(path
, flags
));
886 _syscall(munmap(data_
, size_
));
898 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
901 open(path
, oflag
, pflag
, mflag
);
904 Map(const std::string
&path
, bool edit
) :
915 return data_
== NULL
;
918 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
921 file_
.open(path
.c_str(), oflag
);
922 int file(file_
.file());
925 _syscall(fstat(file
, &stat
));
926 size_
= stat
.st_size
;
928 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
931 void open(const std::string
&path
, bool edit
) {
933 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
935 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
942 size_t size() const {
946 operator std::string() const {
947 return std::string(static_cast<char *>(data_
), size_
);
954 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
) {
955 FatHeader
source(const_cast<void *>(idata
), isize
);
959 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
961 std::vector
<CodesignAllocation
> allocations
;
962 _foreach (mach_header
, source
.GetMachHeaders()) {
963 struct linkedit_data_command
*signature(NULL
);
964 struct symtab_command
*symtab(NULL
);
966 _foreach (load_command
, mach_header
.GetLoadCommands()) {
967 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
969 else if (cmd
== LC_CODE_SIGNATURE
)
970 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
971 else if (cmd
== LC_SYMTAB
)
972 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
976 if (signature
== NULL
)
977 size
= mach_header
.GetSize();
979 size
= mach_header
.Swap(signature
->dataoff
);
980 _assert(size
<= mach_header
.GetSize());
983 if (symtab
!= NULL
) {
984 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
985 _assert(end
<= size
);
986 _assert(end
>= size
- 0x10);
990 size_t alloc(allocate(mach_header
, size
));
992 auto *fat_arch(mach_header
.GetFatArch());
995 if (fat_arch
!= NULL
)
996 align
= source
.Swap(fat_arch
->align
);
997 else switch (mach_header
.GetCPUType()) {
998 case CPU_TYPE_POWERPC
:
999 case CPU_TYPE_POWERPC64
:
1001 case CPU_TYPE_X86_64
:
1005 case CPU_TYPE_ARM64
:
1013 offset
= Align(offset
, 1 << align
);
1015 uint32_t limit(size
);
1017 limit
= Align(limit
, 0x10);
1019 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1020 offset
+= size
+ alloc
;
1021 offset
= Align(offset
, 0x10);
1026 if (source
.IsFat()) {
1027 fat_header fat_header
;
1028 fat_header
.magic
= Swap(FAT_MAGIC
);
1029 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1030 put(output
, &fat_header
, sizeof(fat_header
));
1031 position
+= sizeof(fat_header
);
1033 _foreach (allocation
, allocations
) {
1034 auto &mach_header(allocation
.mach_header_
);
1037 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1038 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1039 fat_arch
.offset
= Swap(allocation
.offset_
);
1040 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1041 fat_arch
.align
= Swap(allocation
.align_
);
1042 put(output
, &fat_arch
, sizeof(fat_arch
));
1043 position
+= sizeof(fat_arch
);
1047 _foreach (allocation
, allocations
) {
1048 auto &mach_header(allocation
.mach_header_
);
1050 pad(output
, allocation
.offset_
- position
);
1051 position
= allocation
.offset_
;
1053 std::vector
<std::string
> commands
;
1055 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1056 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1058 switch (mach_header
.Swap(load_command
->cmd
)) {
1059 case LC_CODE_SIGNATURE
:
1064 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1065 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1067 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1068 segment_command
->filesize
= size
;
1069 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1072 case LC_SEGMENT_64
: {
1073 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1074 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1076 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1077 segment_command
->filesize
= size
;
1078 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1082 commands
.push_back(copy
);
1085 if (allocation
.alloc_
!= 0) {
1086 linkedit_data_command signature
;
1087 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1088 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1089 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1090 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1091 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1094 size_t begin(position
);
1097 _foreach(command
, commands
)
1098 after
+= command
.size();
1100 std::stringbuf altern
;
1102 struct mach_header
header(*mach_header
);
1103 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1104 header
.sizeofcmds
= mach_header
.Swap(after
);
1105 put(output
, &header
, sizeof(header
));
1106 put(altern
, &header
, sizeof(header
));
1107 position
+= sizeof(header
);
1109 if (mach_header
.Bits64()) {
1110 auto pad(mach_header
.Swap(uint32_t(0)));
1111 put(output
, &pad
, sizeof(pad
));
1112 put(altern
, &pad
, sizeof(pad
));
1113 position
+= sizeof(pad
);
1116 _foreach(command
, commands
) {
1117 put(output
, command
.data(), command
.size());
1118 put(altern
, command
.data(), command
.size());
1119 position
+= command
.size();
1122 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1123 if (before
> after
) {
1124 pad(output
, before
- after
);
1125 pad(altern
, before
- after
);
1126 position
+= before
- after
;
1129 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1131 std::string
overlap(altern
.str());
1132 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1134 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1135 position
= begin
+ allocation
.size_
;
1137 pad(output
, allocation
.limit_
- allocation
.size_
);
1138 position
+= allocation
.limit_
- allocation
.size_
;
1140 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
));
1141 if (allocation
.alloc_
> saved
)
1142 pad(output
, allocation
.alloc_
- saved
);
1143 position
+= allocation
.alloc_
;
1149 typedef std::map
<uint32_t, std::string
> Blobs
;
1151 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1152 auto value(buffer
.str());
1153 std::swap(blobs
[slot
], value
);
1156 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1157 auto value(buffer
.str());
1159 blob
.magic
= Swap(magic
);
1160 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1161 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1162 std::swap(blobs
[slot
], value
);
1165 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1167 _foreach (blob
, blobs
)
1168 total
+= blob
.second
.size();
1170 struct SuperBlob super
;
1171 super
.blob
.magic
= Swap(magic
);
1172 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1173 super
.count
= Swap(uint32_t(blobs
.size()));
1174 put(output
, &super
, sizeof(super
));
1176 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1178 _foreach (blob
, blobs
) {
1180 index
.type
= Swap(blob
.first
);
1181 index
.offset
= Swap(uint32_t(offset
));
1182 put(output
, &index
, sizeof(index
));
1183 offset
+= blob
.second
.size();
1186 _foreach (blob
, blobs
)
1187 put(output
, blob
.second
.data(), blob
.second
.size());
1192 #ifndef LDID_NOSMIME
1201 _assert(bio_
!= NULL
);
1205 bio_(BIO_new(BIO_s_mem()))
1209 Buffer(const char *data
, size_t size
) :
1210 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1214 Buffer(const std::string
&data
) :
1215 Buffer(data
.data(), data
.size())
1219 Buffer(PKCS7
*pkcs
) :
1222 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1229 operator BIO
*() const {
1233 explicit operator std::string() const {
1235 auto size(BIO_get_mem_data(bio_
, &data
));
1236 return std::string(data
, size
);
1245 STACK_OF(X509
) *ca_
;
1249 value_(d2i_PKCS12_bio(bio
, NULL
)),
1252 _assert(value_
!= NULL
);
1253 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1254 _assert(key_
!= NULL
);
1255 _assert(cert_
!= NULL
);
1258 Stuff(const std::string
&data
) :
1264 sk_X509_pop_free(ca_
, X509_free
);
1266 EVP_PKEY_free(key_
);
1267 PKCS12_free(value_
);
1270 operator PKCS12
*() const {
1274 operator EVP_PKEY
*() const {
1278 operator X509
*() const {
1282 operator STACK_OF(X509
) *() const {
1292 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1293 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1295 _assert(value_
!= NULL
);
1302 operator PKCS7
*() const {
1309 public std::streambuf
1312 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1316 virtual int_type
overflow(int_type next
) {
1322 public std::streambuf
1325 std::vector
<char> &hash_
;
1326 LDID_SHA1_CTX context_
;
1329 HashBuffer(std::vector
<char> &hash
) :
1332 LDID_SHA1_Init(&context_
);
1336 hash_
.resize(LDID_SHA1_DIGEST_LENGTH
);
1337 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1340 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1341 LDID_SHA1_Update(&context_
, data
, size
);
1345 virtual int_type
overflow(int_type next
) {
1346 if (next
== traits_type::eof())
1358 std::streambuf
&buffer_
;
1361 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1367 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1368 _assert(HashBuffer::xsputn(data
, size
) == size
);
1369 return buffer_
.sputn(data
, size
);
1373 #ifndef LDID_NOTOOLS
1374 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1375 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1383 Split(const std::string
&path
) {
1384 size_t slash(path
.rfind('/'));
1385 if (slash
== std::string::npos
)
1388 dir
= path
.substr(0, slash
+ 1);
1389 base
= path
.substr(slash
+ 1);
1394 static void mkdir_p(const std::string
&path
) {
1398 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1401 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1404 auto slash(path
.rfind('/', path
.size() - 1));
1405 if (slash
== std::string::npos
)
1407 mkdir_p(path
.substr(0, slash
));
1410 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1411 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1413 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1417 static void Commit(const std::string
&path
, const std::string
&temp
) {
1419 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1421 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1423 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1426 _syscall(rename(temp
.c_str(), path
.c_str()));
1432 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
) {
1435 #ifndef LDID_NOSMIME
1437 std::stringbuf data
;
1439 auto name(X509_get_subject_name(stuff
));
1440 _assert(name
!= NULL
);
1441 auto index(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, -1));
1442 _assert(index
>= 0);
1443 auto next(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, index
));
1444 _assert(next
== -1);
1445 auto entry(X509_NAME_get_entry(name
, index
));
1446 _assert(entry
!= NULL
);
1447 auto asn(X509_NAME_ENTRY_get_data(entry
));
1448 _assert(asn
!= NULL
);
1449 team
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1453 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1454 size_t alloc(sizeof(struct SuperBlob
));
1456 uint32_t special(0);
1458 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1459 alloc
+= sizeof(struct BlobIndex
);
1462 if (!entitlements
.empty()) {
1463 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1464 alloc
+= sizeof(struct BlobIndex
);
1465 alloc
+= sizeof(struct Blob
);
1466 alloc
+= entitlements
.size();
1469 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1470 alloc
+= sizeof(struct BlobIndex
);
1471 alloc
+= sizeof(struct Blob
);
1472 alloc
+= sizeof(struct CodeDirectory
);
1473 alloc
+= identifier
.size() + 1;
1476 alloc
+= team
.size() + 1;
1479 alloc
+= sizeof(struct BlobIndex
);
1480 alloc
+= sizeof(struct Blob
);
1481 // XXX: this is just a "sufficiently large number"
1485 _foreach (slot
, slots
)
1486 special
= std::max(special
, slot
.first
);
1488 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1489 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1490 special
= std::max(special
, CSSLOT_INFOSLOT
);
1493 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1494 alloc
= Align(alloc
+ (special
+ normal
) * LDID_SHA1_DIGEST_LENGTH
, 16);
1496 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1500 std::stringbuf data
;
1503 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1505 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1508 if (!entitlements
.empty()) {
1509 std::stringbuf data
;
1510 put(data
, entitlements
.data(), entitlements
.size());
1511 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1515 std::stringbuf data
;
1519 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1520 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1521 sha1(posts
[CSSLOT_INFOSLOT
], data
, size
);
1524 uint32_t special(0);
1525 _foreach (blob
, blobs
)
1526 special
= std::max(special
, blob
.first
);
1527 _foreach (slot
, posts
)
1528 special
= std::max(special
, slot
.first
);
1529 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1531 CodeDirectory directory
;
1532 directory
.version
= Swap(uint32_t(0x00020200));
1533 directory
.flags
= Swap(uint32_t(0));
1534 directory
.nSpecialSlots
= Swap(special
);
1535 directory
.codeLimit
= Swap(uint32_t(limit
));
1536 directory
.nCodeSlots
= Swap(normal
);
1537 directory
.hashSize
= LDID_SHA1_DIGEST_LENGTH
;
1538 directory
.hashType
= CS_HASHTYPE_SHA1
;
1539 directory
.spare1
= 0x00;
1540 directory
.pageSize
= PageShift_
;
1541 directory
.spare2
= Swap(uint32_t(0));
1542 directory
.scatterOffset
= Swap(uint32_t(0));
1543 directory
.spare3
= Swap(uint32_t(0));
1544 directory
.codeLimit64
= Swap(uint64_t(0));
1546 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1548 directory
.identOffset
= Swap(uint32_t(offset
));
1549 offset
+= identifier
.size() + 1;
1552 directory
.teamIDOffset
= Swap(uint32_t(0));
1554 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1555 offset
+= team
.size() + 1;
1558 offset
+= LDID_SHA1_DIGEST_LENGTH
* special
;
1559 directory
.hashOffset
= Swap(uint32_t(offset
));
1560 offset
+= LDID_SHA1_DIGEST_LENGTH
* normal
;
1562 put(data
, &directory
, sizeof(directory
));
1564 put(data
, identifier
.c_str(), identifier
.size() + 1);
1565 put(data
, team
.c_str(), team
.size() + 1);
1567 uint8_t storage
[special
+ normal
][LDID_SHA1_DIGEST_LENGTH
];
1568 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = storage
+ special
;
1570 memset(storage
, 0, sizeof(*storage
) * special
);
1572 _foreach (blob
, blobs
) {
1573 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1574 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1577 _foreach (slot
, posts
) {
1578 _assert(sizeof(*hashes
) == slot
.second
.size());
1579 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1583 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1584 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1586 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1588 put(data
, storage
, sizeof(storage
));
1590 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1593 #ifndef LDID_NOSMIME
1595 std::stringbuf data
;
1596 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1601 Signature
signature(stuff
, sign
);
1602 Buffer
result(signature
);
1603 std::string
value(result
);
1604 put(data
, value
.data(), value
.size());
1606 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1610 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1614 #ifndef LDID_NOTOOLS
1615 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1616 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1618 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1623 std::string
DiskFolder::Path(const std::string
&path
) {
1624 return path_
+ "/" + path
;
1627 DiskFolder::DiskFolder(const std::string
&path
) :
1632 DiskFolder::~DiskFolder() {
1633 if (!std::uncaught_exception())
1634 for (const auto &commit
: commit_
)
1635 Commit(commit
.first
, commit
.second
);
1638 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
) {
1639 std::string
path(Path(root
) + base
);
1641 DIR *dir(opendir(path
.c_str()));
1642 _assert(dir
!= NULL
);
1643 _scope({ _syscall(closedir(dir
)); });
1645 while (auto child
= readdir(dir
)) {
1646 std::string
name(child
->d_name
);
1647 if (name
== "." || name
== "..")
1649 if (Starts(name
, ".ldid."))
1656 _syscall(stat(path
.c_str(), &info
));
1658 else if (S_ISDIR(info
.st_mode
))
1660 else if (S_ISREG(info
.st_mode
))
1663 _assert_(false, "st_mode=%x", info
.st_mode
);
1665 switch (child
->d_type
) {
1673 _assert_(false, "d_type=%u", child
->d_type
);
1678 Find(root
, base
+ name
+ "/", code
);
1680 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1681 std::string
access(root
+ base
+ name
);
1682 _assert_(Open(access
, fun([&](std::streambuf
&data
, const void *flag
) {
1685 })), "open(): %s", access
.c_str());
1690 void DiskFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1692 auto from(Path(path
));
1693 commit_
[from
] = Temporary(save
, from
);
1697 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1699 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1702 _assert(result
== &data
);
1707 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1708 Find(path
, "", code
);
1712 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1718 void SubFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1719 return parent_
.Save(path_
+ path
, flag
, code
);
1722 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1723 return parent_
.Open(path_
+ path
, code
);
1726 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1727 return parent_
.Find(path_
+ path
, code
);
1730 std::string
UnionFolder::Map(const std::string
&path
) {
1731 auto remap(remaps_
.find(path
));
1732 if (remap
== remaps_
.end())
1734 return remap
->second
;
1737 void UnionFolder::Map(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
, const std::string
&file
, const Functor
<void (const Functor
<void (std::streambuf
&, const void *)> &)> &save
) {
1738 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
1739 code(file
.substr(path
.size()), fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1740 save(fun([&](std::streambuf
&data
, const void *flag
) {
1741 parent_
.Save(file
, flag
, fun([&](std::streambuf
&save
) {
1748 UnionFolder::UnionFolder(Folder
&parent
) :
1753 void UnionFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1754 return parent_
.Save(Map(path
), flag
, code
);
1757 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1758 auto file(resets_
.find(path
));
1759 if (file
== resets_
.end())
1760 return parent_
.Open(Map(path
), code
);
1761 auto &entry(file
->second
);
1763 auto &data(entry
.first
);
1764 data
.pubseekpos(0, std::ios::in
);
1765 code(data
, entry
.second
);
1769 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1770 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1771 if (deletes_
.find(path
+ name
) == deletes_
.end())
1775 for (auto &reset
: resets_
)
1776 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, const void *)> &code
) {
1777 auto &entry(reset
.second
);
1778 entry
.first
.pubseekpos(0, std::ios::in
);
1779 code(entry
.first
, entry
.second
);
1782 for (auto &remap
: remaps_
)
1783 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, const void *)> &code
) {
1784 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, const void *flag
) {
1790 #ifndef LDID_NOTOOLS
1791 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1795 size_t writ(source
.sgetn(data
, sizeof(data
)));
1798 _assert(target
.sputn(data
, writ
) == writ
);
1804 #ifndef LDID_NOPLIST
1805 static plist_t
plist(const std::string
&data
) {
1806 plist_t
plist(NULL
);
1807 if (Starts(data
, "bplist00"))
1808 plist_from_bin(data
.data(), data
.size(), &plist
);
1810 plist_from_xml(data
.data(), data
.size(), &plist
);
1811 _assert(plist
!= NULL
);
1815 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1816 std::stringbuf data
;
1818 auto node(plist(data
.str()));
1819 _scope({ plist_free(node
); });
1820 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1824 static std::string
plist_s(plist_t node
) {
1825 _assert(node
!= NULL
);
1826 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1828 plist_get_string_val(node
, &data
);
1829 _scope({ free(data
); });
1847 Expression(const std::string
&code
) {
1848 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1855 bool operator ()(const std::string
&data
) const {
1856 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1857 if (value
== REG_NOMATCH
)
1859 _assert_(value
== 0, "regexec()");
1869 mutable std::auto_ptr
<Expression
> regex_
;
1871 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1878 Rule(const Rule
&rhs
) :
1879 weight_(rhs
.weight_
),
1885 void Compile() const {
1886 regex_
.reset(new Expression(code_
));
1889 bool operator ()(const std::string
&data
) const {
1890 _assert(regex_
.get() != NULL
);
1891 return (*regex_
)(data
);
1894 bool operator <(const Rule
&rhs
) const {
1895 if (weight_
> rhs
.weight_
)
1897 if (weight_
< rhs
.weight_
)
1899 return mode_
> rhs
.mode_
;
1904 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1905 return lhs
->code_
< rhs
->code_
;
1909 #ifndef LDID_NOPLIST
1910 void Sign(std::streambuf
&buffer
, std::vector
<char> &hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&key
, const Slots
&slots
) {
1911 // XXX: this is a miserable fail
1912 std::stringbuf temp
;
1914 auto data(temp
.str());
1916 HashProxy
proxy(hash
, save
);
1917 Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, key
, slots
);
1920 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
) {
1921 std::string executable
;
1922 std::string identifier
;
1924 static const std::string
info("Info.plist");
1926 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
, const void *flag
) {
1927 plist_d(buffer
, fun([&](plist_t node
) {
1928 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1929 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1931 })), "open(): Info.plist");
1933 static const std::string
directory("_CodeSignature/");
1934 static const std::string
signature(directory
+ "CodeResources");
1936 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1938 auto &rules1(versions
[""]);
1939 auto &rules2(versions
["2"]);
1941 folder
.Open(signature
, fun([&](std::streambuf
&buffer
, const void *) {
1942 plist_d(buffer
, fun([&](plist_t node
) {
1943 // XXX: maybe attempt to preserve existing rules
1948 rules1
.insert(Rule
{1, NoMode
, "^"});
1949 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1950 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1951 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1952 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1953 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1957 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1958 rules2
.insert(Rule
{20, NoMode
, "^"});
1959 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1960 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1961 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1962 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1963 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1964 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1965 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1966 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1967 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1968 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1969 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1970 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1973 std::map
<std::string
, std::vector
<char>> local
;
1975 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1976 static Expression
dylib("^[^/]*\\.dylib$");
1978 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1981 auto bundle(root
+ Split(name
).dir
);
1982 SubFolder
subfolder(folder
, bundle
);
1983 Bundle(bundle
, subfolder
, key
, local
, "");
1986 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1987 // BundleDiskRep::adjustResources -> builder.addExclusion
1988 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
1991 auto &hash(local
[name
]);
1995 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1998 Sign(data
, hash
, save
, identifier
, "", key
, slots
);
2000 HashProxy
proxy(hash
, save
);
2005 _assert(hash
.size() == LDID_SHA1_DIGEST_LENGTH
);
2008 auto plist(plist_new_dict());
2009 _scope({ plist_free(plist
); });
2011 for (const auto &version
: versions
) {
2012 auto files(plist_new_dict());
2013 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2015 for (const auto &rule
: version
.second
)
2018 for (const auto &hash
: local
)
2019 for (const auto &rule
: version
.second
)
2020 if (rule(hash
.first
)) {
2021 if (rule
.mode_
== NoMode
)
2022 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
2023 else if (rule
.mode_
== OptionalMode
) {
2024 auto entry(plist_new_dict());
2025 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
2026 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2027 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2034 for (const auto &version
: versions
) {
2035 auto rules(plist_new_dict());
2036 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2038 std::multiset
<const Rule
*, RuleCode
> ordered
;
2039 for (const auto &rule
: version
.second
)
2040 ordered
.insert(&rule
);
2042 for (const auto &rule
: ordered
)
2043 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2044 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2046 auto entry(plist_new_dict());
2047 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2049 switch (rule
->mode_
) {
2053 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2056 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2059 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2062 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2066 if (rule
->weight_
>= 10000)
2067 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2068 else if (rule
->weight_
!= 1)
2069 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2073 folder
.Save(signature
, NULL
, fun([&](std::streambuf
&save
) {
2074 HashProxy
proxy(local
[signature
], save
);
2077 plist_to_xml(plist
, &xml
, &size
);
2078 _scope({ free(xml
); });
2079 put(proxy
, xml
, size
);
2082 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, const void *flag
) {
2083 folder
.Save(executable
, flag
, fun([&](std::streambuf
&save
) {
2085 slots
[1] = local
.at(info
);
2086 slots
[3] = local
.at(signature
);
2087 Sign(buffer
, local
[executable
], save
, identifier
, entitlements
, key
, slots
);
2091 for (const auto &hash
: local
)
2092 remote
[root
+ hash
.first
] = hash
.second
;
2101 #ifndef LDID_NOTOOLS
2102 int main(int argc
, char *argv
[]) {
2103 #ifndef LDID_NOSMIME
2104 OpenSSL_add_all_algorithms();
2112 little_
= endian
.byte
[0];
2117 #ifndef LDID_NOFLAGT
2131 uint32_t flag_CPUType(_not(uint32_t));
2132 uint32_t flag_CPUSubtype(_not(uint32_t));
2134 const char *flag_I(NULL
);
2136 #ifndef LDID_NOFLAGT
2145 std::vector
<std::string
> files
;
2148 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2149 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2150 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2151 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2155 for (int argi(1); argi
!= argc
; ++argi
)
2156 if (argv
[argi
][0] != '-')
2157 files
.push_back(argv
[argi
]);
2158 else switch (argv
[argi
][1]) {
2165 case 'e': flag_e
= true; break;
2168 const char *slot
= argv
[argi
] + 2;
2169 const char *colon
= strchr(slot
, ':');
2170 _assert(colon
!= NULL
);
2171 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2173 unsigned number(strtoul(slot
, &arge
, 0));
2174 _assert(arge
== colon
);
2175 sha1(slots
[number
], file
.data(), file
.size());
2178 case 'D': flag_D
= true; break;
2180 case 'a': flag_a
= true; break;
2185 if (argv
[argi
][2] != '\0') {
2186 const char *cpu
= argv
[argi
] + 2;
2187 const char *colon
= strchr(cpu
, ':');
2188 _assert(colon
!= NULL
);
2190 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2191 _assert(arge
== colon
);
2192 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2193 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2207 if (argv
[argi
][2] != '\0') {
2208 const char *xml
= argv
[argi
] + 2;
2209 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2214 if (argv
[argi
][2] != '\0')
2215 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2218 #ifndef LDID_NOFLAGT
2221 if (argv
[argi
][2] == '-')
2225 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2226 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2236 flag_I
= argv
[argi
] + 2;
2244 _assert(flag_S
|| key
.empty());
2245 _assert(flag_S
|| flag_I
== NULL
);
2247 if (files
.empty()) usage
: {
2251 size_t filei(0), filee(0);
2252 _foreach (file
, files
) try {
2253 std::string
path(file
);
2256 _syscall(stat(path
.c_str(), &info
));
2258 if (S_ISDIR(info
.st_mode
)) {
2259 #ifndef LDID_NOPLIST
2261 ldid::DiskFolder
folder(path
);
2262 std::map
<std::string
, std::vector
<char>> hashes
;
2263 path
+= "/" + Bundle("", folder
, key
, hashes
, entitlements
);
2267 } else if (flag_S
|| flag_r
) {
2268 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2270 std::filebuf output
;
2272 auto temp(Temporary(output
, split
));
2275 ldid::Unsign(input
.data(), input
.size(), output
);
2277 std::string
identifier(flag_I
?: split
.base
.c_str());
2278 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2285 #ifndef LDID_NOFLAGT
2292 Map
mapping(path
, modify
);
2293 FatHeader
fat_header(mapping
.data(), mapping
.size());
2295 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2296 struct linkedit_data_command
*signature(NULL
);
2297 struct encryption_info_command
*encryption(NULL
);
2300 if (mach_header
.GetCPUType() != flag_CPUType
)
2302 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2307 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2309 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2310 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2313 else if (cmd
== LC_CODE_SIGNATURE
)
2314 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2315 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2316 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2317 else if (cmd
== LC_LOAD_DYLIB
) {
2318 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2319 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2321 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2324 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2325 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2329 #ifndef LDID_NOFLAGT
2330 else if (cmd
== LC_ID_DYLIB
) {
2331 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2339 dylib_command
->dylib
.timestamp
= 0;
2340 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2343 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2350 _assert(encryption
!= NULL
);
2351 encryption
->cryptid
= mach_header
.Swap(0);
2355 _assert(signature
!= NULL
);
2357 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2359 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2360 uint8_t *blob
= top
+ data
;
2361 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2363 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2364 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2365 uint32_t begin
= Swap(super
->index
[index
].offset
);
2366 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2367 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2372 _assert(signature
!= NULL
);
2374 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2376 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2377 uint8_t *blob
= top
+ data
;
2378 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2380 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2381 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2382 uint32_t begin
= Swap(super
->index
[index
].offset
);
2383 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2385 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2386 uint32_t pages
= Swap(directory
->nCodeSlots
);
2389 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2390 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2392 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2398 } catch (const char *) {