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)
173 #define FAT_MAGIC 0xcafebabe
174 #define FAT_CIGAM 0xbebafeca
194 #define MH_MAGIC 0xfeedface
195 #define MH_CIGAM 0xcefaedfe
197 #define MH_MAGIC_64 0xfeedfacf
198 #define MH_CIGAM_64 0xcffaedfe
200 #define MH_DYLDLINK 0x4
202 #define MH_OBJECT 0x1
203 #define MH_EXECUTE 0x2
205 #define MH_BUNDLE 0x8
206 #define MH_DYLIB_STUB 0x9
208 struct load_command
{
213 #define LC_REQ_DYLD uint32_t(0x80000000)
215 #define LC_SEGMENT uint32_t(0x01)
216 #define LC_SYMTAB uint32_t(0x02)
217 #define LC_DYSYMTAB uint32_t(0x0b)
218 #define LC_LOAD_DYLIB uint32_t(0x0c)
219 #define LC_ID_DYLIB uint32_t(0x0d)
220 #define LC_SEGMENT_64 uint32_t(0x19)
221 #define LC_UUID uint32_t(0x1b)
222 #define LC_CODE_SIGNATURE uint32_t(0x1d)
223 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
224 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
225 #define LC_ENCRYPTION_INFO uint32_t(0x21)
226 #define LC_DYLD_INFO uint32_t(0x22)
227 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
228 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
233 uint32_t current_version
;
234 uint32_t compatibility_version
;
237 struct dylib_command
{
243 struct uuid_command
{
249 struct symtab_command
{
258 struct dyld_info_command
{
262 uint32_t rebase_size
;
265 uint32_t weak_bind_off
;
266 uint32_t weak_bind_size
;
267 uint32_t lazy_bind_off
;
268 uint32_t lazy_bind_size
;
270 uint32_t export_size
;
273 struct dysymtab_command
{
286 uint32_t extrefsymoff
;
287 uint32_t nextrefsyms
;
288 uint32_t indirectsymoff
;
289 uint32_t nindirectsyms
;
296 struct dylib_table_of_contents
{
297 uint32_t symbol_index
;
298 uint32_t module_index
;
301 struct dylib_module
{
302 uint32_t module_name
;
311 uint32_t iinit_iterm
;
312 uint32_t ninit_nterm
;
313 uint32_t objc_module_info_addr
;
314 uint32_t objc_module_info_size
;
317 struct dylib_reference
{
322 struct relocation_info
{
324 uint32_t r_symbolnum
:24;
343 struct segment_command
{
357 struct segment_command_64
{
399 struct linkedit_data_command
{
406 struct encryption_info_command
{
414 #define BIND_OPCODE_MASK 0xf0
415 #define BIND_IMMEDIATE_MASK 0x0f
416 #define BIND_OPCODE_DONE 0x00
417 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
418 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
419 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
420 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
421 #define BIND_OPCODE_SET_TYPE_IMM 0x50
422 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
423 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
424 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
425 #define BIND_OPCODE_DO_BIND 0x90
426 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
427 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
428 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
430 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
431 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
434 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
435 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
438 inline void pad(std::streambuf
&stream
, size_t size
) {
440 memset(padding
, 0, size
);
441 put(stream
, padding
, size
);
444 template <typename Type_
>
445 Type_
Align(Type_ value
, size_t align
) {
452 static const uint8_t PageShift_(0x0c);
453 static const uint32_t PageSize_(1 << PageShift_
);
455 static inline uint16_t Swap_(uint16_t value
) {
457 ((value
>> 8) & 0x00ff) |
458 ((value
<< 8) & 0xff00);
461 static inline uint32_t Swap_(uint32_t value
) {
462 value
= ((value
>> 8) & 0x00ff00ff) |
463 ((value
<< 8) & 0xff00ff00);
464 value
= ((value
>> 16) & 0x0000ffff) |
465 ((value
<< 16) & 0xffff0000);
469 static inline uint64_t Swap_(uint64_t value
) {
470 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
471 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
472 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
476 static inline int16_t Swap_(int16_t value
) {
477 return Swap_(static_cast<uint16_t>(value
));
480 static inline int32_t Swap_(int32_t value
) {
481 return Swap_(static_cast<uint32_t>(value
));
484 static inline int64_t Swap_(int64_t value
) {
485 return Swap_(static_cast<uint64_t>(value
));
488 static bool little_(true);
490 static inline uint16_t Swap(uint16_t value
) {
491 return little_
? Swap_(value
) : value
;
494 static inline uint32_t Swap(uint32_t value
) {
495 return little_
? Swap_(value
) : value
;
498 static inline uint64_t Swap(uint64_t value
) {
499 return little_
? Swap_(value
) : value
;
502 static inline int16_t Swap(int16_t value
) {
503 return Swap(static_cast<uint16_t>(value
));
506 static inline int32_t Swap(int32_t value
) {
507 return Swap(static_cast<uint32_t>(value
));
510 static inline int64_t Swap(int64_t value
) {
511 return Swap(static_cast<uint64_t>(value
));
514 template <typename Target_
>
527 Swapped(bool swapped
) :
532 template <typename Type_
>
533 Type_
Swap(Type_ value
) const {
534 return swapped_
? Swap_(value
) : value
;
546 Data(void *base
, size_t size
) :
552 void *GetBase() const {
556 size_t GetSize() const {
567 struct mach_header
*mach_header_
;
568 struct load_command
*load_command_
;
571 MachHeader(void *base
, size_t size
) :
574 mach_header_
= (mach_header
*) base
;
576 switch (Swap(mach_header_
->magic
)) {
578 swapped_
= !swapped_
;
584 swapped_
= !swapped_
;
593 void *post
= mach_header_
+ 1;
595 post
= (uint32_t *) post
+ 1;
596 load_command_
= (struct load_command
*) post
;
599 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
600 Swap(mach_header_
->filetype
) == MH_DYLIB
||
601 Swap(mach_header_
->filetype
) == MH_BUNDLE
605 bool Bits64() const {
609 struct mach_header
*operator ->() const {
613 operator struct mach_header
*() const {
617 uint32_t GetCPUType() const {
618 return Swap(mach_header_
->cputype
);
621 uint32_t GetCPUSubtype() const {
622 return Swap(mach_header_
->cpusubtype
) & 0xff;
625 struct load_command
*GetLoadCommand() const {
626 return load_command_
;
629 std::vector
<struct load_command
*> GetLoadCommands() const {
630 std::vector
<struct load_command
*> load_commands
;
632 struct load_command
*load_command
= load_command_
;
633 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
634 load_commands
.push_back(load_command
);
635 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
638 return load_commands
;
641 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
642 std::vector
<struct segment_command
*> segment_commands
;
644 _foreach (load_command
, GetLoadCommands()) {
645 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
646 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
647 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
648 segment_commands
.push_back(segment_command
);
652 return segment_commands
;
655 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
656 std::vector
<struct segment_command_64
*> segment_commands
;
658 _foreach (load_command
, GetLoadCommands()) {
659 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
660 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
661 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
662 segment_commands
.push_back(segment_command
);
666 return segment_commands
;
669 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
670 std::vector
<section
*> sections
;
672 _foreach (segment
, GetSegments(segment_name
)) {
673 section
*section
= (struct section
*) (segment
+ 1);
676 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
677 if (strncmp(section
->sectname
, section_name
, 16) == 0)
678 sections
.push_back(section
);
686 template <typename Target_
>
687 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
688 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
691 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
692 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
693 segment_command
*segment_command
= (struct segment_command
*) load_command
;
694 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
697 section
*sections
= (struct section
*) (segment_command
+ 1);
700 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
701 section
*section
= §ions
[sect
];
702 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
703 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
704 //printf("0x%.8x %s\n", address, segment_command->segname);
705 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
711 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
714 return Pointer
<Target_
>(this);
717 template <typename Target_
>
718 Pointer
<Target_
> GetOffset(uint32_t offset
) {
719 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
723 class FatMachHeader
:
730 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
731 MachHeader(base
, size
),
736 fat_arch
*GetFatArch() const {
745 fat_header
*fat_header_
;
746 std::vector
<FatMachHeader
> mach_headers_
;
749 FatHeader(void *base
, size_t size
) :
752 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
754 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
755 swapped_
= !swapped_
;
757 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
759 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
761 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
762 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
764 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
765 uint32_t arch_offset
= Swap(fat_arch
->offset
);
766 uint32_t arch_size
= Swap(fat_arch
->size
);
767 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
773 std::vector
<FatMachHeader
> &GetMachHeaders() {
774 return mach_headers_
;
778 return fat_header_
!= NULL
;
781 struct fat_header
*operator ->() const {
785 operator struct fat_header
*() const {
790 template <typename Target_
>
793 const MachHeader
*framework_
;
794 const Target_
*pointer_
;
797 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
798 framework_(framework
),
803 operator const Target_
*() const {
807 const Target_
*operator ->() const {
811 Pointer
<Target_
> &operator ++() {
816 template <typename Value_
>
817 Value_
Swap(Value_ value
) {
818 return framework_
->Swap(value
);
822 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
823 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
824 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
825 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
826 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
827 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
828 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
829 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
831 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
832 #define CSSLOT_INFOSLOT uint32_t(0x00001)
833 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
834 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
835 #define CSSLOT_APPLICATION uint32_t(0x00004)
836 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
838 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
840 #define CS_HASHTYPE_SHA1 1
855 struct BlobIndex index
[];
858 struct CodeDirectory
{
862 uint32_t identOffset
;
863 uint32_t nSpecialSlots
;
874 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
877 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
878 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
881 struct CodesignAllocation
{
882 FatMachHeader mach_header_
;
889 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
890 mach_header_(mach_header
),
912 _syscall(close(file_
));
915 void open(const char *path
, int flags
) {
916 _assert(file_
== -1);
917 file_
= _syscall(::open(path
, flags
));
934 _syscall(munmap(data_
, size_
));
946 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
949 open(path
, oflag
, pflag
, mflag
);
952 Map(const std::string
&path
, bool edit
) :
963 return data_
== NULL
;
966 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
969 file_
.open(path
.c_str(), oflag
);
970 int file(file_
.file());
973 _syscall(fstat(file
, &stat
));
974 size_
= stat
.st_size
;
976 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
979 void open(const std::string
&path
, bool edit
) {
981 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
983 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
990 size_t size() const {
994 operator std::string() const {
995 return std::string(static_cast<char *>(data_
), size_
);
1001 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (size_t)> &allocate
, const Functor
<size_t (std::streambuf
&output
, size_t, const std::string
&, const char *)> &save
) {
1002 FatHeader
source(const_cast<void *>(idata
), isize
);
1006 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1008 std::vector
<CodesignAllocation
> allocations
;
1009 _foreach (mach_header
, source
.GetMachHeaders()) {
1010 struct linkedit_data_command
*signature(NULL
);
1011 struct symtab_command
*symtab(NULL
);
1013 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1014 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1016 else if (cmd
== LC_CODE_SIGNATURE
)
1017 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1018 else if (cmd
== LC_SYMTAB
)
1019 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1023 if (signature
== NULL
)
1024 size
= mach_header
.GetSize();
1026 size
= mach_header
.Swap(signature
->dataoff
);
1027 _assert(size
<= mach_header
.GetSize());
1030 if (symtab
!= NULL
) {
1031 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1032 _assert(end
<= size
);
1033 _assert(end
>= size
- 0x10);
1037 size_t alloc(allocate(size
));
1039 auto *fat_arch(mach_header
.GetFatArch());
1040 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1041 offset
= Align(offset
, 1 << align
);
1043 uint32_t limit(size
);
1045 limit
= Align(limit
, 0x10);
1047 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1048 offset
+= size
+ alloc
;
1049 offset
= Align(offset
, 0x10);
1054 if (source
.IsFat()) {
1055 fat_header fat_header
;
1056 fat_header
.magic
= Swap(FAT_MAGIC
);
1057 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1058 put(output
, &fat_header
, sizeof(fat_header
));
1059 position
+= sizeof(fat_header
);
1061 _foreach (allocation
, allocations
) {
1062 auto &mach_header(allocation
.mach_header_
);
1065 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1066 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1067 fat_arch
.offset
= Swap(allocation
.offset_
);
1068 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1069 fat_arch
.align
= Swap(allocation
.align_
);
1070 put(output
, &fat_arch
, sizeof(fat_arch
));
1071 position
+= sizeof(fat_arch
);
1075 _foreach (allocation
, allocations
) {
1076 auto &mach_header(allocation
.mach_header_
);
1078 pad(output
, allocation
.offset_
- position
);
1079 position
= allocation
.offset_
;
1081 std::vector
<std::string
> commands
;
1083 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1084 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1086 switch (mach_header
.Swap(load_command
->cmd
)) {
1087 case LC_CODE_SIGNATURE
:
1092 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1093 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1095 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1096 segment_command
->filesize
= size
;
1097 segment_command
->vmsize
= Align(size
, PageSize_
);
1100 case LC_SEGMENT_64
: {
1101 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1102 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1104 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1105 segment_command
->filesize
= size
;
1106 segment_command
->vmsize
= Align(size
, PageSize_
);
1110 commands
.push_back(copy
);
1113 if (allocation
.alloc_
!= 0) {
1114 linkedit_data_command signature
;
1115 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1116 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1117 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1118 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1119 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1122 size_t begin(position
);
1125 _foreach(command
, commands
)
1126 after
+= command
.size();
1128 std::stringbuf altern
;
1130 struct mach_header
header(*mach_header
);
1131 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1132 header
.sizeofcmds
= mach_header
.Swap(after
);
1133 put(output
, &header
, sizeof(header
));
1134 put(altern
, &header
, sizeof(header
));
1135 position
+= sizeof(header
);
1137 if (mach_header
.Bits64()) {
1138 auto pad(mach_header
.Swap(uint32_t(0)));
1139 put(output
, &pad
, sizeof(pad
));
1140 put(altern
, &pad
, sizeof(pad
));
1141 position
+= sizeof(pad
);
1144 _foreach(command
, commands
) {
1145 put(output
, command
.data(), command
.size());
1146 put(altern
, command
.data(), command
.size());
1147 position
+= command
.size();
1150 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1151 if (before
> after
) {
1152 pad(output
, before
- after
);
1153 pad(altern
, before
- after
);
1154 position
+= before
- after
;
1157 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1159 std::string
overlap(altern
.str());
1160 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1162 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1163 position
= begin
+ allocation
.size_
;
1165 pad(output
, allocation
.limit_
- allocation
.size_
);
1166 position
+= allocation
.limit_
- allocation
.size_
;
1168 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1169 if (allocation
.alloc_
> saved
)
1170 pad(output
, allocation
.alloc_
- saved
);
1171 position
+= allocation
.alloc_
;
1177 typedef std::map
<uint32_t, std::string
> Blobs
;
1179 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1180 auto value(buffer
.str());
1181 std::swap(blobs
[slot
], value
);
1184 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1185 auto value(buffer
.str());
1187 blob
.magic
= Swap(magic
);
1188 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1189 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1190 std::swap(blobs
[slot
], value
);
1193 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1195 _foreach (blob
, blobs
)
1196 total
+= blob
.second
.size();
1198 struct SuperBlob super
;
1199 super
.blob
.magic
= Swap(magic
);
1200 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1201 super
.count
= Swap(uint32_t(blobs
.size()));
1202 put(output
, &super
, sizeof(super
));
1204 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1206 _foreach (blob
, blobs
) {
1208 index
.type
= Swap(blob
.first
);
1209 index
.offset
= Swap(uint32_t(offset
));
1210 put(output
, &index
, sizeof(index
));
1211 offset
+= blob
.second
.size();
1214 _foreach (blob
, blobs
)
1215 put(output
, blob
.second
.data(), blob
.second
.size());
1220 #ifndef LDID_NOSMIME
1229 _assert(bio_
!= NULL
);
1233 bio_(BIO_new(BIO_s_mem()))
1237 Buffer(const char *data
, size_t size
) :
1238 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1242 Buffer(const std::string
&data
) :
1243 Buffer(data
.data(), data
.size())
1247 Buffer(PKCS7
*pkcs
) :
1250 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1257 operator BIO
*() const {
1261 explicit operator std::string() const {
1263 auto size(BIO_get_mem_data(bio_
, &data
));
1264 return std::string(data
, size
);
1273 STACK_OF(X509
) *ca_
;
1277 value_(d2i_PKCS12_bio(bio
, NULL
)),
1280 _assert(value_
!= NULL
);
1281 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1282 _assert(key_
!= NULL
);
1283 _assert(cert_
!= NULL
);
1286 Stuff(const std::string
&data
) :
1292 sk_X509_pop_free(ca_
, X509_free
);
1294 EVP_PKEY_free(key_
);
1295 PKCS12_free(value_
);
1298 operator PKCS12
*() const {
1302 operator EVP_PKEY
*() const {
1306 operator X509
*() const {
1310 operator STACK_OF(X509
) *() const {
1320 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1321 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1323 _assert(value_
!= NULL
);
1330 operator PKCS7
*() const {
1337 public std::streambuf
1340 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1344 virtual int_type
overflow(int_type next
) {
1350 public std::streambuf
1353 std::vector
<char> &hash_
;
1354 LDID_SHA1_CTX context_
;
1357 HashBuffer(std::vector
<char> &hash
) :
1360 LDID_SHA1_Init(&context_
);
1364 hash_
.resize(LDID_SHA1_DIGEST_LENGTH
);
1365 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1368 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1369 LDID_SHA1_Update(&context_
, data
, size
);
1373 virtual int_type
overflow(int_type next
) {
1374 if (next
== traits_type::eof())
1386 std::streambuf
&buffer_
;
1389 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1395 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1396 _assert(HashBuffer::xsputn(data
, size
) == size
);
1397 return buffer_
.sputn(data
, size
);
1401 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1402 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1410 Split(const std::string
&path
) {
1411 size_t slash(path
.rfind('/'));
1412 if (slash
== std::string::npos
)
1415 dir
= path
.substr(0, slash
+ 1);
1416 base
= path
.substr(slash
+ 1);
1421 static void mkdir_p(const std::string
&path
) {
1425 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1428 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1431 auto slash(path
.rfind('/', path
.size() - 1));
1432 if (slash
== std::string::npos
)
1434 mkdir_p(path
.substr(0, slash
));
1437 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1438 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1440 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1444 static void Commit(const std::string
&path
, const std::string
&temp
) {
1446 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1448 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1450 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1453 _syscall(rename(temp
.c_str(), path
.c_str()));
1458 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
) {
1459 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1460 size_t alloc(sizeof(struct SuperBlob
));
1462 uint32_t special(0);
1464 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1465 alloc
+= sizeof(struct BlobIndex
);
1468 if (!entitlements
.empty()) {
1469 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1470 alloc
+= sizeof(struct BlobIndex
);
1471 alloc
+= sizeof(struct Blob
);
1472 alloc
+= entitlements
.size();
1475 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1476 alloc
+= sizeof(struct BlobIndex
);
1477 alloc
+= sizeof(struct Blob
);
1478 alloc
+= sizeof(struct CodeDirectory
);
1479 alloc
+= identifier
.size() + 1;
1482 alloc
+= sizeof(struct BlobIndex
);
1483 alloc
+= sizeof(struct Blob
);
1484 // XXX: this is just a "sufficiently large number"
1488 _foreach (slot
, slots
)
1489 special
= std::max(special
, slot
.first
);
1491 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1492 alloc
= Align(alloc
+ (special
+ normal
) * LDID_SHA1_DIGEST_LENGTH
, 16);
1494 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1498 std::stringbuf data
;
1501 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1503 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1506 if (!entitlements
.empty()) {
1507 std::stringbuf data
;
1508 put(data
, entitlements
.data(), entitlements
.size());
1509 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1513 std::stringbuf data
;
1515 uint32_t special(0);
1516 _foreach (blob
, blobs
)
1517 special
= std::max(special
, blob
.first
);
1518 _foreach (slot
, slots
)
1519 special
= std::max(special
, slot
.first
);
1520 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1522 CodeDirectory directory
;
1523 directory
.version
= Swap(uint32_t(0x00020001));
1524 directory
.flags
= Swap(uint32_t(0));
1525 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + identifier
.size() + 1 + LDID_SHA1_DIGEST_LENGTH
* special
));
1526 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1527 directory
.nSpecialSlots
= Swap(special
);
1528 directory
.codeLimit
= Swap(uint32_t(limit
));
1529 directory
.nCodeSlots
= Swap(normal
);
1530 directory
.hashSize
= LDID_SHA1_DIGEST_LENGTH
;
1531 directory
.hashType
= CS_HASHTYPE_SHA1
;
1532 directory
.spare1
= 0x00;
1533 directory
.pageSize
= PageShift_
;
1534 directory
.spare2
= Swap(uint32_t(0));
1535 put(data
, &directory
, sizeof(directory
));
1537 put(data
, identifier
.c_str(), identifier
.size() + 1);
1539 uint8_t storage
[special
+ normal
][LDID_SHA1_DIGEST_LENGTH
];
1540 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = storage
+ special
;
1542 memset(storage
, 0, sizeof(*storage
) * special
);
1544 _foreach (blob
, blobs
) {
1545 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1546 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1549 _foreach (slot
, slots
) {
1550 _assert(sizeof(*hashes
) == slot
.second
.size());
1551 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1555 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1556 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1558 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1560 put(data
, storage
, sizeof(storage
));
1562 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1565 #ifndef LDID_NOSMIME
1567 std::stringbuf data
;
1568 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1573 Signature
signature(stuff
, sign
);
1574 Buffer
result(signature
);
1575 std::string
value(result
);
1576 put(data
, value
.data(), value
.size());
1578 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1582 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1586 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1587 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1589 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1594 std::string
DiskFolder::Path(const std::string
&path
) {
1595 return path_
+ "/" + path
;
1598 DiskFolder::DiskFolder(const std::string
&path
) :
1603 DiskFolder::~DiskFolder() {
1604 if (!std::uncaught_exception())
1605 for (const auto &commit
: commit_
)
1606 Commit(commit
.first
, commit
.second
);
1609 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
) {
1610 std::string
path(Path(root
) + base
);
1612 DIR *dir(opendir(path
.c_str()));
1613 _assert(dir
!= NULL
);
1614 _scope({ _syscall(closedir(dir
)); });
1616 while (auto child
= readdir(dir
)) {
1617 std::string
name(child
->d_name
);
1618 if (name
== "." || name
== "..")
1620 if (Starts(name
, ".ldid."))
1627 _syscall(stat(path
.c_str(), &info
));
1629 else if (S_ISDIR(info
.st_mode
))
1631 else if (S_ISREG(info
.st_mode
))
1634 _assert_(false, "st_mode=%x", info
.st_mode
);
1636 switch (child
->d_type
) {
1644 _assert_(false, "d_type=%u", child
->d_type
);
1649 Find(root
, base
+ name
+ "/", code
);
1651 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1652 std::string
access(root
+ base
+ name
);
1653 _assert_(Open(access
, fun([&](std::streambuf
&data
) {
1656 })), "open(): %s", access
.c_str());
1661 void DiskFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1663 auto from(Path(path
));
1664 commit_
[from
] = Temporary(save
, from
);
1668 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1670 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1673 _assert(result
== &data
);
1678 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1679 Find(path
, "", code
);
1682 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1688 void SubFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1689 return parent_
.Save(path_
+ path
, code
);
1692 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1693 return parent_
.Open(path_
+ path
, code
);
1696 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1697 return parent_
.Find(path_
+ path
, code
);
1700 UnionFolder::UnionFolder(Folder
&parent
) :
1705 void UnionFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1706 return parent_
.Save(path
, code
);
1709 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1710 auto file(files_
.find(path
));
1711 if (file
== files_
.end())
1712 return parent_
.Open(path
, code
);
1714 auto &data(file
->second
);
1715 data
.pubseekpos(0, std::ios::in
);
1720 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1721 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1722 if (files_
.find(name
) == files_
.end())
1726 for (auto &file
: files_
)
1727 code(file
.first
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1728 parent_
.Save(file
.first
, fun([&](std::streambuf
&save
) {
1729 file
.second
.pubseekpos(0, std::ios::in
);
1730 code(file
.second
, save
);
1735 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1739 size_t writ(source
.sgetn(data
, sizeof(data
)));
1742 _assert(target
.sputn(data
, writ
) == writ
);
1748 #ifndef LDID_NOPLIST
1749 static plist_t
plist(const std::string
&data
) {
1750 plist_t
plist(NULL
);
1751 if (Starts(data
, "bplist00"))
1752 plist_from_bin(data
.data(), data
.size(), &plist
);
1754 plist_from_xml(data
.data(), data
.size(), &plist
);
1755 _assert(plist
!= NULL
);
1759 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1760 std::stringbuf data
;
1762 auto node(plist(data
.str()));
1763 _scope({ plist_free(node
); });
1764 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1768 static std::string
plist_s(plist_t node
) {
1769 _assert(node
!= NULL
);
1770 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1772 plist_get_string_val(node
, &data
);
1773 _scope({ free(data
); });
1791 Expression(const std::string
&code
) {
1792 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1799 bool operator ()(const std::string
&data
) const {
1800 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1801 if (value
== REG_NOMATCH
)
1803 _assert_(value
== 0, "regexec()");
1813 mutable std::auto_ptr
<Expression
> regex_
;
1815 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1822 Rule(const Rule
&rhs
) :
1823 weight_(rhs
.weight_
),
1829 void Compile() const {
1830 regex_
.reset(new Expression(code_
));
1833 bool operator ()(const std::string
&data
) const {
1834 _assert(regex_
.get() != NULL
);
1835 return (*regex_
)(data
);
1838 bool operator <(const Rule
&rhs
) const {
1839 if (weight_
> rhs
.weight_
)
1841 if (weight_
< rhs
.weight_
)
1843 return mode_
> rhs
.mode_
;
1848 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1849 return lhs
->code_
< rhs
->code_
;
1853 #ifndef LDID_NOPLIST
1854 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
) {
1855 std::string executable
;
1856 std::string identifier
;
1858 static const std::string
info("Info.plist");
1860 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
) {
1861 plist_d(buffer
, fun([&](plist_t node
) {
1862 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1863 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1865 })), "open(): Info.plist");
1867 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1869 auto &rules1(versions
[""]);
1870 auto &rules2(versions
["2"]);
1872 static const std::string
signature("_CodeSignature/CodeResources");
1874 folder
.Open(signature
, fun([&](std::streambuf
&buffer
) {
1875 plist_d(buffer
, fun([&](plist_t node
) {
1876 // XXX: maybe attempt to preserve existing rules
1881 rules1
.insert(Rule
{1, NoMode
, "^"});
1882 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1883 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1884 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1885 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1886 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1890 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1891 rules2
.insert(Rule
{20, NoMode
, "^"});
1892 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1893 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1894 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1895 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1896 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1897 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1898 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1899 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1900 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1901 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1902 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1903 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1906 std::map
<std::string
, std::vector
<char>> local
;
1908 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1910 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1913 auto bundle(root
+ Split(name
).dir
);
1914 SubFolder
subfolder(folder
, bundle
);
1915 Bundle(bundle
, subfolder
, key
, local
, "");
1918 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1919 if (name
== executable
|| name
== signature
)
1922 auto &hash(local
[name
]);
1926 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1927 HashProxy
proxy(hash
, save
);
1931 _assert(hash
.size() == LDID_SHA1_DIGEST_LENGTH
);
1934 auto plist(plist_new_dict());
1935 _scope({ plist_free(plist
); });
1937 for (const auto &version
: versions
) {
1938 auto files(plist_new_dict());
1939 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
1941 for (const auto &rule
: version
.second
)
1944 for (const auto &hash
: local
)
1945 for (const auto &rule
: version
.second
)
1946 if (rule(hash
.first
)) {
1947 if (rule
.mode_
== NoMode
)
1948 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
1949 else if (rule
.mode_
== OptionalMode
) {
1950 auto entry(plist_new_dict());
1951 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
1952 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1953 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
1960 for (const auto &version
: versions
) {
1961 auto rules(plist_new_dict());
1962 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
1964 std::multiset
<const Rule
*, RuleCode
> ordered
;
1965 for (const auto &rule
: version
.second
)
1966 ordered
.insert(&rule
);
1968 for (const auto &rule
: ordered
)
1969 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
1970 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
1972 auto entry(plist_new_dict());
1973 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
1975 switch (rule
->mode_
) {
1979 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
1982 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1985 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
1988 plist_dict_set_item(entry
, "top", plist_new_bool(true));
1992 if (rule
->weight_
>= 10000)
1993 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
1994 else if (rule
->weight_
!= 1)
1995 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
1999 folder
.Save(signature
, fun([&](std::streambuf
&save
) {
2000 HashProxy
proxy(local
[signature
], save
);
2003 plist_to_xml(plist
, &xml
, &size
);
2004 _scope({ free(xml
); });
2005 put(proxy
, xml
, size
);
2008 folder
.Open(executable
, fun([&](std::streambuf
&buffer
) {
2009 // XXX: this is a miserable fail
2010 std::stringbuf temp
;
2012 auto data(temp
.str());
2014 folder
.Save(executable
, fun([&](std::streambuf
&save
) {
2016 slots
[1] = local
.at(info
);
2017 slots
[3] = local
.at(signature
);
2019 HashProxy
proxy(local
[executable
], save
);
2020 Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, key
, slots
);
2024 for (const auto &hash
: local
)
2025 remote
[root
+ hash
.first
] = hash
.second
;
2033 int main(int argc
, char *argv
[]) {
2034 #ifndef LDID_NOSMIME
2035 OpenSSL_add_all_algorithms();
2043 little_
= endian
.byte
[0];
2048 #ifndef LDID_NOFLAGT
2060 uint32_t flag_CPUType(_not(uint32_t));
2061 uint32_t flag_CPUSubtype(_not(uint32_t));
2063 const char *flag_I(NULL
);
2065 #ifndef LDID_NOFLAGT
2074 std::vector
<std::string
> files
;
2077 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2078 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2079 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2080 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2084 for (int argi(1); argi
!= argc
; ++argi
)
2085 if (argv
[argi
][0] != '-')
2086 files
.push_back(argv
[argi
]);
2087 else switch (argv
[argi
][1]) {
2094 case 'e': flag_e
= true; break;
2097 const char *slot
= argv
[argi
] + 2;
2098 const char *colon
= strchr(slot
, ':');
2099 _assert(colon
!= NULL
);
2100 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2102 unsigned number(strtoul(slot
, &arge
, 0));
2103 _assert(arge
== colon
);
2104 std::vector
<char> &hash(slots
[number
]);
2105 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
2106 sha1(reinterpret_cast<uint8_t *>(hash
.data()), file
.data(), file
.size());
2109 case 'D': flag_D
= true; break;
2111 case 'a': flag_a
= true; break;
2116 if (argv
[argi
][2] != '\0') {
2117 const char *cpu
= argv
[argi
] + 2;
2118 const char *colon
= strchr(cpu
, ':');
2119 _assert(colon
!= NULL
);
2121 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2122 _assert(arge
== colon
);
2123 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2124 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2138 if (argv
[argi
][2] != '\0') {
2139 const char *xml
= argv
[argi
] + 2;
2140 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2145 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2148 #ifndef LDID_NOFLAGT
2151 if (argv
[argi
][2] == '-')
2155 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2156 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2162 flag_I
= argv
[argi
] + 2;
2170 _assert(flag_S
|| key
.empty());
2171 _assert(flag_S
|| flag_I
== NULL
);
2173 if (files
.empty()) usage
: {
2177 size_t filei(0), filee(0);
2178 _foreach (file
, files
) try {
2179 std::string
path(file
);
2182 _syscall(stat(path
.c_str(), &info
));
2184 if (S_ISDIR(info
.st_mode
)) {
2185 #ifndef LDID_NOPLIST
2187 ldid::DiskFolder
folder(path
);
2188 std::map
<std::string
, std::vector
<char>> hashes
;
2189 path
+= "/" + Bundle("", folder
, key
, hashes
, entitlements
);
2193 } else if (flag_S
|| flag_r
) {
2194 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2196 std::filebuf output
;
2198 auto temp(Temporary(output
, split
));
2201 ldid::Unsign(input
.data(), input
.size(), output
);
2203 std::string
identifier(flag_I
?: split
.base
.c_str());
2204 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2211 #ifndef LDID_NOFLAGT
2218 Map
mapping(path
, modify
);
2219 FatHeader
fat_header(mapping
.data(), mapping
.size());
2221 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2222 struct linkedit_data_command
*signature(NULL
);
2223 struct encryption_info_command
*encryption(NULL
);
2226 if (mach_header
.GetCPUType() != flag_CPUType
)
2228 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2233 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2235 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2236 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2239 else if (cmd
== LC_CODE_SIGNATURE
)
2240 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2241 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2242 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2243 #ifndef LDID_NOFLAGT
2244 else if (cmd
== LC_ID_DYLIB
) {
2245 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2253 dylib_command
->dylib
.timestamp
= 0;
2254 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2257 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2264 _assert(encryption
!= NULL
);
2265 encryption
->cryptid
= mach_header
.Swap(0);
2269 _assert(signature
!= NULL
);
2271 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2273 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2274 uint8_t *blob
= top
+ data
;
2275 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2277 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2278 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2279 uint32_t begin
= Swap(super
->index
[index
].offset
);
2280 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2281 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2286 _assert(signature
!= NULL
);
2288 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2290 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2291 uint8_t *blob
= top
+ data
;
2292 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2294 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2295 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2296 uint32_t begin
= Swap(super
->index
[index
].offset
);
2297 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2299 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2300 uint32_t pages
= Swap(directory
->nCodeSlots
);
2303 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2304 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2306 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2312 } catch (const char *) {