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 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
463 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
468 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
469 _assert(read(stream
, data
, size
) == size
);
472 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
473 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
476 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
479 if (auto writ
= read(stream
, data
, size
))
485 static inline void pad(std::streambuf
&stream
, size_t size
) {
487 memset(padding
, 0, size
);
488 put(stream
, padding
, size
);
491 template <typename Type_
>
492 Type_
Align(Type_ value
, size_t align
) {
499 static const uint8_t PageShift_(0x0c);
500 static const uint32_t PageSize_(1 << PageShift_
);
502 static inline uint16_t Swap_(uint16_t value
) {
504 ((value
>> 8) & 0x00ff) |
505 ((value
<< 8) & 0xff00);
508 static inline uint32_t Swap_(uint32_t value
) {
509 value
= ((value
>> 8) & 0x00ff00ff) |
510 ((value
<< 8) & 0xff00ff00);
511 value
= ((value
>> 16) & 0x0000ffff) |
512 ((value
<< 16) & 0xffff0000);
516 static inline uint64_t Swap_(uint64_t value
) {
517 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
518 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
519 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
523 static inline int16_t Swap_(int16_t value
) {
524 return Swap_(static_cast<uint16_t>(value
));
527 static inline int32_t Swap_(int32_t value
) {
528 return Swap_(static_cast<uint32_t>(value
));
531 static inline int64_t Swap_(int64_t value
) {
532 return Swap_(static_cast<uint64_t>(value
));
535 static bool little_(true);
537 static inline uint16_t Swap(uint16_t value
) {
538 return little_
? Swap_(value
) : value
;
541 static inline uint32_t Swap(uint32_t value
) {
542 return little_
? Swap_(value
) : value
;
545 static inline uint64_t Swap(uint64_t value
) {
546 return little_
? Swap_(value
) : value
;
549 static inline int16_t Swap(int16_t value
) {
550 return Swap(static_cast<uint16_t>(value
));
553 static inline int32_t Swap(int32_t value
) {
554 return Swap(static_cast<uint32_t>(value
));
557 static inline int64_t Swap(int64_t value
) {
558 return Swap(static_cast<uint64_t>(value
));
571 Swapped(bool swapped
) :
576 template <typename Type_
>
577 Type_
Swap(Type_ value
) const {
578 return swapped_
? Swap_(value
) : value
;
590 Data(void *base
, size_t size
) :
596 void *GetBase() const {
600 size_t GetSize() const {
611 struct mach_header
*mach_header_
;
612 struct load_command
*load_command_
;
615 MachHeader(void *base
, size_t size
) :
618 mach_header_
= (mach_header
*) base
;
620 switch (Swap(mach_header_
->magic
)) {
622 swapped_
= !swapped_
;
628 swapped_
= !swapped_
;
637 void *post
= mach_header_
+ 1;
639 post
= (uint32_t *) post
+ 1;
640 load_command_
= (struct load_command
*) post
;
643 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
644 Swap(mach_header_
->filetype
) == MH_DYLIB
||
645 Swap(mach_header_
->filetype
) == MH_BUNDLE
649 bool Bits64() const {
653 struct mach_header
*operator ->() const {
657 operator struct mach_header
*() const {
661 uint32_t GetCPUType() const {
662 return Swap(mach_header_
->cputype
);
665 uint32_t GetCPUSubtype() const {
666 return Swap(mach_header_
->cpusubtype
) & 0xff;
669 struct load_command
*GetLoadCommand() const {
670 return load_command_
;
673 std::vector
<struct load_command
*> GetLoadCommands() const {
674 std::vector
<struct load_command
*> load_commands
;
676 struct load_command
*load_command
= load_command_
;
677 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
678 load_commands
.push_back(load_command
);
679 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
682 return load_commands
;
685 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
686 _foreach (load_command
, GetLoadCommands())
687 switch (Swap(load_command
->cmd
)) {
689 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
690 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
691 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
692 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
693 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
696 case LC_SEGMENT_64
: {
697 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
698 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
699 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
700 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
701 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
706 template <typename Target_
>
707 Target_
*GetOffset(uint32_t offset
) const {
708 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
712 class FatMachHeader
:
719 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
720 MachHeader(base
, size
),
725 fat_arch
*GetFatArch() const {
734 fat_header
*fat_header_
;
735 std::vector
<FatMachHeader
> mach_headers_
;
738 FatHeader(void *base
, size_t size
) :
741 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
743 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
744 swapped_
= !swapped_
;
746 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
748 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
750 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
751 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
753 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
754 uint32_t arch_offset
= Swap(fat_arch
->offset
);
755 uint32_t arch_size
= Swap(fat_arch
->size
);
756 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
762 std::vector
<FatMachHeader
> &GetMachHeaders() {
763 return mach_headers_
;
767 return fat_header_
!= NULL
;
770 struct fat_header
*operator ->() const {
774 operator struct fat_header
*() const {
779 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
780 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
781 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
782 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
783 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
784 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
785 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
786 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
788 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
789 #define CSSLOT_INFOSLOT uint32_t(0x00001)
790 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
791 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
792 #define CSSLOT_APPLICATION uint32_t(0x00004)
793 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
795 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
797 #define CS_HASHTYPE_SHA1 1
812 struct BlobIndex index
[];
815 struct CodeDirectory
{
819 uint32_t identOffset
;
820 uint32_t nSpecialSlots
;
828 uint32_t scatterOffset
;
829 uint32_t teamIDOffset
;
831 uint64_t codeLimit64
;
835 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
838 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
839 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
842 static void sha1(std::vector
<char> &hash
, const void *data
, size_t size
) {
843 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
844 sha1(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
847 struct CodesignAllocation
{
848 FatMachHeader mach_header_
;
855 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
856 mach_header_(mach_header
),
879 _syscall(close(file_
));
882 void open(const char *path
, int flags
) {
883 _assert(file_
== -1);
884 file_
= _syscall(::open(path
, flags
));
901 _syscall(munmap(data_
, size_
));
913 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
916 open(path
, oflag
, pflag
, mflag
);
919 Map(const std::string
&path
, bool edit
) :
930 return data_
== NULL
;
933 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
936 file_
.open(path
.c_str(), oflag
);
937 int file(file_
.file());
940 _syscall(fstat(file
, &stat
));
941 size_
= stat
.st_size
;
943 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
946 void open(const std::string
&path
, bool edit
) {
948 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
950 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
957 size_t size() const {
961 operator std::string() const {
962 return std::string(static_cast<char *>(data_
), size_
);
969 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
) {
970 FatHeader
source(const_cast<void *>(idata
), isize
);
974 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
976 std::vector
<CodesignAllocation
> allocations
;
977 _foreach (mach_header
, source
.GetMachHeaders()) {
978 struct linkedit_data_command
*signature(NULL
);
979 struct symtab_command
*symtab(NULL
);
981 _foreach (load_command
, mach_header
.GetLoadCommands()) {
982 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
984 else if (cmd
== LC_CODE_SIGNATURE
)
985 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
986 else if (cmd
== LC_SYMTAB
)
987 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
991 if (signature
== NULL
)
992 size
= mach_header
.GetSize();
994 size
= mach_header
.Swap(signature
->dataoff
);
995 _assert(size
<= mach_header
.GetSize());
998 if (symtab
!= NULL
) {
999 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1000 _assert(end
<= size
);
1001 _assert(end
>= size
- 0x10);
1005 size_t alloc(allocate(mach_header
, size
));
1007 auto *fat_arch(mach_header
.GetFatArch());
1010 if (fat_arch
!= NULL
)
1011 align
= source
.Swap(fat_arch
->align
);
1012 else switch (mach_header
.GetCPUType()) {
1013 case CPU_TYPE_POWERPC
:
1014 case CPU_TYPE_POWERPC64
:
1016 case CPU_TYPE_X86_64
:
1020 case CPU_TYPE_ARM64
:
1028 offset
= Align(offset
, 1 << align
);
1030 uint32_t limit(size
);
1032 limit
= Align(limit
, 0x10);
1034 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1035 offset
+= size
+ alloc
;
1036 offset
= Align(offset
, 0x10);
1041 if (source
.IsFat()) {
1042 fat_header fat_header
;
1043 fat_header
.magic
= Swap(FAT_MAGIC
);
1044 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1045 put(output
, &fat_header
, sizeof(fat_header
));
1046 position
+= sizeof(fat_header
);
1048 _foreach (allocation
, allocations
) {
1049 auto &mach_header(allocation
.mach_header_
);
1052 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1053 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1054 fat_arch
.offset
= Swap(allocation
.offset_
);
1055 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1056 fat_arch
.align
= Swap(allocation
.align_
);
1057 put(output
, &fat_arch
, sizeof(fat_arch
));
1058 position
+= sizeof(fat_arch
);
1062 _foreach (allocation
, allocations
) {
1063 auto &mach_header(allocation
.mach_header_
);
1065 pad(output
, allocation
.offset_
- position
);
1066 position
= allocation
.offset_
;
1068 std::vector
<std::string
> commands
;
1070 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1071 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1073 switch (mach_header
.Swap(load_command
->cmd
)) {
1074 case LC_CODE_SIGNATURE
:
1079 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1080 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1082 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1083 segment_command
->filesize
= size
;
1084 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1087 case LC_SEGMENT_64
: {
1088 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1089 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1091 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1092 segment_command
->filesize
= size
;
1093 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1097 commands
.push_back(copy
);
1100 if (allocation
.alloc_
!= 0) {
1101 linkedit_data_command signature
;
1102 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1103 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1104 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1105 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1106 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1109 size_t begin(position
);
1112 _foreach(command
, commands
)
1113 after
+= command
.size();
1115 std::stringbuf altern
;
1117 struct mach_header
header(*mach_header
);
1118 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1119 header
.sizeofcmds
= mach_header
.Swap(after
);
1120 put(output
, &header
, sizeof(header
));
1121 put(altern
, &header
, sizeof(header
));
1122 position
+= sizeof(header
);
1124 if (mach_header
.Bits64()) {
1125 auto pad(mach_header
.Swap(uint32_t(0)));
1126 put(output
, &pad
, sizeof(pad
));
1127 put(altern
, &pad
, sizeof(pad
));
1128 position
+= sizeof(pad
);
1131 _foreach(command
, commands
) {
1132 put(output
, command
.data(), command
.size());
1133 put(altern
, command
.data(), command
.size());
1134 position
+= command
.size();
1137 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1138 if (before
> after
) {
1139 pad(output
, before
- after
);
1140 pad(altern
, before
- after
);
1141 position
+= before
- after
;
1144 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1146 std::string
overlap(altern
.str());
1147 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1149 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1150 position
= begin
+ allocation
.size_
;
1152 pad(output
, allocation
.limit_
- allocation
.size_
);
1153 position
+= allocation
.limit_
- allocation
.size_
;
1155 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
));
1156 if (allocation
.alloc_
> saved
)
1157 pad(output
, allocation
.alloc_
- saved
);
1158 position
+= allocation
.alloc_
;
1164 typedef std::map
<uint32_t, std::string
> Blobs
;
1166 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1167 auto value(buffer
.str());
1168 std::swap(blobs
[slot
], value
);
1171 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1172 auto value(buffer
.str());
1174 blob
.magic
= Swap(magic
);
1175 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1176 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1177 std::swap(blobs
[slot
], value
);
1180 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1182 _foreach (blob
, blobs
)
1183 total
+= blob
.second
.size();
1185 struct SuperBlob super
;
1186 super
.blob
.magic
= Swap(magic
);
1187 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1188 super
.count
= Swap(uint32_t(blobs
.size()));
1189 put(output
, &super
, sizeof(super
));
1191 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1193 _foreach (blob
, blobs
) {
1195 index
.type
= Swap(blob
.first
);
1196 index
.offset
= Swap(uint32_t(offset
));
1197 put(output
, &index
, sizeof(index
));
1198 offset
+= blob
.second
.size();
1201 _foreach (blob
, blobs
)
1202 put(output
, blob
.second
.data(), blob
.second
.size());
1207 #ifndef LDID_NOSMIME
1216 _assert(bio_
!= NULL
);
1220 bio_(BIO_new(BIO_s_mem()))
1224 Buffer(const char *data
, size_t size
) :
1225 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1229 Buffer(const std::string
&data
) :
1230 Buffer(data
.data(), data
.size())
1234 Buffer(PKCS7
*pkcs
) :
1237 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1244 operator BIO
*() const {
1248 explicit operator std::string() const {
1250 auto size(BIO_get_mem_data(bio_
, &data
));
1251 return std::string(data
, size
);
1260 STACK_OF(X509
) *ca_
;
1264 value_(d2i_PKCS12_bio(bio
, NULL
)),
1267 _assert(value_
!= NULL
);
1268 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1269 _assert(key_
!= NULL
);
1270 _assert(cert_
!= NULL
);
1273 Stuff(const std::string
&data
) :
1279 sk_X509_pop_free(ca_
, X509_free
);
1281 EVP_PKEY_free(key_
);
1282 PKCS12_free(value_
);
1285 operator PKCS12
*() const {
1289 operator EVP_PKEY
*() const {
1293 operator X509
*() const {
1297 operator STACK_OF(X509
) *() const {
1307 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1308 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1310 _assert(value_
!= NULL
);
1317 operator PKCS7
*() const {
1324 public std::streambuf
1327 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1331 virtual int_type
overflow(int_type next
) {
1337 public std::streambuf
1340 std::vector
<char> &hash_
;
1341 LDID_SHA1_CTX context_
;
1344 HashBuffer(std::vector
<char> &hash
) :
1347 LDID_SHA1_Init(&context_
);
1351 hash_
.resize(LDID_SHA1_DIGEST_LENGTH
);
1352 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1355 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1356 LDID_SHA1_Update(&context_
, data
, size
);
1360 virtual int_type
overflow(int_type next
) {
1361 if (next
== traits_type::eof())
1373 std::streambuf
&buffer_
;
1376 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1382 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1383 _assert(HashBuffer::xsputn(data
, size
) == size
);
1384 return buffer_
.sputn(data
, size
);
1388 #ifndef LDID_NOTOOLS
1389 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1390 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1398 Split(const std::string
&path
) {
1399 size_t slash(path
.rfind('/'));
1400 if (slash
== std::string::npos
)
1403 dir
= path
.substr(0, slash
+ 1);
1404 base
= path
.substr(slash
+ 1);
1409 static void mkdir_p(const std::string
&path
) {
1413 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1416 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1419 auto slash(path
.rfind('/', path
.size() - 1));
1420 if (slash
== std::string::npos
)
1422 mkdir_p(path
.substr(0, slash
));
1425 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1426 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1428 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1432 static void Commit(const std::string
&path
, const std::string
&temp
) {
1434 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1436 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1438 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1441 _syscall(rename(temp
.c_str(), path
.c_str()));
1447 void Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirement
, const std::string
&key
, const Slots
&slots
) {
1450 #ifndef LDID_NOSMIME
1453 auto name(X509_get_subject_name(stuff
));
1454 _assert(name
!= NULL
);
1455 auto index(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, -1));
1456 _assert(index
>= 0);
1457 auto next(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, index
));
1458 _assert(next
== -1);
1459 auto entry(X509_NAME_get_entry(name
, index
));
1460 _assert(entry
!= NULL
);
1461 auto asn(X509_NAME_ENTRY_get_data(entry
));
1462 _assert(asn
!= NULL
);
1463 team
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1467 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1468 size_t alloc(sizeof(struct SuperBlob
));
1470 uint32_t special(0);
1472 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1473 alloc
+= sizeof(struct BlobIndex
);
1474 if (!requirement
.empty())
1477 alloc
+= requirement
.size();
1479 if (!entitlements
.empty()) {
1480 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1481 alloc
+= sizeof(struct BlobIndex
);
1482 alloc
+= sizeof(struct Blob
);
1483 alloc
+= entitlements
.size();
1486 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1487 alloc
+= sizeof(struct BlobIndex
);
1488 alloc
+= sizeof(struct Blob
);
1489 alloc
+= sizeof(struct CodeDirectory
);
1490 alloc
+= identifier
.size() + 1;
1493 alloc
+= team
.size() + 1;
1496 alloc
+= sizeof(struct BlobIndex
);
1497 alloc
+= sizeof(struct Blob
);
1498 // XXX: this is just a "sufficiently large number"
1502 _foreach (slot
, slots
)
1503 special
= std::max(special
, slot
.first
);
1505 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1506 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1507 special
= std::max(special
, CSSLOT_INFOSLOT
);
1510 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1511 alloc
= Align(alloc
+ (special
+ normal
) * LDID_SHA1_DIGEST_LENGTH
, 16);
1513 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1517 std::stringbuf data
;
1519 if (requirement
.empty()) {
1521 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1523 put(data
, requirement
.data(), requirement
.size());
1526 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1529 if (!entitlements
.empty()) {
1530 std::stringbuf data
;
1531 put(data
, entitlements
.data(), entitlements
.size());
1532 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1536 std::stringbuf data
;
1540 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1541 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1542 sha1(posts
[CSSLOT_INFOSLOT
], data
, size
);
1545 uint32_t special(0);
1546 _foreach (blob
, blobs
)
1547 special
= std::max(special
, blob
.first
);
1548 _foreach (slot
, posts
)
1549 special
= std::max(special
, slot
.first
);
1550 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1552 CodeDirectory directory
;
1553 directory
.version
= Swap(uint32_t(0x00020200));
1554 directory
.flags
= Swap(uint32_t(0));
1555 directory
.nSpecialSlots
= Swap(special
);
1556 directory
.codeLimit
= Swap(uint32_t(limit
));
1557 directory
.nCodeSlots
= Swap(normal
);
1558 directory
.hashSize
= LDID_SHA1_DIGEST_LENGTH
;
1559 directory
.hashType
= CS_HASHTYPE_SHA1
;
1560 directory
.spare1
= 0x00;
1561 directory
.pageSize
= PageShift_
;
1562 directory
.spare2
= Swap(uint32_t(0));
1563 directory
.scatterOffset
= Swap(uint32_t(0));
1564 directory
.spare3
= Swap(uint32_t(0));
1565 directory
.codeLimit64
= Swap(uint64_t(0));
1567 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1569 directory
.identOffset
= Swap(uint32_t(offset
));
1570 offset
+= identifier
.size() + 1;
1573 directory
.teamIDOffset
= Swap(uint32_t(0));
1575 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1576 offset
+= team
.size() + 1;
1579 offset
+= LDID_SHA1_DIGEST_LENGTH
* special
;
1580 directory
.hashOffset
= Swap(uint32_t(offset
));
1581 offset
+= LDID_SHA1_DIGEST_LENGTH
* normal
;
1583 put(data
, &directory
, sizeof(directory
));
1585 put(data
, identifier
.c_str(), identifier
.size() + 1);
1586 put(data
, team
.c_str(), team
.size() + 1);
1588 uint8_t storage
[special
+ normal
][LDID_SHA1_DIGEST_LENGTH
];
1589 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = storage
+ special
;
1591 memset(storage
, 0, sizeof(*storage
) * special
);
1593 _foreach (blob
, blobs
) {
1594 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1595 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1598 _foreach (slot
, posts
) {
1599 _assert(sizeof(*hashes
) == slot
.second
.size());
1600 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1604 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1605 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1607 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1609 put(data
, storage
, sizeof(storage
));
1611 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1614 #ifndef LDID_NOSMIME
1616 std::stringbuf data
;
1617 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1622 Signature
signature(stuff
, sign
);
1623 Buffer
result(signature
);
1624 std::string
value(result
);
1625 put(data
, value
.data(), value
.size());
1627 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1631 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1635 #ifndef LDID_NOTOOLS
1636 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1637 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1639 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1644 std::string
DiskFolder::Path(const std::string
&path
) {
1645 return path_
+ "/" + path
;
1648 DiskFolder::DiskFolder(const std::string
&path
) :
1653 DiskFolder::~DiskFolder() {
1654 if (!std::uncaught_exception())
1655 for (const auto &commit
: commit_
)
1656 Commit(commit
.first
, commit
.second
);
1659 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
) {
1660 std::string
path(Path(root
) + base
);
1662 DIR *dir(opendir(path
.c_str()));
1663 _assert(dir
!= NULL
);
1664 _scope({ _syscall(closedir(dir
)); });
1666 while (auto child
= readdir(dir
)) {
1667 std::string
name(child
->d_name
);
1668 if (name
== "." || name
== "..")
1670 if (Starts(name
, ".ldid."))
1677 _syscall(stat(path
.c_str(), &info
));
1679 else if (S_ISDIR(info
.st_mode
))
1681 else if (S_ISREG(info
.st_mode
))
1684 _assert_(false, "st_mode=%x", info
.st_mode
);
1686 switch (child
->d_type
) {
1694 _assert_(false, "d_type=%u", child
->d_type
);
1699 Find(root
, base
+ name
+ "/", code
);
1701 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1702 std::string
access(root
+ base
+ name
);
1703 _assert_(Open(access
, fun([&](std::streambuf
&data
, const void *flag
) {
1706 })), "open(): %s", access
.c_str());
1711 void DiskFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1713 auto from(Path(path
));
1714 commit_
[from
] = Temporary(save
, from
);
1718 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1720 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1723 _assert(result
== &data
);
1728 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1729 Find(path
, "", code
);
1733 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1739 void SubFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1740 return parent_
.Save(path_
+ path
, flag
, code
);
1743 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1744 return parent_
.Open(path_
+ path
, code
);
1747 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1748 return parent_
.Find(path_
+ path
, code
);
1751 std::string
UnionFolder::Map(const std::string
&path
) {
1752 auto remap(remaps_
.find(path
));
1753 if (remap
== remaps_
.end())
1755 return remap
->second
;
1758 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
) {
1759 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
1760 code(file
.substr(path
.size()), fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1761 save(fun([&](std::streambuf
&data
, const void *flag
) {
1762 parent_
.Save(file
, flag
, fun([&](std::streambuf
&save
) {
1769 UnionFolder::UnionFolder(Folder
&parent
) :
1774 void UnionFolder::Save(const std::string
&path
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1775 return parent_
.Save(Map(path
), flag
, code
);
1778 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, const void *)> &code
) {
1779 auto file(resets_
.find(path
));
1780 if (file
== resets_
.end())
1781 return parent_
.Open(Map(path
), code
);
1782 auto &entry(file
->second
);
1784 auto &data(entry
.first
);
1785 data
.pubseekpos(0, std::ios::in
);
1786 code(data
, entry
.second
);
1790 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1791 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1792 if (deletes_
.find(path
+ name
) == deletes_
.end())
1796 for (auto &reset
: resets_
)
1797 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, const void *)> &code
) {
1798 auto &entry(reset
.second
);
1799 entry
.first
.pubseekpos(0, std::ios::in
);
1800 code(entry
.first
, entry
.second
);
1803 for (auto &remap
: remaps_
)
1804 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, const void *)> &code
) {
1805 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, const void *flag
) {
1811 #ifndef LDID_NOTOOLS
1812 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1816 size_t writ(source
.sgetn(data
, sizeof(data
)));
1819 _assert(target
.sputn(data
, writ
) == writ
);
1825 #ifndef LDID_NOPLIST
1826 static plist_t
plist(const std::string
&data
) {
1827 plist_t
plist(NULL
);
1828 if (Starts(data
, "bplist00"))
1829 plist_from_bin(data
.data(), data
.size(), &plist
);
1831 plist_from_xml(data
.data(), data
.size(), &plist
);
1832 _assert(plist
!= NULL
);
1836 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1837 std::stringbuf data
;
1839 auto node(plist(data
.str()));
1840 _scope({ plist_free(node
); });
1841 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1845 static std::string
plist_s(plist_t node
) {
1846 _assert(node
!= NULL
);
1847 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1849 plist_get_string_val(node
, &data
);
1850 _scope({ free(data
); });
1868 Expression(const std::string
&code
) {
1869 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1876 bool operator ()(const std::string
&data
) const {
1877 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1878 if (value
== REG_NOMATCH
)
1880 _assert_(value
== 0, "regexec()");
1890 mutable std::auto_ptr
<Expression
> regex_
;
1892 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1899 Rule(const Rule
&rhs
) :
1900 weight_(rhs
.weight_
),
1906 void Compile() const {
1907 regex_
.reset(new Expression(code_
));
1910 bool operator ()(const std::string
&data
) const {
1911 _assert(regex_
.get() != NULL
);
1912 return (*regex_
)(data
);
1915 bool operator <(const Rule
&rhs
) const {
1916 if (weight_
> rhs
.weight_
)
1918 if (weight_
< rhs
.weight_
)
1920 return mode_
> rhs
.mode_
;
1925 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1926 return lhs
->code_
< rhs
->code_
;
1930 #ifndef LDID_NOPLIST
1931 static void Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, std::vector
<char> &hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirement
, const std::string
&key
, const Slots
&slots
) {
1932 // XXX: this is a miserable fail
1933 std::stringbuf temp
;
1934 put(temp
, prefix
, size
);
1936 auto data(temp
.str());
1938 HashProxy
proxy(hash
, save
);
1939 Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, requirement
, key
, slots
);
1942 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
, const std::string
&requirement
) {
1943 std::string executable
;
1944 std::string identifier
;
1946 static const std::string
info("Info.plist");
1948 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
, const void *flag
) {
1949 plist_d(buffer
, fun([&](plist_t node
) {
1950 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1951 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1953 })), "open(): Info.plist");
1955 static const std::string
directory("_CodeSignature/");
1956 static const std::string
signature(directory
+ "CodeResources");
1958 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1960 auto &rules1(versions
[""]);
1961 auto &rules2(versions
["2"]);
1963 folder
.Open(signature
, fun([&](std::streambuf
&buffer
, const void *) {
1964 plist_d(buffer
, fun([&](plist_t node
) {
1965 // XXX: maybe attempt to preserve existing rules
1970 rules1
.insert(Rule
{1, NoMode
, "^"});
1971 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1972 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1973 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1974 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1975 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1979 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1980 rules2
.insert(Rule
{20, NoMode
, "^"});
1981 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1982 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1983 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1984 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1985 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1986 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1987 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1988 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1989 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1990 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1991 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1992 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1995 std::map
<std::string
, std::vector
<char>> local
;
1997 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1999 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
2002 auto bundle(root
+ Split(name
).dir
);
2003 SubFolder
subfolder(folder
, bundle
);
2004 Bundle(bundle
, subfolder
, key
, local
, "", "");
2007 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
2008 // BundleDiskRep::adjustResources -> builder.addExclusion
2009 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2012 auto &hash(local
[name
]);
2016 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
2026 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2027 if (size
== sizeof(header
.bytes
))
2028 switch (Swap(header
.magic
)) {
2030 // Java class file format
2031 if (Swap(header
.count
) >= 40)
2034 case MH_MAGIC
: case MH_MAGIC_64
:
2035 case MH_CIGAM
: case MH_CIGAM_64
:
2037 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", "", key
, slots
);
2041 HashProxy
proxy(hash
, save
);
2042 put(proxy
, header
.bytes
, size
);
2046 _assert(hash
.size() == LDID_SHA1_DIGEST_LENGTH
);
2049 auto plist(plist_new_dict());
2050 _scope({ plist_free(plist
); });
2052 for (const auto &version
: versions
) {
2053 auto files(plist_new_dict());
2054 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2056 for (const auto &rule
: version
.second
)
2059 for (const auto &hash
: local
)
2060 for (const auto &rule
: version
.second
)
2061 if (rule(hash
.first
)) {
2062 if (rule
.mode_
== NoMode
)
2063 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
2064 else if (rule
.mode_
== OptionalMode
) {
2065 auto entry(plist_new_dict());
2066 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
2067 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2068 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2075 for (const auto &version
: versions
) {
2076 auto rules(plist_new_dict());
2077 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2079 std::multiset
<const Rule
*, RuleCode
> ordered
;
2080 for (const auto &rule
: version
.second
)
2081 ordered
.insert(&rule
);
2083 for (const auto &rule
: ordered
)
2084 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2085 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2087 auto entry(plist_new_dict());
2088 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2090 switch (rule
->mode_
) {
2094 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2097 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2100 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2103 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2107 if (rule
->weight_
>= 10000)
2108 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2109 else if (rule
->weight_
!= 1)
2110 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2114 folder
.Save(signature
, NULL
, fun([&](std::streambuf
&save
) {
2115 HashProxy
proxy(local
[signature
], save
);
2118 plist_to_xml(plist
, &xml
, &size
);
2119 _scope({ free(xml
); });
2120 put(proxy
, xml
, size
);
2123 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, const void *flag
) {
2124 folder
.Save(executable
, flag
, fun([&](std::streambuf
&save
) {
2126 slots
[1] = local
.at(info
);
2127 slots
[3] = local
.at(signature
);
2128 Sign(NULL
, 0, buffer
, local
[executable
], save
, identifier
, entitlements
, requirement
, key
, slots
);
2132 for (const auto &hash
: local
)
2133 remote
[root
+ hash
.first
] = hash
.second
;
2142 #ifndef LDID_NOTOOLS
2143 int main(int argc
, char *argv
[]) {
2144 #ifndef LDID_NOSMIME
2145 OpenSSL_add_all_algorithms();
2153 little_
= endian
.byte
[0];
2159 #ifndef LDID_NOFLAGT
2173 uint32_t flag_CPUType(_not(uint32_t));
2174 uint32_t flag_CPUSubtype(_not(uint32_t));
2176 const char *flag_I(NULL
);
2178 #ifndef LDID_NOFLAGT
2188 std::vector
<std::string
> files
;
2191 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2192 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2193 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2194 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2198 for (int argi(1); argi
!= argc
; ++argi
)
2199 if (argv
[argi
][0] != '-')
2200 files
.push_back(argv
[argi
]);
2201 else switch (argv
[argi
][1]) {
2208 case 'e': flag_e
= true; break;
2211 const char *slot
= argv
[argi
] + 2;
2212 const char *colon
= strchr(slot
, ':');
2213 _assert(colon
!= NULL
);
2214 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2216 unsigned number(strtoul(slot
, &arge
, 0));
2217 _assert(arge
== colon
);
2218 sha1(slots
[number
], file
.data(), file
.size());
2221 case 'q': flag_q
= true; break;
2224 const char *xml
= argv
[argi
] + 2;
2225 requirement
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2228 case 'D': flag_D
= true; break;
2230 case 'a': flag_a
= true; break;
2235 if (argv
[argi
][2] != '\0') {
2236 const char *cpu
= argv
[argi
] + 2;
2237 const char *colon
= strchr(cpu
, ':');
2238 _assert(colon
!= NULL
);
2240 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2241 _assert(arge
== colon
);
2242 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2243 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2257 if (argv
[argi
][2] != '\0') {
2258 const char *xml
= argv
[argi
] + 2;
2259 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2264 if (argv
[argi
][2] != '\0')
2265 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2268 #ifndef LDID_NOFLAGT
2271 if (argv
[argi
][2] == '-')
2275 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2276 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2286 flag_I
= argv
[argi
] + 2;
2294 _assert(flag_S
|| key
.empty());
2295 _assert(flag_S
|| flag_I
== NULL
);
2297 if (files
.empty()) usage
: {
2301 size_t filei(0), filee(0);
2302 _foreach (file
, files
) try {
2303 std::string
path(file
);
2306 _syscall(stat(path
.c_str(), &info
));
2308 if (S_ISDIR(info
.st_mode
)) {
2309 #ifndef LDID_NOPLIST
2311 ldid::DiskFolder
folder(path
);
2312 std::map
<std::string
, std::vector
<char>> hashes
;
2313 path
+= "/" + Bundle("", folder
, key
, hashes
, entitlements
, requirement
);
2317 } else if (flag_S
|| flag_r
) {
2318 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2320 std::filebuf output
;
2322 auto temp(Temporary(output
, split
));
2325 ldid::Unsign(input
.data(), input
.size(), output
);
2327 std::string
identifier(flag_I
?: split
.base
.c_str());
2328 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, requirement
, key
, slots
);
2335 #ifndef LDID_NOFLAGT
2342 Map
mapping(path
, modify
);
2343 FatHeader
fat_header(mapping
.data(), mapping
.size());
2345 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2346 struct linkedit_data_command
*signature(NULL
);
2347 struct encryption_info_command
*encryption(NULL
);
2350 if (mach_header
.GetCPUType() != flag_CPUType
)
2352 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2357 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2359 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2360 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2363 else if (cmd
== LC_CODE_SIGNATURE
)
2364 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2365 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2366 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2367 else if (cmd
== LC_LOAD_DYLIB
) {
2368 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2369 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2371 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2374 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2375 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2379 #ifndef LDID_NOFLAGT
2380 else if (cmd
== LC_ID_DYLIB
) {
2381 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2389 dylib_command
->dylib
.timestamp
= 0;
2390 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2393 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2400 _assert(encryption
!= NULL
);
2401 encryption
->cryptid
= mach_header
.Swap(0);
2405 _assert(signature
!= NULL
);
2407 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2409 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2410 uint8_t *blob
= top
+ data
;
2411 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2413 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2414 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2415 uint32_t begin
= Swap(super
->index
[index
].offset
);
2416 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2417 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2422 _assert(signature
!= NULL
);
2424 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2426 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2427 uint8_t *blob
= top
+ data
;
2428 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2430 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2431 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
2432 uint32_t begin
= Swap(super
->index
[index
].offset
);
2433 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2434 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
2439 _assert(signature
!= NULL
);
2441 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2443 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2444 uint8_t *blob
= top
+ data
;
2445 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2447 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2448 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2449 uint32_t begin
= Swap(super
->index
[index
].offset
);
2450 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
2452 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2453 uint32_t pages
= Swap(directory
->nCodeSlots
);
2456 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2457 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2459 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2465 } catch (const char *) {