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>
55 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56 #define LDID_SHA1 CC_SHA1
57 #define LDID_SHA1_CTX CC_SHA1_CTX
58 #define LDID_SHA1_Init CC_SHA1_Init
59 #define LDID_SHA1_Update CC_SHA1_Update
60 #define LDID_SHA1_Final CC_SHA1_Final
62 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63 #define LDID_SHA256 CC_SHA256
64 #define LDID_SHA256_CTX CC_SHA256_CTX
65 #define LDID_SHA256_Init CC_SHA256_Init
66 #define LDID_SHA256_Update CC_SHA256_Update
67 #define LDID_SHA256_Final CC_SHA256_Final
69 #include <openssl/sha.h>
71 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72 #define LDID_SHA1 SHA1
73 #define LDID_SHA1_CTX SHA_CTX
74 #define LDID_SHA1_Init SHA1_Init
75 #define LDID_SHA1_Update SHA1_Update
76 #define LDID_SHA1_Final SHA1_Final
78 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79 #define LDID_SHA256 SHA256
80 #define LDID_SHA256_CTX SHA256_CTX
81 #define LDID_SHA256_Init SHA256_Init
82 #define LDID_SHA256_Update SHA256_Update
83 #define LDID_SHA256_Final SHA256_Final
87 #include <plist/plist.h>
92 #define _assert___(line) \
94 #define _assert__(line) \
98 #define _assert_(expr, format, ...) \
100 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
101 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
104 // XXX: this is not acceptable
105 #define _assert_(expr, format, ...) \
107 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
112 #define _assert(expr) \
113 _assert_(expr, "%s", #expr)
115 #define _syscall(expr, ...) [&] { for (;;) { \
117 if ((long) _value != -1) \
120 if (error == EINTR) \
122 /* XXX: EINTR is included in this list to fix g++ */ \
123 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
124 if (error == success) \
125 return (decltype(expr)) -success; \
126 _assert_(false, "errno=%u", error); \
130 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
136 __attribute__((packed))
138 template <typename Type_
>
140 typedef typename
Type_::const_iterator Result
;
143 #define _foreach(item, list) \
144 for (bool _stop(true); _stop; ) \
145 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
146 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
147 for (bool _suck(true); _suck; _suck = false) \
148 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
153 template <typename Function_
>
161 Scope(const Function_
&function
) :
171 template <typename Function_
>
172 Scope
<Function_
> _scope(const Function_
&function
) {
173 return Scope
<Function_
>(function
);
176 #define _scope__(counter, function) \
177 __attribute__((__unused__)) \
178 const _Scope &_scope ## counter(_scope([&]function))
179 #define _scope_(counter, function) \
180 _scope__(counter, function)
181 #define _scope(function) \
182 _scope_(__COUNTER__, function)
184 #define CPU_ARCH_MASK uint32_t(0xff000000)
185 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
187 #define CPU_TYPE_ANY uint32_t(-1)
188 #define CPU_TYPE_VAX uint32_t( 1)
189 #define CPU_TYPE_MC680x0 uint32_t( 6)
190 #define CPU_TYPE_X86 uint32_t( 7)
191 #define CPU_TYPE_MC98000 uint32_t(10)
192 #define CPU_TYPE_HPPA uint32_t(11)
193 #define CPU_TYPE_ARM uint32_t(12)
194 #define CPU_TYPE_MC88000 uint32_t(13)
195 #define CPU_TYPE_SPARC uint32_t(14)
196 #define CPU_TYPE_I860 uint32_t(15)
197 #define CPU_TYPE_POWERPC uint32_t(18)
199 #define CPU_TYPE_I386 CPU_TYPE_X86
201 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
202 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
203 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
210 #define FAT_MAGIC 0xcafebabe
211 #define FAT_CIGAM 0xbebafeca
231 #define MH_MAGIC 0xfeedface
232 #define MH_CIGAM 0xcefaedfe
234 #define MH_MAGIC_64 0xfeedfacf
235 #define MH_CIGAM_64 0xcffaedfe
237 #define MH_DYLDLINK 0x4
239 #define MH_OBJECT 0x1
240 #define MH_EXECUTE 0x2
242 #define MH_BUNDLE 0x8
243 #define MH_DYLIB_STUB 0x9
245 struct load_command
{
250 #define LC_REQ_DYLD uint32_t(0x80000000)
252 #define LC_SEGMENT uint32_t(0x01)
253 #define LC_SYMTAB uint32_t(0x02)
254 #define LC_DYSYMTAB uint32_t(0x0b)
255 #define LC_LOAD_DYLIB uint32_t(0x0c)
256 #define LC_ID_DYLIB uint32_t(0x0d)
257 #define LC_SEGMENT_64 uint32_t(0x19)
258 #define LC_UUID uint32_t(0x1b)
259 #define LC_CODE_SIGNATURE uint32_t(0x1d)
260 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
261 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
262 #define LC_ENCRYPTION_INFO uint32_t(0x21)
263 #define LC_DYLD_INFO uint32_t(0x22)
264 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
265 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
280 uint32_t current_version
;
281 uint32_t compatibility_version
;
284 struct dylib_command
{
290 struct uuid_command
{
296 struct symtab_command
{
305 struct dyld_info_command
{
309 uint32_t rebase_size
;
312 uint32_t weak_bind_off
;
313 uint32_t weak_bind_size
;
314 uint32_t lazy_bind_off
;
315 uint32_t lazy_bind_size
;
317 uint32_t export_size
;
320 struct dysymtab_command
{
333 uint32_t extrefsymoff
;
334 uint32_t nextrefsyms
;
335 uint32_t indirectsymoff
;
336 uint32_t nindirectsyms
;
343 struct dylib_table_of_contents
{
344 uint32_t symbol_index
;
345 uint32_t module_index
;
348 struct dylib_module
{
349 uint32_t module_name
;
358 uint32_t iinit_iterm
;
359 uint32_t ninit_nterm
;
360 uint32_t objc_module_info_addr
;
361 uint32_t objc_module_info_size
;
364 struct dylib_reference
{
369 struct relocation_info
{
371 uint32_t r_symbolnum
:24;
390 struct segment_command
{
404 struct segment_command_64
{
447 struct linkedit_data_command
{
454 struct encryption_info_command
{
462 #define BIND_OPCODE_MASK 0xf0
463 #define BIND_IMMEDIATE_MASK 0x0f
464 #define BIND_OPCODE_DONE 0x00
465 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
466 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
467 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
468 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
469 #define BIND_OPCODE_SET_TYPE_IMM 0x50
470 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
471 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
472 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
473 #define BIND_OPCODE_DO_BIND 0x90
474 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
475 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
476 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
478 static auto dummy([](double) {});
480 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
481 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
486 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
487 _assert(read(stream
, data
, size
) == size
);
490 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
491 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
494 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Functor
<void (double)> &percent
) {
496 for (size_t total(0); total
!= size
;) {
497 auto writ(std::min(size
- total
, size_t(4096 * 4)));
498 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
500 percent(double(total
) / size
);
504 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
507 if (auto writ
= read(stream
, data
, size
))
513 static inline void pad(std::streambuf
&stream
, size_t size
) {
515 memset(padding
, 0, size
);
516 put(stream
, padding
, size
);
519 template <typename Type_
>
520 Type_
Align(Type_ value
, size_t align
) {
527 static const uint8_t PageShift_(0x0c);
528 static const uint32_t PageSize_(1 << PageShift_
);
530 static inline uint16_t Swap_(uint16_t value
) {
532 ((value
>> 8) & 0x00ff) |
533 ((value
<< 8) & 0xff00);
536 static inline uint32_t Swap_(uint32_t value
) {
537 value
= ((value
>> 8) & 0x00ff00ff) |
538 ((value
<< 8) & 0xff00ff00);
539 value
= ((value
>> 16) & 0x0000ffff) |
540 ((value
<< 16) & 0xffff0000);
544 static inline uint64_t Swap_(uint64_t value
) {
545 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
546 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
547 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
551 static inline int16_t Swap_(int16_t value
) {
552 return Swap_(static_cast<uint16_t>(value
));
555 static inline int32_t Swap_(int32_t value
) {
556 return Swap_(static_cast<uint32_t>(value
));
559 static inline int64_t Swap_(int64_t value
) {
560 return Swap_(static_cast<uint64_t>(value
));
563 static bool little_(true);
565 static inline uint16_t Swap(uint16_t value
) {
566 return little_
? Swap_(value
) : value
;
569 static inline uint32_t Swap(uint32_t value
) {
570 return little_
? Swap_(value
) : value
;
573 static inline uint64_t Swap(uint64_t value
) {
574 return little_
? Swap_(value
) : value
;
577 static inline int16_t Swap(int16_t value
) {
578 return Swap(static_cast<uint16_t>(value
));
581 static inline int32_t Swap(int32_t value
) {
582 return Swap(static_cast<uint32_t>(value
));
585 static inline int64_t Swap(int64_t value
) {
586 return Swap(static_cast<uint64_t>(value
));
599 Swapped(bool swapped
) :
604 template <typename Type_
>
605 Type_
Swap(Type_ value
) const {
606 return swapped_
? Swap_(value
) : value
;
618 Data(void *base
, size_t size
) :
624 void *GetBase() const {
628 size_t GetSize() const {
639 struct mach_header
*mach_header_
;
640 struct load_command
*load_command_
;
643 MachHeader(void *base
, size_t size
) :
646 mach_header_
= (mach_header
*) base
;
648 switch (Swap(mach_header_
->magic
)) {
650 swapped_
= !swapped_
;
656 swapped_
= !swapped_
;
665 void *post
= mach_header_
+ 1;
667 post
= (uint32_t *) post
+ 1;
668 load_command_
= (struct load_command
*) post
;
671 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
672 Swap(mach_header_
->filetype
) == MH_DYLIB
||
673 Swap(mach_header_
->filetype
) == MH_BUNDLE
677 bool Bits64() const {
681 struct mach_header
*operator ->() const {
685 operator struct mach_header
*() const {
689 uint32_t GetCPUType() const {
690 return Swap(mach_header_
->cputype
);
693 uint32_t GetCPUSubtype() const {
694 return Swap(mach_header_
->cpusubtype
) & 0xff;
697 struct load_command
*GetLoadCommand() const {
698 return load_command_
;
701 std::vector
<struct load_command
*> GetLoadCommands() const {
702 std::vector
<struct load_command
*> load_commands
;
704 struct load_command
*load_command
= load_command_
;
705 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
706 load_commands
.push_back(load_command
);
707 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
710 return load_commands
;
713 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
714 _foreach (load_command
, GetLoadCommands())
715 switch (Swap(load_command
->cmd
)) {
717 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
718 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
719 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
720 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
721 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
724 case LC_SEGMENT_64
: {
725 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
726 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
727 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
728 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
729 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
734 template <typename Target_
>
735 Target_
*GetOffset(uint32_t offset
) const {
736 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
740 class FatMachHeader
:
747 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
748 MachHeader(base
, size
),
753 fat_arch
*GetFatArch() const {
762 fat_header
*fat_header_
;
763 std::vector
<FatMachHeader
> mach_headers_
;
766 FatHeader(void *base
, size_t size
) :
769 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
771 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
772 swapped_
= !swapped_
;
774 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
776 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
778 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
779 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
781 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
782 uint32_t arch_offset
= Swap(fat_arch
->offset
);
783 uint32_t arch_size
= Swap(fat_arch
->size
);
784 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
790 std::vector
<FatMachHeader
> &GetMachHeaders() {
791 return mach_headers_
;
795 return fat_header_
!= NULL
;
798 struct fat_header
*operator ->() const {
802 operator struct fat_header
*() const {
807 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
808 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
809 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
810 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
811 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
812 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
813 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
814 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
816 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
817 #define CSSLOT_INFOSLOT uint32_t(0x00001)
818 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
819 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
820 #define CSSLOT_APPLICATION uint32_t(0x00004)
821 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
822 #define CSSLOT_ALTERNATE uint32_t(0x01000)
824 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
826 #define CS_HASHTYPE_SHA160_160 1
827 #define CS_HASHTYPE_SHA256_256 2
828 #define CS_HASHTYPE_SHA256_160 3
829 #define CS_HASHTYPE_SHA386_386 4
844 struct BlobIndex index
[];
847 struct CodeDirectory
{
851 uint32_t identOffset
;
852 uint32_t nSpecialSlots
;
860 uint32_t scatterOffset
;
861 uint32_t teamIDOffset
;
863 uint64_t codeLimit64
;
867 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
874 Algorithm(size_t size
, uint8_t type
) :
880 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
882 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
883 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
884 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
887 struct AlgorithmSHA1
:
891 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
895 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
899 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
900 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
903 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
904 return operator()(hash
.sha1_
, data
, size
);
907 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
908 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
909 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
913 struct AlgorithmSHA256
:
917 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
921 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
925 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
926 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
929 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
930 return operator()(hash
.sha256_
, data
, size
);
933 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
934 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
935 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
939 static const std::vector
<Algorithm
*> &GetAlgorithms() {
940 static AlgorithmSHA1 sha1
;
941 static AlgorithmSHA256 sha256
;
943 static Algorithm
*array
[] = {
948 static std::vector
<Algorithm
*> algorithms(array
, array
+ sizeof(array
) / sizeof(array
[0]));
952 struct CodesignAllocation
{
953 FatMachHeader mach_header_
;
960 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
961 mach_header_(mach_header
),
984 _syscall(close(file_
));
987 void open(const char *path
, int flags
) {
988 _assert(file_
== -1);
989 file_
= _syscall(::open(path
, flags
));
1006 _syscall(munmap(data_
, size_
));
1018 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1021 open(path
, oflag
, pflag
, mflag
);
1024 Map(const std::string
&path
, bool edit
) :
1034 bool empty() const {
1035 return data_
== NULL
;
1038 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1041 file_
.open(path
.c_str(), oflag
);
1042 int file(file_
.file());
1045 _syscall(fstat(file
, &stat
));
1046 size_
= stat
.st_size
;
1048 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1051 void open(const std::string
&path
, bool edit
) {
1053 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1055 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1058 void *data() const {
1062 size_t size() const {
1066 operator std::string() const {
1067 return std::string(static_cast<char *>(data_
), size_
);
1074 std::string
Analyze(const void *data
, size_t size
) {
1075 std::string entitlements
;
1077 FatHeader
fat_header(const_cast<void *>(data
), size
);
1078 _foreach (mach_header
, fat_header
.GetMachHeaders())
1079 _foreach (load_command
, mach_header
.GetLoadCommands())
1080 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1081 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1082 auto offset(mach_header
.Swap(signature
->dataoff
));
1083 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1084 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1086 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1087 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1088 auto begin(Swap(super
->index
[index
].offset
));
1089 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1090 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1092 if (entitlements
.empty())
1093 entitlements
.assign(reinterpret_cast<char *>(blob
+ 1), writ
);
1095 _assert(entitlements
.compare(0, entitlements
.size(), reinterpret_cast<char *>(blob
+ 1), writ
) == 0);
1099 return entitlements
;
1102 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, std::streambuf
&output
, size_t, const std::string
&, const char *, const Functor
<void (double)> &)> &save
, const Functor
<void (double)> &percent
) {
1103 FatHeader
source(const_cast<void *>(idata
), isize
);
1107 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1109 std::vector
<CodesignAllocation
> allocations
;
1110 _foreach (mach_header
, source
.GetMachHeaders()) {
1111 struct linkedit_data_command
*signature(NULL
);
1112 struct symtab_command
*symtab(NULL
);
1114 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1115 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1117 else if (cmd
== LC_CODE_SIGNATURE
)
1118 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1119 else if (cmd
== LC_SYMTAB
)
1120 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1124 if (signature
== NULL
)
1125 size
= mach_header
.GetSize();
1127 size
= mach_header
.Swap(signature
->dataoff
);
1128 _assert(size
<= mach_header
.GetSize());
1131 if (symtab
!= NULL
) {
1132 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1133 _assert(end
<= size
);
1134 _assert(end
>= size
- 0x10);
1138 size_t alloc(allocate(mach_header
, size
));
1140 auto *fat_arch(mach_header
.GetFatArch());
1143 if (fat_arch
!= NULL
)
1144 align
= source
.Swap(fat_arch
->align
);
1145 else switch (mach_header
.GetCPUType()) {
1146 case CPU_TYPE_POWERPC
:
1147 case CPU_TYPE_POWERPC64
:
1149 case CPU_TYPE_X86_64
:
1153 case CPU_TYPE_ARM64
:
1161 offset
= Align(offset
, 1 << align
);
1163 uint32_t limit(size
);
1165 limit
= Align(limit
, 0x10);
1167 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1168 offset
+= size
+ alloc
;
1169 offset
= Align(offset
, 0x10);
1174 if (source
.IsFat()) {
1175 fat_header fat_header
;
1176 fat_header
.magic
= Swap(FAT_MAGIC
);
1177 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1178 put(output
, &fat_header
, sizeof(fat_header
));
1179 position
+= sizeof(fat_header
);
1181 _foreach (allocation
, allocations
) {
1182 auto &mach_header(allocation
.mach_header_
);
1185 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1186 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1187 fat_arch
.offset
= Swap(allocation
.offset_
);
1188 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1189 fat_arch
.align
= Swap(allocation
.align_
);
1190 put(output
, &fat_arch
, sizeof(fat_arch
));
1191 position
+= sizeof(fat_arch
);
1195 _foreach (allocation
, allocations
) {
1196 auto &mach_header(allocation
.mach_header_
);
1198 pad(output
, allocation
.offset_
- position
);
1199 position
= allocation
.offset_
;
1201 std::vector
<std::string
> commands
;
1203 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1204 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1206 switch (mach_header
.Swap(load_command
->cmd
)) {
1207 case LC_CODE_SIGNATURE
:
1212 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1213 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1215 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1216 segment_command
->filesize
= size
;
1217 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1220 case LC_SEGMENT_64
: {
1221 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1222 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1224 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1225 segment_command
->filesize
= size
;
1226 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1230 commands
.push_back(copy
);
1233 if (allocation
.alloc_
!= 0) {
1234 linkedit_data_command signature
;
1235 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1236 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1237 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1238 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1239 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1242 size_t begin(position
);
1245 _foreach(command
, commands
)
1246 after
+= command
.size();
1248 std::stringbuf altern
;
1250 struct mach_header
header(*mach_header
);
1251 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1252 header
.sizeofcmds
= mach_header
.Swap(after
);
1253 put(output
, &header
, sizeof(header
));
1254 put(altern
, &header
, sizeof(header
));
1255 position
+= sizeof(header
);
1257 if (mach_header
.Bits64()) {
1258 auto pad(mach_header
.Swap(uint32_t(0)));
1259 put(output
, &pad
, sizeof(pad
));
1260 put(altern
, &pad
, sizeof(pad
));
1261 position
+= sizeof(pad
);
1264 _foreach(command
, commands
) {
1265 put(output
, command
.data(), command
.size());
1266 put(altern
, command
.data(), command
.size());
1267 position
+= command
.size();
1270 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1271 if (before
> after
) {
1272 pad(output
, before
- after
);
1273 pad(altern
, before
- after
);
1274 position
+= before
- after
;
1277 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1279 std::string
overlap(altern
.str());
1280 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1282 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), percent
);
1283 position
= begin
+ allocation
.size_
;
1285 pad(output
, allocation
.limit_
- allocation
.size_
);
1286 position
+= allocation
.limit_
- allocation
.size_
;
1288 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
, percent
));
1289 if (allocation
.alloc_
> saved
)
1290 pad(output
, allocation
.alloc_
- saved
);
1292 _assert(allocation
.alloc_
== saved
);
1293 position
+= allocation
.alloc_
;
1299 typedef std::map
<uint32_t, std::string
> Blobs
;
1301 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1302 auto value(buffer
.str());
1303 std::swap(blobs
[slot
], value
);
1306 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1307 auto value(buffer
.str());
1309 blob
.magic
= Swap(magic
);
1310 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1311 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1312 auto &save(blobs
[slot
]);
1313 std::swap(save
, value
);
1317 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1319 _foreach (blob
, blobs
)
1320 total
+= blob
.second
.size();
1322 struct SuperBlob super
;
1323 super
.blob
.magic
= Swap(magic
);
1324 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1325 super
.count
= Swap(uint32_t(blobs
.size()));
1326 put(output
, &super
, sizeof(super
));
1328 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1330 _foreach (blob
, blobs
) {
1332 index
.type
= Swap(blob
.first
);
1333 index
.offset
= Swap(uint32_t(offset
));
1334 put(output
, &index
, sizeof(index
));
1335 offset
+= blob
.second
.size();
1338 _foreach (blob
, blobs
)
1339 put(output
, blob
.second
.data(), blob
.second
.size());
1344 #ifndef LDID_NOSMIME
1353 _assert(bio_
!= NULL
);
1357 bio_(BIO_new(BIO_s_mem()))
1361 Buffer(const char *data
, size_t size
) :
1362 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1366 Buffer(const std::string
&data
) :
1367 Buffer(data
.data(), data
.size())
1371 Buffer(PKCS7
*pkcs
) :
1374 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1381 operator BIO
*() const {
1385 explicit operator std::string() const {
1387 auto size(BIO_get_mem_data(bio_
, &data
));
1388 return std::string(data
, size
);
1397 STACK_OF(X509
) *ca_
;
1401 value_(d2i_PKCS12_bio(bio
, NULL
)),
1404 _assert(value_
!= NULL
);
1405 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1406 _assert(key_
!= NULL
);
1407 _assert(cert_
!= NULL
);
1410 Stuff(const std::string
&data
) :
1416 sk_X509_pop_free(ca_
, X509_free
);
1418 EVP_PKEY_free(key_
);
1419 PKCS12_free(value_
);
1422 operator PKCS12
*() const {
1426 operator EVP_PKEY
*() const {
1430 operator X509
*() const {
1434 operator STACK_OF(X509
) *() const {
1444 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1445 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1447 _assert(value_
!= NULL
);
1454 operator PKCS7
*() const {
1461 public std::streambuf
1464 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1468 virtual int_type
overflow(int_type next
) {
1475 uint8_t sha1_
[LDID_SHA1_DIGEST_LENGTH
];
1479 public std::streambuf
1484 LDID_SHA1_CTX sha1_
;
1485 LDID_SHA256_CTX sha256_
;
1488 HashBuffer(ldid::Hash
&hash
) :
1491 LDID_SHA1_Init(&sha1_
);
1492 LDID_SHA256_Init(&sha256_
);
1496 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1497 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1500 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1501 LDID_SHA1_Update(&sha1_
, data
, size
);
1502 LDID_SHA256_Update(&sha256_
, data
, size
);
1506 virtual int_type
overflow(int_type next
) {
1507 if (next
== traits_type::eof())
1519 std::streambuf
&buffer_
;
1522 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1528 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1529 _assert(HashBuffer::xsputn(data
, size
) == size
);
1530 return buffer_
.sputn(data
, size
);
1534 #ifndef LDID_NOTOOLS
1535 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1536 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1544 Split(const std::string
&path
) {
1545 size_t slash(path
.rfind('/'));
1546 if (slash
== std::string::npos
)
1549 dir
= path
.substr(0, slash
+ 1);
1550 base
= path
.substr(slash
+ 1);
1555 static void mkdir_p(const std::string
&path
) {
1559 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1562 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1565 auto slash(path
.rfind('/', path
.size() - 1));
1566 if (slash
== std::string::npos
)
1568 mkdir_p(path
.substr(0, slash
));
1571 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1572 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1574 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1578 static void Commit(const std::string
&path
, const std::string
&temp
) {
1580 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1582 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1584 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1587 _syscall(rename(temp
.c_str(), path
.c_str()));
1593 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirement
, const std::string
&key
, const Slots
&slots
, const Functor
<void (double)> &percent
) {
1598 #ifndef LDID_NOSMIME
1601 auto name(X509_get_subject_name(stuff
));
1602 _assert(name
!= NULL
);
1603 auto index(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, -1));
1604 _assert(index
>= 0);
1605 auto next(X509_NAME_get_index_by_NID(name
, NID_organizationalUnitName
, index
));
1606 _assert(next
== -1);
1607 auto entry(X509_NAME_get_entry(name
, index
));
1608 _assert(entry
!= NULL
);
1609 auto asn(X509_NAME_ENTRY_get_data(entry
));
1610 _assert(asn
!= NULL
);
1611 team
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1615 // XXX: this is just a "sufficiently large number"
1616 size_t certificate(0x3000);
1618 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1619 size_t alloc(sizeof(struct SuperBlob
));
1621 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1623 uint32_t special(0);
1625 _foreach (slot
, slots
)
1626 special
= std::max(special
, slot
.first
);
1628 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1629 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1630 special
= std::max(special
, CSSLOT_INFOSLOT
);
1633 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1634 alloc
+= sizeof(struct BlobIndex
);
1635 if (requirement
.empty())
1638 alloc
+= requirement
.size();
1640 if (!entitlements
.empty()) {
1641 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1642 alloc
+= sizeof(struct BlobIndex
);
1643 alloc
+= sizeof(struct Blob
);
1644 alloc
+= entitlements
.size();
1647 size_t directory(0);
1649 directory
+= sizeof(struct BlobIndex
);
1650 directory
+= sizeof(struct Blob
);
1651 directory
+= sizeof(struct CodeDirectory
);
1652 directory
+= identifier
.size() + 1;
1655 directory
+= team
.size() + 1;
1657 for (Algorithm
*algorithm
: GetAlgorithms())
1658 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
1661 alloc
+= sizeof(struct BlobIndex
);
1662 alloc
+= sizeof(struct Blob
);
1663 alloc
+= certificate
;
1667 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1671 std::stringbuf data
;
1673 if (requirement
.empty()) {
1675 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1677 put(data
, requirement
.data(), requirement
.size());
1680 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1683 if (!entitlements
.empty()) {
1684 std::stringbuf data
;
1685 put(data
, entitlements
.data(), entitlements
.size());
1686 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1691 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1692 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
1693 auto &slot(posts
[CSSLOT_INFOSLOT
]);
1694 for (Algorithm
*algorithm
: GetAlgorithms())
1695 (*algorithm
)(slot
, data
, size
);
1700 for (Algorithm
*pointer
: GetAlgorithms()) {
1701 Algorithm
&algorithm(*pointer
);
1703 std::stringbuf data
;
1705 uint32_t special(0);
1706 _foreach (blob
, blobs
)
1707 special
= std::max(special
, blob
.first
);
1708 _foreach (slot
, posts
)
1709 special
= std::max(special
, slot
.first
);
1710 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1712 CodeDirectory directory
;
1713 directory
.version
= Swap(uint32_t(0x00020200));
1714 directory
.flags
= Swap(uint32_t(0));
1715 directory
.nSpecialSlots
= Swap(special
);
1716 directory
.codeLimit
= Swap(uint32_t(limit
));
1717 directory
.nCodeSlots
= Swap(normal
);
1718 directory
.hashSize
= algorithm
.size_
;
1719 directory
.hashType
= algorithm
.type_
;
1720 directory
.spare1
= 0x00;
1721 directory
.pageSize
= PageShift_
;
1722 directory
.spare2
= Swap(uint32_t(0));
1723 directory
.scatterOffset
= Swap(uint32_t(0));
1724 directory
.spare3
= Swap(uint32_t(0));
1725 directory
.codeLimit64
= Swap(uint64_t(0));
1727 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1729 directory
.identOffset
= Swap(uint32_t(offset
));
1730 offset
+= identifier
.size() + 1;
1733 directory
.teamIDOffset
= Swap(uint32_t(0));
1735 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1736 offset
+= team
.size() + 1;
1739 offset
+= special
* algorithm
.size_
;
1740 directory
.hashOffset
= Swap(uint32_t(offset
));
1741 offset
+= normal
* algorithm
.size_
;
1743 put(data
, &directory
, sizeof(directory
));
1745 put(data
, identifier
.c_str(), identifier
.size() + 1);
1747 put(data
, team
.c_str(), team
.size() + 1);
1749 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
1750 auto *hashes(&storage
[special
* algorithm
.size_
]);
1752 memset(storage
.data(), 0, special
* algorithm
.size_
);
1754 _foreach (blob
, blobs
) {
1755 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1756 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
1759 _foreach (slot
, posts
)
1760 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
1764 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
1765 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1766 percent(double(i
) / normal
);
1769 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1772 put(data
, storage
.data(), storage
.size());
1774 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
1775 algorithm(hash
, save
.data(), save
.size());
1780 #ifndef LDID_NOSMIME
1782 std::stringbuf data
;
1783 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1788 Signature
signature(stuff
, sign
);
1789 Buffer
result(signature
);
1790 std::string
value(result
);
1791 put(data
, value
.data(), value
.size());
1793 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
1794 _assert(save
.size() <= certificate
);
1798 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1804 #ifndef LDID_NOTOOLS
1805 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<void (double)> &percent
) {
1806 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1808 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1813 std::string
DiskFolder::Path(const std::string
&path
) const {
1814 return path_
+ "/" + path
;
1817 DiskFolder::DiskFolder(const std::string
&path
) :
1822 DiskFolder::~DiskFolder() {
1823 if (!std::uncaught_exception())
1824 for (const auto &commit
: commit_
)
1825 Commit(commit
.first
, commit
.second
);
1829 std::string
readlink(const std::string
&path
) {
1830 for (size_t size(1024); ; size
*= 2) {
1834 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
1835 if (size_t(writ
) >= size
)
1844 void DiskFolder::Find(const std::string
&root
, const std::string
&base
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
1845 std::string
path(Path(root
) + base
);
1847 DIR *dir(opendir(path
.c_str()));
1848 _assert(dir
!= NULL
);
1849 _scope({ _syscall(closedir(dir
)); });
1851 while (auto child
= readdir(dir
)) {
1852 std::string
name(child
->d_name
);
1853 if (name
== "." || name
== "..")
1855 if (Starts(name
, ".ldid."))
1862 _syscall(stat((path
+ name
).c_str(), &info
));
1864 else if (S_ISDIR(info
.st_mode
))
1866 else if (S_ISREG(info
.st_mode
))
1869 _assert_(false, "st_mode=%x", info
.st_mode
);
1871 switch (child
->d_type
) {
1879 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
1882 _assert_(false, "d_type=%u", child
->d_type
);
1887 Find(root
, base
+ name
+ "/", code
, link
);
1893 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1896 std::stringbuf save
;
1900 auto from(Path(path
));
1901 commit_
[from
] = Temporary(save
, from
);
1906 bool DiskFolder::Look(const std::string
&path
) const {
1907 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
1910 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
1912 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1913 _assert_(result
== &data
, "DiskFolder::Open(%s)", path
.c_str());
1915 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
1916 data
.pubseekpos(0, std::ios::in
);
1917 code(data
, length
, NULL
);
1920 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
1921 Find(path
, "", code
, link
);
1925 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
1931 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1932 return parent_
.Save(path_
+ path
, edit
, flag
, code
);
1935 bool SubFolder::Look(const std::string
&path
) const {
1936 return parent_
.Look(path_
+ path
);
1939 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
1940 return parent_
.Open(path_
+ path
, code
);
1943 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
1944 return parent_
.Find(path_
+ path
, code
, link
);
1947 std::string
UnionFolder::Map(const std::string
&path
) const {
1948 auto remap(remaps_
.find(path
));
1949 if (remap
== remaps_
.end())
1951 return remap
->second
;
1954 void UnionFolder::Map(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const std::string
&file
, const Functor
<void (const Functor
<void (std::streambuf
&, size_t, const void *)> &)> &save
) const {
1955 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
1956 code(file
.substr(path
.size()));
1959 UnionFolder::UnionFolder(Folder
&parent
) :
1964 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
1965 return parent_
.Save(Map(path
), edit
, flag
, code
);
1968 bool UnionFolder::Look(const std::string
&path
) const {
1969 auto file(resets_
.find(path
));
1970 if (file
!= resets_
.end())
1972 return parent_
.Look(Map(path
));
1975 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
1976 auto file(resets_
.find(path
));
1977 if (file
== resets_
.end())
1978 return parent_
.Open(Map(path
), code
);
1979 auto &entry(file
->second
);
1981 auto &data(*entry
.data_
);
1982 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
1983 data
.pubseekpos(0, std::ios::in
);
1984 code(data
, length
, entry
.flag_
);
1987 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
1988 for (auto &reset
: resets_
)
1989 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
1990 auto &entry(reset
.second
);
1991 auto &data(*entry
.data_
);
1992 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
1993 data
.pubseekpos(0, std::ios::in
);
1994 code(data
, length
, entry
.flag_
);
1997 for (auto &remap
: remaps_
)
1998 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
1999 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2000 code(data
, length
, flag
);
2004 parent_
.Find(path
, fun([&](const std::string
&name
) {
2005 if (deletes_
.find(path
+ name
) == deletes_
.end())
2007 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2008 if (deletes_
.find(path
+ name
) == deletes_
.end())
2013 #ifndef LDID_NOTOOLS
2014 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const ldid::Functor
<void (double)> &percent
) {
2018 char data
[4096 * 4];
2019 size_t writ(source
.sgetn(data
, sizeof(data
)));
2022 _assert(target
.sputn(data
, writ
) == writ
);
2024 percent(double(total
) / length
);
2028 #ifndef LDID_NOPLIST
2029 static plist_t
plist(const std::string
&data
) {
2030 plist_t
plist(NULL
);
2031 if (Starts(data
, "bplist00"))
2032 plist_from_bin(data
.data(), data
.size(), &plist
);
2034 plist_from_xml(data
.data(), data
.size(), &plist
);
2035 _assert(plist
!= NULL
);
2039 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2040 std::stringbuf data
;
2041 copy(buffer
, data
, length
, ldid::fun(dummy
));
2042 auto node(plist(data
.str()));
2043 _scope({ plist_free(node
); });
2044 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2048 static std::string
plist_s(plist_t node
) {
2049 _assert(node
!= NULL
);
2050 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2052 plist_get_string_val(node
, &data
);
2053 _scope({ free(data
); });
2069 std::vector
<std::string
> matches_
;
2072 Expression(const std::string
&code
) {
2073 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2074 matches_
.resize(regex_
.re_nsub
+ 1);
2081 bool operator ()(const std::string
&data
) {
2082 regmatch_t matches
[matches_
.size()];
2083 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2084 if (value
== REG_NOMATCH
)
2086 _assert_(value
== 0, "regexec()");
2087 for (size_t i(0); i
!= matches_
.size(); ++i
)
2088 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2092 const std::string
&operator [](size_t index
) const {
2093 return matches_
[index
];
2102 mutable std::auto_ptr
<Expression
> regex_
;
2104 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2111 Rule(const Rule
&rhs
) :
2112 weight_(rhs
.weight_
),
2118 void Compile() const {
2119 regex_
.reset(new Expression(code_
));
2122 bool operator ()(const std::string
&data
) const {
2123 _assert(regex_
.get() != NULL
);
2124 return (*regex_
)(data
);
2127 bool operator <(const Rule
&rhs
) const {
2128 if (weight_
> rhs
.weight_
)
2130 if (weight_
< rhs
.weight_
)
2132 return mode_
> rhs
.mode_
;
2137 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2138 return lhs
->code_
< rhs
->code_
;
2142 #ifndef LDID_NOPLIST
2143 static Hash
Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, Hash
&hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirement
, const std::string
&key
, const Slots
&slots
, size_t length
, const Functor
<void (double)> &percent
) {
2144 // XXX: this is a miserable fail
2145 std::stringbuf temp
;
2146 put(temp
, prefix
, size
);
2147 copy(buffer
, temp
, length
- size
, percent
);
2148 // XXX: this is a stupid hack
2149 pad(temp
, 0x10 - (length
& 0xf));
2150 auto data(temp
.str());
2152 HashProxy
proxy(hash
, save
);
2153 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, requirement
, key
, slots
, percent
);
2156 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, Hash
> &remote
, const std::string
&requirement
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2157 std::string executable
;
2158 std::string identifier
;
2162 std::string
info("Info.plist");
2163 if (!folder
.Look(info
) && folder
.Look("Resources/" + info
)) {
2165 info
= "Resources/" + info
;
2168 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2169 plist_d(buffer
, length
, fun([&](plist_t node
) {
2170 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2171 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2175 if (!mac
&& folder
.Look("MacOS/" + executable
)) {
2176 executable
= "MacOS/" + executable
;
2180 std::string entitlements
;
2181 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2182 // XXX: this is a miserable fail
2183 std::stringbuf temp
;
2184 copy(buffer
, temp
, length
, percent
);
2185 // XXX: this is a stupid hack
2186 pad(temp
, 0x10 - (length
& 0xf));
2187 auto data(temp
.str());
2188 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2191 static const std::string
directory("_CodeSignature/");
2192 static const std::string
signature(directory
+ "CodeResources");
2194 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2196 auto &rules1(versions
[""]);
2197 auto &rules2(versions
["2"]);
2199 const std::string
resources(mac
? "Resources/" : "");
2202 rules1
.insert(Rule
{1, NoMode
, "^" + resources
});
2203 if (!mac
) rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
2204 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2205 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2206 if (!mac
) rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
2207 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2211 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2212 rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2213 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2214 if (!mac
) rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
2215 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2216 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2217 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2218 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2219 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2220 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2221 if (!mac
) rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
2222 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2223 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2224 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2227 std::map
<std::string
, Hash
> local
;
2229 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2230 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2231 std::map
<std::string
, Bundle
> bundles
;
2233 folder
.Find("", fun([&](const std::string
&name
) {
2236 auto bundle(root
+ Split(name
).dir
);
2237 bundle
.resize(bundle
.size() - resources
.size());
2238 SubFolder
subfolder(folder
, bundle
);
2240 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2241 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&entitlements
) -> std::string
{ return entitlements
; }))
2242 , progress
, percent
);
2243 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2246 std::set
<std::string
> excludes
;
2248 auto exclude([&](const std::string
&name
) {
2249 // BundleDiskRep::adjustResources -> builder.addExclusion
2250 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2253 for (const auto &bundle
: bundles
)
2254 if (Starts(name
, bundle
.first
+ "/")) {
2255 excludes
.insert(name
);
2262 std::map
<std::string
, std::string
> links
;
2264 folder
.Find("", fun([&](const std::string
&name
) {
2268 if (local
.find(name
) != local
.end())
2270 auto &hash(local
[name
]);
2272 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2273 progress(root
+ name
);
2284 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2286 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2287 switch (Swap(header
.magic
)) {
2289 // Java class file format
2290 if (Swap(header
.count
) >= 40)
2293 case MH_MAGIC
: case MH_MAGIC_64
:
2294 case MH_CIGAM
: case MH_CIGAM_64
:
2295 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2297 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", "", key
, slots
, length
, percent
);
2302 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2303 HashProxy
proxy(hash
, save
);
2304 put(proxy
, header
.bytes
, size
);
2305 copy(data
, proxy
, length
- size
, percent
);
2308 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2312 links
[name
] = read();
2315 auto plist(plist_new_dict());
2316 _scope({ plist_free(plist
); });
2318 for (const auto &version
: versions
) {
2319 auto files(plist_new_dict());
2320 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2322 for (const auto &rule
: version
.second
)
2325 bool old(&version
.second
== &rules1
);
2327 for (const auto &hash
: local
)
2328 for (const auto &rule
: version
.second
)
2329 if (rule(hash
.first
)) {
2330 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2331 else if (old
&& rule
.mode_
== NoMode
)
2332 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2333 else if (rule
.mode_
!= OmitMode
) {
2334 auto entry(plist_new_dict());
2335 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2337 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2338 if (rule
.mode_
== OptionalMode
)
2339 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2340 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2346 for (const auto &link
: links
)
2347 for (const auto &rule
: version
.second
)
2348 if (rule(link
.first
)) {
2349 if (rule
.mode_
!= OmitMode
) {
2350 auto entry(plist_new_dict());
2351 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2352 if (rule
.mode_
== OptionalMode
)
2353 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2354 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2361 for (const auto &bundle
: bundles
) {
2362 auto entry(plist_new_dict());
2363 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2364 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2365 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2369 for (const auto &version
: versions
) {
2370 auto rules(plist_new_dict());
2371 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2373 std::multiset
<const Rule
*, RuleCode
> ordered
;
2374 for (const auto &rule
: version
.second
)
2375 ordered
.insert(&rule
);
2377 for (const auto &rule
: ordered
)
2378 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2379 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2381 auto entry(plist_new_dict());
2382 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2384 switch (rule
->mode_
) {
2388 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2391 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2394 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2397 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2401 if (rule
->weight_
>= 10000)
2402 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2403 else if (rule
->weight_
!= 1)
2404 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2408 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2409 HashProxy
proxy(local
[signature
], save
);
2412 plist_to_xml(plist
, &xml
, &size
);
2413 _scope({ free(xml
); });
2414 put(proxy
, xml
, size
);
2418 bundle
.path
= executable
;
2420 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2421 progress(root
+ executable
);
2422 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2424 slots
[1] = local
.at(info
);
2425 slots
[3] = local
.at(signature
);
2426 bundle
.hash
= Sign(NULL
, 0, buffer
, local
[executable
], save
, identifier
, entitlements
, requirement
, key
, slots
, length
, percent
);
2430 for (const auto &entry
: local
)
2431 remote
[root
+ entry
.first
] = entry
.second
;
2436 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, const std::string
&requirement
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2437 std::map
<std::string
, Hash
> local
;
2438 return Sign(root
, folder
, key
, local
, requirement
, alter
, progress
, percent
);
2445 #ifndef LDID_NOTOOLS
2446 int main(int argc
, char *argv
[]) {
2447 #ifndef LDID_NOSMIME
2448 OpenSSL_add_all_algorithms();
2456 little_
= endian
.byte
[0];
2462 #ifndef LDID_NOFLAGT
2476 uint32_t flag_CPUType(_not(uint32_t));
2477 uint32_t flag_CPUSubtype(_not(uint32_t));
2479 const char *flag_I(NULL
);
2481 #ifndef LDID_NOFLAGT
2491 std::vector
<std::string
> files
;
2494 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2495 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2496 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2497 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2501 for (int argi(1); argi
!= argc
; ++argi
)
2502 if (argv
[argi
][0] != '-')
2503 files
.push_back(argv
[argi
]);
2504 else switch (argv
[argi
][1]) {
2511 case 'e': flag_e
= true; break;
2514 const char *string
= argv
[argi
] + 2;
2515 const char *colon
= strchr(string
, ':');
2516 _assert(colon
!= NULL
);
2517 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2519 unsigned number(strtoul(string
, &arge
, 0));
2520 _assert(arge
== colon
);
2521 auto &slot(slots
[number
]);
2522 for (Algorithm
*algorithm
: GetAlgorithms())
2523 (*algorithm
)(slot
, file
.data(), file
.size());
2526 case 'q': flag_q
= true; break;
2529 const char *xml
= argv
[argi
] + 2;
2530 requirement
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2533 case 'D': flag_D
= true; break;
2535 case 'a': flag_a
= true; break;
2540 if (argv
[argi
][2] != '\0') {
2541 const char *cpu
= argv
[argi
] + 2;
2542 const char *colon
= strchr(cpu
, ':');
2543 _assert(colon
!= NULL
);
2545 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2546 _assert(arge
== colon
);
2547 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2548 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2562 if (argv
[argi
][2] != '\0') {
2563 const char *xml
= argv
[argi
] + 2;
2564 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2569 if (argv
[argi
][2] != '\0')
2570 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2573 #ifndef LDID_NOFLAGT
2576 if (argv
[argi
][2] == '-')
2580 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2581 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2591 flag_I
= argv
[argi
] + 2;
2599 _assert(flag_S
|| key
.empty());
2600 _assert(flag_S
|| flag_I
== NULL
);
2602 if (files
.empty()) usage
: {
2606 size_t filei(0), filee(0);
2607 _foreach (file
, files
) try {
2608 std::string
path(file
);
2611 _syscall(stat(path
.c_str(), &info
));
2613 if (S_ISDIR(info
.st_mode
)) {
2614 #ifndef LDID_NOPLIST
2616 ldid::DiskFolder
folder(path
);
2617 path
+= "/" + Sign("", folder
, key
, requirement
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; })
2618 , ldid::fun([&](const std::string
&) {}), ldid::fun(dummy
)
2623 } else if (flag_S
|| flag_r
) {
2624 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2626 std::filebuf output
;
2628 auto temp(Temporary(output
, split
));
2631 ldid::Unsign(input
.data(), input
.size(), output
, ldid::fun(dummy
));
2633 std::string
identifier(flag_I
?: split
.base
.c_str());
2634 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, requirement
, key
, slots
, ldid::fun(dummy
));
2641 #ifndef LDID_NOFLAGT
2648 Map
mapping(path
, modify
);
2649 FatHeader
fat_header(mapping
.data(), mapping
.size());
2651 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2652 struct linkedit_data_command
*signature(NULL
);
2653 struct encryption_info_command
*encryption(NULL
);
2656 if (mach_header
.GetCPUType() != flag_CPUType
)
2658 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2663 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2665 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2666 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2669 else if (cmd
== LC_CODE_SIGNATURE
)
2670 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2671 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2672 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2673 else if (cmd
== LC_LOAD_DYLIB
) {
2674 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2675 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2677 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2680 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2681 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2685 #ifndef LDID_NOFLAGT
2686 else if (cmd
== LC_ID_DYLIB
) {
2687 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2695 dylib_command
->dylib
.timestamp
= 0;
2696 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2699 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2706 _assert(encryption
!= NULL
);
2707 encryption
->cryptid
= mach_header
.Swap(0);
2711 _assert(signature
!= NULL
);
2713 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2715 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2716 uint8_t *blob
= top
+ data
;
2717 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2719 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2720 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2721 uint32_t begin
= Swap(super
->index
[index
].offset
);
2722 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2723 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2728 _assert(signature
!= NULL
);
2730 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2732 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2733 uint8_t *blob
= top
+ data
;
2734 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2736 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2737 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
2738 uint32_t begin
= Swap(super
->index
[index
].offset
);
2739 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2740 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
2745 _assert(signature
!= NULL
);
2747 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2749 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2750 uint8_t *blob
= top
+ data
;
2751 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2753 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2754 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2755 uint32_t begin
= Swap(super
->index
[index
].offset
);
2756 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
2758 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2759 uint32_t pages
= Swap(directory
->nCodeSlots
);
2762 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2763 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
2765 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
2771 } catch (const char *) {