1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include <sys/types.h>
45 #include <openssl/err.h>
46 #include <openssl/pem.h>
47 #include <openssl/pkcs7.h>
48 #include <openssl/pkcs12.h>
49 #include <openssl/sha.h>
51 #include <plist/plist.h>
55 #define _assert___(line) \
57 #define _assert__(line) \
60 #define _assert_(expr, format, ...) \
62 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
63 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
66 #define _assert(expr) \
67 _assert_(expr, "%s", #expr)
69 #define _syscall(expr, ...) [&] { for (;;) { \
71 if ((long) _value != -1) \
76 /* XXX: EINTR is included in this list to fix g++ */ \
77 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
78 if (error == success) \
79 return (decltype(expr)) -success; \
80 _assert_(false, "errno=%u", error); \
84 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
90 __attribute__((packed))
92 template <typename Type_
>
94 typedef typename
Type_::const_iterator Result
;
97 #define _foreach(item, list) \
98 for (bool _stop(true); _stop; ) \
99 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
100 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
101 for (bool _suck(true); _suck; _suck = false) \
102 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
107 template <typename Function_
>
115 Scope(const Function_
&function
) :
125 template <typename Function_
>
126 Scope
<Function_
> _scope(const Function_
&function
) {
127 return Scope
<Function_
>(function
);
130 #define _scope__(counter, function) \
131 __attribute__((__unused__)) \
132 const _Scope &_scope ## counter(_scope([&]function))
133 #define _scope_(counter, function) \
134 _scope__(counter, function)
135 #define _scope(function) \
136 _scope_(__COUNTER__, function)
143 #define FAT_MAGIC 0xcafebabe
144 #define FAT_CIGAM 0xbebafeca
164 #define MH_MAGIC 0xfeedface
165 #define MH_CIGAM 0xcefaedfe
167 #define MH_MAGIC_64 0xfeedfacf
168 #define MH_CIGAM_64 0xcffaedfe
170 #define MH_DYLDLINK 0x4
172 #define MH_OBJECT 0x1
173 #define MH_EXECUTE 0x2
175 #define MH_BUNDLE 0x8
176 #define MH_DYLIB_STUB 0x9
178 struct load_command
{
183 #define LC_REQ_DYLD uint32_t(0x80000000)
185 #define LC_SEGMENT uint32_t(0x01)
186 #define LC_SYMTAB uint32_t(0x02)
187 #define LC_DYSYMTAB uint32_t(0x0b)
188 #define LC_LOAD_DYLIB uint32_t(0x0c)
189 #define LC_ID_DYLIB uint32_t(0x0d)
190 #define LC_SEGMENT_64 uint32_t(0x19)
191 #define LC_UUID uint32_t(0x1b)
192 #define LC_CODE_SIGNATURE uint32_t(0x1d)
193 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
194 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
195 #define LC_ENCRYPTION_INFO uint32_t(0x21)
196 #define LC_DYLD_INFO uint32_t(0x22)
197 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
198 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
203 uint32_t current_version
;
204 uint32_t compatibility_version
;
207 struct dylib_command
{
213 struct uuid_command
{
219 struct symtab_command
{
228 struct dyld_info_command
{
232 uint32_t rebase_size
;
235 uint32_t weak_bind_off
;
236 uint32_t weak_bind_size
;
237 uint32_t lazy_bind_off
;
238 uint32_t lazy_bind_size
;
240 uint32_t export_size
;
243 struct dysymtab_command
{
256 uint32_t extrefsymoff
;
257 uint32_t nextrefsyms
;
258 uint32_t indirectsymoff
;
259 uint32_t nindirectsyms
;
266 struct dylib_table_of_contents
{
267 uint32_t symbol_index
;
268 uint32_t module_index
;
271 struct dylib_module
{
272 uint32_t module_name
;
281 uint32_t iinit_iterm
;
282 uint32_t ninit_nterm
;
283 uint32_t objc_module_info_addr
;
284 uint32_t objc_module_info_size
;
287 struct dylib_reference
{
292 struct relocation_info
{
294 uint32_t r_symbolnum
:24;
313 struct segment_command
{
327 struct segment_command_64
{
369 struct linkedit_data_command
{
376 struct encryption_info_command
{
384 #define BIND_OPCODE_MASK 0xf0
385 #define BIND_IMMEDIATE_MASK 0x0f
386 #define BIND_OPCODE_DONE 0x00
387 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
388 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
389 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
390 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
391 #define BIND_OPCODE_SET_TYPE_IMM 0x50
392 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
393 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
394 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
395 #define BIND_OPCODE_DO_BIND 0x90
396 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
397 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
398 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
400 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
401 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
404 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
405 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
408 inline void pad(std::streambuf
&stream
, size_t size
) {
410 memset(padding
, 0, size
);
411 put(stream
, padding
, size
);
414 template <typename Type_
>
415 Type_
Align(Type_ value
, size_t align
) {
422 static const uint8_t PageShift_(0x0c);
423 static const uint32_t PageSize_(1 << PageShift_
);
425 static inline uint16_t Swap_(uint16_t value
) {
427 ((value
>> 8) & 0x00ff) |
428 ((value
<< 8) & 0xff00);
431 static inline uint32_t Swap_(uint32_t value
) {
432 value
= ((value
>> 8) & 0x00ff00ff) |
433 ((value
<< 8) & 0xff00ff00);
434 value
= ((value
>> 16) & 0x0000ffff) |
435 ((value
<< 16) & 0xffff0000);
439 static inline uint64_t Swap_(uint64_t value
) {
440 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
441 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
442 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
446 static inline int16_t Swap_(int16_t value
) {
447 return Swap_(static_cast<uint16_t>(value
));
450 static inline int32_t Swap_(int32_t value
) {
451 return Swap_(static_cast<uint32_t>(value
));
454 static inline int64_t Swap_(int64_t value
) {
455 return Swap_(static_cast<uint64_t>(value
));
458 static bool little_(true);
460 static inline uint16_t Swap(uint16_t value
) {
461 return little_
? Swap_(value
) : value
;
464 static inline uint32_t Swap(uint32_t value
) {
465 return little_
? Swap_(value
) : value
;
468 static inline uint64_t Swap(uint64_t value
) {
469 return little_
? Swap_(value
) : value
;
472 static inline int16_t Swap(int16_t value
) {
473 return Swap(static_cast<uint16_t>(value
));
476 static inline int32_t Swap(int32_t value
) {
477 return Swap(static_cast<uint32_t>(value
));
480 static inline int64_t Swap(int64_t value
) {
481 return Swap(static_cast<uint64_t>(value
));
484 template <typename Target_
>
497 Swapped(bool swapped
) :
502 template <typename Type_
>
503 Type_
Swap(Type_ value
) const {
504 return swapped_
? Swap_(value
) : value
;
516 Data(void *base
, size_t size
) :
522 void *GetBase() const {
526 size_t GetSize() const {
537 struct mach_header
*mach_header_
;
538 struct load_command
*load_command_
;
541 MachHeader(void *base
, size_t size
) :
544 mach_header_
= (mach_header
*) base
;
546 switch (Swap(mach_header_
->magic
)) {
548 swapped_
= !swapped_
;
554 swapped_
= !swapped_
;
563 void *post
= mach_header_
+ 1;
565 post
= (uint32_t *) post
+ 1;
566 load_command_
= (struct load_command
*) post
;
569 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
570 Swap(mach_header_
->filetype
) == MH_DYLIB
||
571 Swap(mach_header_
->filetype
) == MH_BUNDLE
575 bool Bits64() const {
579 struct mach_header
*operator ->() const {
583 operator struct mach_header
*() const {
587 uint32_t GetCPUType() const {
588 return Swap(mach_header_
->cputype
);
591 uint32_t GetCPUSubtype() const {
592 return Swap(mach_header_
->cpusubtype
) & 0xff;
595 struct load_command
*GetLoadCommand() const {
596 return load_command_
;
599 std::vector
<struct load_command
*> GetLoadCommands() const {
600 std::vector
<struct load_command
*> load_commands
;
602 struct load_command
*load_command
= load_command_
;
603 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
604 load_commands
.push_back(load_command
);
605 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
608 return load_commands
;
611 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
612 std::vector
<struct segment_command
*> segment_commands
;
614 _foreach (load_command
, GetLoadCommands()) {
615 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
616 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
617 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
618 segment_commands
.push_back(segment_command
);
622 return segment_commands
;
625 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
626 std::vector
<struct segment_command_64
*> segment_commands
;
628 _foreach (load_command
, GetLoadCommands()) {
629 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
630 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
631 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
632 segment_commands
.push_back(segment_command
);
636 return segment_commands
;
639 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
640 std::vector
<section
*> sections
;
642 _foreach (segment
, GetSegments(segment_name
)) {
643 section
*section
= (struct section
*) (segment
+ 1);
646 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
647 if (strncmp(section
->sectname
, section_name
, 16) == 0)
648 sections
.push_back(section
);
656 template <typename Target_
>
657 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
658 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
661 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
662 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
663 segment_command
*segment_command
= (struct segment_command
*) load_command
;
664 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
667 section
*sections
= (struct section
*) (segment_command
+ 1);
670 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
671 section
*section
= §ions
[sect
];
672 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
673 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
674 //printf("0x%.8x %s\n", address, segment_command->segname);
675 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
681 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
684 return Pointer
<Target_
>(this);
687 template <typename Target_
>
688 Pointer
<Target_
> GetOffset(uint32_t offset
) {
689 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
693 class FatMachHeader
:
700 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
701 MachHeader(base
, size
),
706 fat_arch
*GetFatArch() const {
715 fat_header
*fat_header_
;
716 std::vector
<FatMachHeader
> mach_headers_
;
719 FatHeader(void *base
, size_t size
) :
722 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
724 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
725 swapped_
= !swapped_
;
727 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
729 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
731 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
732 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
734 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
735 uint32_t arch_offset
= Swap(fat_arch
->offset
);
736 uint32_t arch_size
= Swap(fat_arch
->size
);
737 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
743 std::vector
<FatMachHeader
> &GetMachHeaders() {
744 return mach_headers_
;
748 return fat_header_
!= NULL
;
751 struct fat_header
*operator ->() const {
755 operator struct fat_header
*() const {
760 template <typename Target_
>
763 const MachHeader
*framework_
;
764 const Target_
*pointer_
;
767 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
768 framework_(framework
),
773 operator const Target_
*() const {
777 const Target_
*operator ->() const {
781 Pointer
<Target_
> &operator ++() {
786 template <typename Value_
>
787 Value_
Swap(Value_ value
) {
788 return framework_
->Swap(value
);
792 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
793 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
794 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
795 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
796 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
797 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
798 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
799 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
801 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
802 #define CSSLOT_INFOSLOT uint32_t(0x00001)
803 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
804 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
805 #define CSSLOT_APPLICATION uint32_t(0x00004)
806 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
808 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
810 #define CS_HASHTYPE_SHA1 1
825 struct BlobIndex index
[];
828 struct CodeDirectory
{
832 uint32_t identOffset
;
833 uint32_t nSpecialSlots
;
843 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
845 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
846 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
849 struct CodesignAllocation
{
850 FatMachHeader mach_header_
;
857 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
858 mach_header_(mach_header
),
880 _syscall(close(file_
));
883 void open(const char *path
, int flags
) {
884 _assert(file_
== -1);
885 file_
= _syscall(::open(path
, flags
));
902 _syscall(munmap(data_
, size_
));
914 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
917 open(path
, oflag
, pflag
, mflag
);
920 Map(const std::string
&path
, bool edit
) :
931 return data_
== NULL
;
934 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
937 file_
.open(path
.c_str(), oflag
);
938 int file(file_
.file());
941 _syscall(fstat(file
, &stat
));
942 size_
= stat
.st_size
;
944 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
947 void open(const std::string
&path
, bool edit
) {
949 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
951 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
958 size_t size() const {
962 operator std::string() const {
963 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 (size_t)> &allocate
, const Functor
<size_t (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(size
));
1007 auto *fat_arch(mach_header
.GetFatArch());
1008 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1009 offset
= Align(offset
, 1 << align
);
1011 uint32_t limit(size
);
1013 limit
= Align(limit
, 0x10);
1015 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1016 offset
+= size
+ alloc
;
1017 offset
= Align(offset
, 0x10);
1022 if (source
.IsFat()) {
1023 fat_header fat_header
;
1024 fat_header
.magic
= Swap(FAT_MAGIC
);
1025 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1026 put(output
, &fat_header
, sizeof(fat_header
));
1027 position
+= sizeof(fat_header
);
1029 _foreach (allocation
, allocations
) {
1030 auto &mach_header(allocation
.mach_header_
);
1033 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1034 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1035 fat_arch
.offset
= Swap(allocation
.offset_
);
1036 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1037 fat_arch
.align
= Swap(allocation
.align_
);
1038 put(output
, &fat_arch
, sizeof(fat_arch
));
1039 position
+= sizeof(fat_arch
);
1043 _foreach (allocation
, allocations
) {
1044 auto &mach_header(allocation
.mach_header_
);
1046 pad(output
, allocation
.offset_
- position
);
1047 position
= allocation
.offset_
;
1049 std::vector
<std::string
> commands
;
1051 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1052 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1054 switch (mach_header
.Swap(load_command
->cmd
)) {
1055 case LC_CODE_SIGNATURE
:
1060 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1061 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1063 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1064 segment_command
->filesize
= size
;
1065 segment_command
->vmsize
= Align(size
, PageSize_
);
1068 case LC_SEGMENT_64
: {
1069 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1070 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1072 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1073 segment_command
->filesize
= size
;
1074 segment_command
->vmsize
= Align(size
, PageSize_
);
1078 commands
.push_back(copy
);
1081 if (allocation
.alloc_
!= 0) {
1082 linkedit_data_command signature
;
1083 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1084 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1085 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1086 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1087 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1090 size_t begin(position
);
1093 _foreach(command
, commands
)
1094 after
+= command
.size();
1096 std::stringbuf altern
;
1098 struct mach_header
header(*mach_header
);
1099 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1100 header
.sizeofcmds
= mach_header
.Swap(after
);
1101 put(output
, &header
, sizeof(header
));
1102 put(altern
, &header
, sizeof(header
));
1103 position
+= sizeof(header
);
1105 if (mach_header
.Bits64()) {
1106 auto pad(mach_header
.Swap(uint32_t(0)));
1107 put(output
, &pad
, sizeof(pad
));
1108 put(altern
, &pad
, sizeof(pad
));
1109 position
+= sizeof(pad
);
1112 _foreach(command
, commands
) {
1113 put(output
, command
.data(), command
.size());
1114 put(altern
, command
.data(), command
.size());
1115 position
+= command
.size();
1118 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1119 if (before
> after
) {
1120 pad(output
, before
- after
);
1121 pad(altern
, before
- after
);
1122 position
+= before
- after
;
1125 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1127 std::string
overlap(altern
.str());
1128 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1130 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1131 position
= begin
+ allocation
.size_
;
1133 pad(output
, allocation
.limit_
- allocation
.size_
);
1134 position
+= allocation
.limit_
- allocation
.size_
;
1136 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1137 if (allocation
.alloc_
> saved
)
1138 pad(output
, allocation
.alloc_
- saved
);
1139 position
+= allocation
.alloc_
;
1145 typedef std::map
<uint32_t, std::string
> Blobs
;
1147 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1148 auto value(buffer
.str());
1149 std::swap(blobs
[slot
], value
);
1152 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1153 auto value(buffer
.str());
1155 blob
.magic
= Swap(magic
);
1156 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1157 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1158 std::swap(blobs
[slot
], value
);
1161 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1163 _foreach (blob
, blobs
)
1164 total
+= blob
.second
.size();
1166 struct SuperBlob super
;
1167 super
.blob
.magic
= Swap(magic
);
1168 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1169 super
.count
= Swap(uint32_t(blobs
.size()));
1170 put(output
, &super
, sizeof(super
));
1172 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1174 _foreach (blob
, blobs
) {
1176 index
.type
= Swap(blob
.first
);
1177 index
.offset
= Swap(uint32_t(offset
));
1178 put(output
, &index
, sizeof(index
));
1179 offset
+= blob
.second
.size();
1182 _foreach (blob
, blobs
)
1183 put(output
, blob
.second
.data(), blob
.second
.size());
1196 _assert(bio_
!= NULL
);
1200 bio_(BIO_new(BIO_s_mem()))
1204 Buffer(const char *data
, size_t size
) :
1205 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1209 Buffer(const std::string
&data
) :
1210 Buffer(data
.data(), data
.size())
1214 Buffer(PKCS7
*pkcs
) :
1217 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1224 operator BIO
*() const {
1228 explicit operator std::string() const {
1230 auto size(BIO_get_mem_data(bio_
, &data
));
1231 return std::string(data
, size
);
1240 STACK_OF(X509
) *ca_
;
1244 value_(d2i_PKCS12_bio(bio
, NULL
)),
1247 _assert(value_
!= NULL
);
1248 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1249 _assert(key_
!= NULL
);
1250 _assert(cert_
!= NULL
);
1253 Stuff(const std::string
&data
) :
1259 sk_X509_pop_free(ca_
, X509_free
);
1261 EVP_PKEY_free(key_
);
1262 PKCS12_free(value_
);
1265 operator PKCS12
*() const {
1269 operator EVP_PKEY
*() const {
1273 operator X509
*() const {
1277 operator STACK_OF(X509
) *() const {
1287 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1288 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1290 _assert(value_
!= NULL
);
1297 operator PKCS7
*() const {
1303 public std::streambuf
1306 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1310 virtual int_type
overflow(int_type next
) {
1316 public std::streambuf
1319 std::vector
<char> &hash_
;
1323 HashBuffer(std::vector
<char> &hash
) :
1326 SHA1_Init(&context_
);
1330 hash_
.resize(SHA_DIGEST_LENGTH
);
1331 SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1334 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1335 SHA1_Update(&context_
, data
, size
);
1339 virtual int_type
overflow(int_type next
) {
1340 if (next
== traits_type::eof())
1352 std::streambuf
&buffer_
;
1355 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1361 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1362 _assert(HashBuffer::xsputn(data
, size
) == size
);
1363 return buffer_
.sputn(data
, size
);
1367 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1368 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1376 Split(const std::string
&path
) {
1377 size_t slash(path
.rfind('/'));
1378 if (slash
== std::string::npos
)
1381 dir
= path
.substr(0, slash
+ 1);
1382 base
= path
.substr(slash
+ 1);
1387 static void mkdir_p(const std::string
&path
) {
1391 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1394 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1397 auto slash(path
.rfind('/', path
.size() - 1));
1398 if (slash
== std::string::npos
)
1400 mkdir_p(path
.substr(0, slash
));
1403 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1404 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1406 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1410 static void Commit(const std::string
&path
, const std::string
&temp
) {
1412 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1414 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1416 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1419 _syscall(rename(temp
.c_str(), path
.c_str()));
1424 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
) {
1425 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1426 size_t alloc(sizeof(struct SuperBlob
));
1428 uint32_t special(0);
1430 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1431 alloc
+= sizeof(struct BlobIndex
);
1434 if (!entitlements
.empty()) {
1435 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1436 alloc
+= sizeof(struct BlobIndex
);
1437 alloc
+= sizeof(struct Blob
);
1438 alloc
+= entitlements
.size();
1441 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1442 alloc
+= sizeof(struct BlobIndex
);
1443 alloc
+= sizeof(struct Blob
);
1444 alloc
+= sizeof(struct CodeDirectory
);
1445 alloc
+= identifier
.size() + 1;
1448 alloc
+= sizeof(struct BlobIndex
);
1449 alloc
+= sizeof(struct Blob
);
1450 // XXX: this is just a "sufficiently large number"
1454 _foreach (slot
, slots
)
1455 special
= std::max(special
, slot
.first
);
1457 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1458 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1460 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1464 std::stringbuf data
;
1467 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1469 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1472 if (!entitlements
.empty()) {
1473 std::stringbuf data
;
1474 put(data
, entitlements
.data(), entitlements
.size());
1475 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1479 std::stringbuf data
;
1481 uint32_t special(0);
1482 _foreach (blob
, blobs
)
1483 special
= std::max(special
, blob
.first
);
1484 _foreach (slot
, slots
)
1485 special
= std::max(special
, slot
.first
);
1486 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1488 CodeDirectory directory
;
1489 directory
.version
= Swap(uint32_t(0x00020001));
1490 directory
.flags
= Swap(uint32_t(0));
1491 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + identifier
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1492 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1493 directory
.nSpecialSlots
= Swap(special
);
1494 directory
.codeLimit
= Swap(uint32_t(limit
));
1495 directory
.nCodeSlots
= Swap(normal
);
1496 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1497 directory
.hashType
= CS_HASHTYPE_SHA1
;
1498 directory
.spare1
= 0x00;
1499 directory
.pageSize
= PageShift_
;
1500 directory
.spare2
= Swap(uint32_t(0));
1501 put(data
, &directory
, sizeof(directory
));
1503 put(data
, identifier
.c_str(), identifier
.size() + 1);
1505 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1506 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1508 memset(storage
, 0, sizeof(*storage
) * special
);
1510 _foreach (blob
, blobs
) {
1511 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1512 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1515 _foreach (slot
, slots
) {
1516 _assert(sizeof(*hashes
) == slot
.second
.size());
1517 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1521 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1522 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1524 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1526 put(data
, storage
, sizeof(storage
));
1528 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1532 std::stringbuf data
;
1533 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1538 Signature
signature(stuff
, sign
);
1539 Buffer
result(signature
);
1540 std::string
value(result
);
1541 put(data
, value
.data(), value
.size());
1543 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1546 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1550 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1551 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1553 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1558 std::string
DiskFolder::Path(const std::string
&path
) {
1559 return path_
+ "/" + path
;
1562 DiskFolder::DiskFolder(const std::string
&path
) :
1567 DiskFolder::~DiskFolder() {
1568 if (!std::uncaught_exception())
1569 for (const auto &commit
: commit_
)
1570 Commit(commit
.first
, commit
.second
);
1573 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
) {
1574 std::string
path(Path(root
) + base
);
1576 DIR *dir(opendir(path
.c_str()));
1577 _assert(dir
!= NULL
);
1578 _scope({ _syscall(closedir(dir
)); });
1580 while (auto child
= readdir(dir
)) {
1581 std::string
name(child
->d_name
);
1582 if (name
== "." || name
== "..")
1584 if (Starts(name
, ".ldid."))
1591 _syscall(stat(path
.c_str(), &info
));
1593 else if (S_ISDIR(info
.st_mode
))
1595 else if (S_ISREG(info
.st_mode
))
1598 _assert_(false, "st_mode=%x", info
.st_mode
);
1600 switch (child
->d_type
) {
1608 _assert_(false, "d_type=%u", child
->d_type
);
1613 Find(root
, base
+ name
+ "/", code
);
1615 code(base
+ name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1616 std::string
access(root
+ base
+ name
);
1617 _assert_(Open(access
, fun([&](std::streambuf
&data
) {
1620 })), "open(): %s", access
.c_str());
1625 void DiskFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1627 auto from(Path(path
));
1628 commit_
[from
] = Temporary(save
, from
);
1632 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1634 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1637 _assert(result
== &data
);
1642 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1643 Find(path
, "", code
);
1646 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1652 void SubFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1653 return parent_
.Save(path_
+ path
, code
);
1656 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1657 return parent_
.Open(path_
+ path
, code
);
1660 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1661 return parent_
.Find(path_
+ path
, code
);
1664 UnionFolder::UnionFolder(Folder
&parent
) :
1669 void UnionFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1670 return parent_
.Save(path
, code
);
1673 bool UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1674 auto file(files_
.find(path
));
1675 if (file
== files_
.end())
1676 return parent_
.Open(path
, code
);
1678 auto &data(file
->second
);
1679 data
.pubseekpos(0, std::ios::in
);
1684 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1685 parent_
.Find(path
, fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &save
) {
1686 if (files_
.find(name
) == files_
.end())
1690 for (auto &file
: files_
)
1691 code(file
.first
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1692 parent_
.Save(file
.first
, fun([&](std::streambuf
&save
) {
1693 file
.second
.pubseekpos(0, std::ios::in
);
1694 code(file
.second
, save
);
1699 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1703 size_t writ(source
.sgetn(data
, sizeof(data
)));
1706 _assert(target
.sputn(data
, writ
) == writ
);
1712 static plist_t
plist(const std::string
&data
) {
1713 plist_t
plist(NULL
);
1714 if (Starts(data
, "bplist00"))
1715 plist_from_bin(data
.data(), data
.size(), &plist
);
1717 plist_from_xml(data
.data(), data
.size(), &plist
);
1718 _assert(plist
!= NULL
);
1722 static void plist_d(std::streambuf
&buffer
, const Functor
<void (plist_t
)> &code
) {
1723 std::stringbuf data
;
1725 auto node(plist(data
.str()));
1726 _scope({ plist_free(node
); });
1727 _assert(plist_get_node_type(node
) == PLIST_DICT
);
1731 static std::string
plist_s(plist_t node
) {
1732 _assert(node
!= NULL
);
1733 _assert(plist_get_node_type(node
) == PLIST_STRING
);
1735 plist_get_string_val(node
, &data
);
1736 _scope({ free(data
); });
1753 Expression(const std::string
&code
) {
1754 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1761 bool operator ()(const std::string
&data
) const {
1762 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1763 if (value
== REG_NOMATCH
)
1765 _assert_(value
== 0, "regexec()");
1775 mutable std::auto_ptr
<Expression
> regex_
;
1777 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1784 Rule(const Rule
&rhs
) :
1785 weight_(rhs
.weight_
),
1791 void Compile() const {
1792 regex_
.reset(new Expression(code_
));
1795 bool operator ()(const std::string
&data
) const {
1796 _assert(regex_
.get() != NULL
);
1797 return (*regex_
)(data
);
1800 bool operator <(const Rule
&rhs
) const {
1801 if (weight_
> rhs
.weight_
)
1803 if (weight_
< rhs
.weight_
)
1805 return mode_
> rhs
.mode_
;
1810 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1811 return lhs
->code_
< rhs
->code_
;
1815 std::string
Bundle(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, std::vector
<char>> &remote
) {
1816 std::string executable
;
1817 std::string identifier
;
1819 static const std::string
info("Info.plist");
1821 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
) {
1822 plist_d(buffer
, fun([&](plist_t node
) {
1823 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
1824 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
1826 })), "open(): Info.plist");
1828 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1830 auto &rules1(versions
[""]);
1831 auto &rules2(versions
["2"]);
1833 static const std::string
signature("_CodeSignature/CodeResources");
1835 folder
.Open(signature
, fun([&](std::streambuf
&buffer
) {
1836 plist_d(buffer
, fun([&](plist_t node
) {
1837 // XXX: maybe attempt to preserve existing rules
1842 rules1
.insert(Rule
{1, NoMode
, "^"});
1843 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1844 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1845 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1846 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1847 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1851 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1852 rules2
.insert(Rule
{20, NoMode
, "^"});
1853 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1854 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1855 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1856 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1857 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1858 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1859 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1860 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1861 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1862 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1863 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1864 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1867 std::map
<std::string
, std::vector
<char>> local
;
1869 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1871 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1874 auto bundle(root
+ Split(name
).dir
);
1875 SubFolder
subfolder(folder
, bundle
);
1876 Bundle(bundle
, subfolder
, key
, local
);
1879 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1880 if (name
== executable
|| name
== signature
)
1883 auto &hash(local
[name
]);
1887 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1888 HashProxy
proxy(hash
, save
);
1892 _assert(hash
.size() == SHA_DIGEST_LENGTH
);
1895 auto plist(plist_new_dict());
1896 _scope({ plist_free(plist
); });
1898 for (const auto &version
: versions
) {
1899 auto files(plist_new_dict());
1900 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
1902 for (const auto &rule
: version
.second
)
1905 for (const auto &hash
: local
)
1906 for (const auto &rule
: version
.second
)
1907 if (rule(hash
.first
)) {
1908 if (rule
.mode_
== NoMode
)
1909 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(hash
.second
.data(), hash
.second
.size()));
1910 else if (rule
.mode_
== OptionalMode
) {
1911 auto entry(plist_new_dict());
1912 plist_dict_set_item(entry
, "hash", plist_new_data(hash
.second
.data(), hash
.second
.size()));
1913 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1914 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
1921 for (const auto &version
: versions
) {
1922 auto rules(plist_new_dict());
1923 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
1925 std::multiset
<const Rule
*, RuleCode
> ordered
;
1926 for (const auto &rule
: version
.second
)
1927 ordered
.insert(&rule
);
1929 for (const auto &rule
: ordered
)
1930 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
1931 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
1933 auto entry(plist_new_dict());
1934 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
1936 switch (rule
->mode_
) {
1940 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
1943 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
1946 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
1949 plist_dict_set_item(entry
, "top", plist_new_bool(true));
1953 if (rule
->weight_
>= 10000)
1954 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
1955 else if (rule
->weight_
!= 1)
1956 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
1960 folder
.Save(signature
, fun([&](std::streambuf
&save
) {
1961 HashProxy
proxy(local
[signature
], save
);
1964 plist_to_xml(plist
, &xml
, &size
);
1965 _scope({ free(xml
); });
1966 put(proxy
, xml
, size
);
1969 folder
.Open(executable
, fun([&](std::streambuf
&buffer
) {
1970 // XXX: this is a miserable fail
1971 std::stringbuf temp
;
1973 auto data(temp
.str());
1975 folder
.Save(executable
, fun([&](std::streambuf
&save
) {
1977 slots
[1] = local
.at(info
);
1978 slots
[3] = local
.at(signature
);
1980 HashProxy
proxy(local
[executable
], save
);
1981 Sign(data
.data(), data
.size(), proxy
, identifier
, "", key
, slots
);
1985 for (const auto &hash
: local
)
1986 remote
[root
+ hash
.first
] = hash
.second
;
1993 int main(int argc
, char *argv
[]) {
1994 OpenSSL_add_all_algorithms();
2001 little_
= endian
.byte
[0];
2016 uint32_t flag_CPUType(_not(uint32_t));
2017 uint32_t flag_CPUSubtype(_not(uint32_t));
2019 const char *flag_I(NULL
);
2028 std::vector
<std::string
> files
;
2031 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2032 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2033 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2034 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2038 for (int argi(1); argi
!= argc
; ++argi
)
2039 if (argv
[argi
][0] != '-')
2040 files
.push_back(argv
[argi
]);
2041 else switch (argv
[argi
][1]) {
2048 case 'e': flag_e
= true; break;
2051 const char *slot
= argv
[argi
] + 2;
2052 const char *colon
= strchr(slot
, ':');
2053 _assert(colon
!= NULL
);
2054 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2056 unsigned number(strtoul(slot
, &arge
, 0));
2057 _assert(arge
== colon
);
2058 std::vector
<char> &hash(slots
[number
]);
2059 hash
.resize(SHA_DIGEST_LENGTH
);
2060 sha1(reinterpret_cast<uint8_t *>(hash
.data()), file
.data(), file
.size());
2063 case 'D': flag_D
= true; break;
2065 case 'a': flag_a
= true; break;
2070 if (argv
[argi
][2] != '\0') {
2071 const char *cpu
= argv
[argi
] + 2;
2072 const char *colon
= strchr(cpu
, ':');
2073 _assert(colon
!= NULL
);
2075 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2076 _assert(arge
== colon
);
2077 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2078 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2092 if (argv
[argi
][2] != '\0') {
2093 const char *xml
= argv
[argi
] + 2;
2094 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2099 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2104 if (argv
[argi
][2] == '-')
2108 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2109 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2114 flag_I
= argv
[argi
] + 2;
2122 _assert(flag_S
|| key
.empty());
2123 _assert(flag_S
|| flag_I
== NULL
);
2125 if (files
.empty()) usage
: {
2129 size_t filei(0), filee(0);
2130 _foreach (file
, files
) try {
2131 std::string
path(file
);
2134 _syscall(stat(path
.c_str(), &info
));
2136 if (S_ISDIR(info
.st_mode
)) {
2138 ldid::DiskFolder
folder(path
);
2139 std::map
<std::string
, std::vector
<char>> hashes
;
2140 path
+= "/" + Bundle("", folder
, key
, hashes
);
2141 } else if (flag_S
|| flag_r
) {
2142 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2144 std::filebuf output
;
2146 auto temp(Temporary(output
, split
));
2149 ldid::Unsign(input
.data(), input
.size(), output
);
2151 std::string
identifier(flag_I
?: split
.base
.c_str());
2152 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2158 Map
mapping(path
, flag_T
|| flag_s
);
2159 FatHeader
fat_header(mapping
.data(), mapping
.size());
2161 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2162 struct linkedit_data_command
*signature(NULL
);
2163 struct encryption_info_command
*encryption(NULL
);
2166 if (mach_header
.GetCPUType() != flag_CPUType
)
2168 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2173 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2175 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2176 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2179 else if (cmd
== LC_CODE_SIGNATURE
)
2180 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2181 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2182 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2183 else if (cmd
== LC_ID_DYLIB
) {
2184 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2192 dylib_command
->dylib
.timestamp
= 0;
2193 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2196 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2202 _assert(encryption
!= NULL
);
2203 encryption
->cryptid
= mach_header
.Swap(0);
2207 _assert(signature
!= NULL
);
2209 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2211 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2212 uint8_t *blob
= top
+ data
;
2213 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2215 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2216 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2217 uint32_t begin
= Swap(super
->index
[index
].offset
);
2218 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2219 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2224 _assert(signature
!= NULL
);
2226 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2228 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2229 uint8_t *blob
= top
+ data
;
2230 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2232 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2233 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2234 uint32_t begin
= Swap(super
->index
[index
].offset
);
2235 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2237 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2238 uint32_t pages
= Swap(directory
->nCodeSlots
);
2241 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2242 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2244 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2250 } catch (const char *) {