]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Add a build environment for iOS+Cydia packaging.
[ldid.git] / ldid.cpp
CommitLineData
ab113d22 1/* ldid - (Mach-O) Link-Loader Identity Editor
e0524446 2 * Copyright (C) 2007-2012 Jay Freeman (saurik)
a362a82f
JF
3*/
4
e0524446
JF
5/* GNU Lesser General Public License, Version 3 {{{ */
6/* This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
a362a82f 10 *
e0524446
JF
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
a362a82f 15 *
e0524446
JF
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18**/
19/* }}} */
a362a82f
JF
20
21#include "minimal/stdlib.h"
b8187ac7 22#include "minimal/string.h"
a362a82f
JF
23#include "minimal/mapping.h"
24
fdb119ef
JF
25#include "sha1.h"
26
a362a82f
JF
27#include <cstring>
28#include <string>
29#include <vector>
30
fdb119ef 31#include <sys/wait.h>
31ad673b
JF
32#include <sys/types.h>
33#include <sys/stat.h>
fdb119ef 34
a362a82f
JF
35struct fat_header {
36 uint32_t magic;
37 uint32_t nfat_arch;
c05d9758 38} _packed;
a362a82f
JF
39
40#define FAT_MAGIC 0xcafebabe
41#define FAT_CIGAM 0xbebafeca
42
43struct fat_arch {
44 uint32_t cputype;
45 uint32_t cpusubtype;
46 uint32_t offset;
47 uint32_t size;
48 uint32_t align;
c05d9758 49} _packed;
a362a82f
JF
50
51struct mach_header {
52 uint32_t magic;
53 uint32_t cputype;
04802ab1 54 uint32_t cpusubtype;
a362a82f
JF
55 uint32_t filetype;
56 uint32_t ncmds;
57 uint32_t sizeofcmds;
58 uint32_t flags;
c05d9758 59} _packed;
a362a82f 60
fdb119ef 61#define MH_MAGIC 0xfeedface
a362a82f
JF
62#define MH_CIGAM 0xcefaedfe
63
3cbc6463
JF
64#define MH_MAGIC_64 0xfeedfacf
65#define MH_CIGAM_64 0xcffaedfe
66
82813bde
JF
67#define MH_DYLDLINK 0x4
68
efd6cd4a
JF
69#define MH_EXECUTE 0x2
70#define MH_DYLIB 0x6
71#define MH_BUNDLE 0x8
72#define MH_DYLIB_STUB 0x9
a362a82f
JF
73
74struct load_command {
75 uint32_t cmd;
76 uint32_t cmdsize;
c05d9758 77} _packed;
a362a82f 78
4a57e66c
JF
79#define LC_REQ_DYLD uint32_t(0x80000000)
80
81#define LC_SEGMENT uint32_t(0x01)
82#define LC_SYMTAB uint32_t(0x02)
83#define LC_DYSYMTAB uint32_t(0x0b)
84#define LC_LOAD_DYLIB uint32_t(0x0c)
85#define LC_ID_DYLIB uint32_t(0x0d)
289ccbbc 86#define LC_SEGMENT_64 uint32_t(0x19)
4a57e66c
JF
87#define LC_UUID uint32_t(0x1b)
88#define LC_CODE_SIGNATURE uint32_t(0x1d)
89#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
90#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
c0cc1574 91#define LC_ENCRYPTION_INFO uint32_t(0x21)
4a57e66c
JF
92#define LC_DYLD_INFO uint32_t(0x22)
93#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
a362a82f
JF
94
95struct dylib {
96 uint32_t name;
97 uint32_t timestamp;
98 uint32_t current_version;
99 uint32_t compatibility_version;
c05d9758 100} _packed;
a362a82f
JF
101
102struct dylib_command {
103 uint32_t cmd;
104 uint32_t cmdsize;
105 struct dylib dylib;
c05d9758 106} _packed;
a362a82f
JF
107
108struct uuid_command {
109 uint32_t cmd;
110 uint32_t cmdsize;
111 uint8_t uuid[16];
c05d9758 112} _packed;
a362a82f 113
20e7eb29
JF
114struct symtab_command {
115 uint32_t cmd;
116 uint32_t cmdsize;
117 uint32_t symoff;
118 uint32_t nsyms;
119 uint32_t stroff;
120 uint32_t strsize;
121} _packed;
122
4a57e66c
JF
123struct dyld_info_command {
124 uint32_t cmd;
125 uint32_t cmdsize;
126 uint32_t rebase_off;
127 uint32_t rebase_size;
128 uint32_t bind_off;
129 uint32_t bind_size;
130 uint32_t weak_bind_off;
131 uint32_t weak_bind_size;
132 uint32_t lazy_bind_off;
133 uint32_t lazy_bind_size;
134 uint32_t export_off;
135 uint32_t export_size;
136} _packed;
137
138struct dysymtab_command {
139 uint32_t cmd;
140 uint32_t cmdsize;
141 uint32_t ilocalsym;
142 uint32_t nlocalsym;
143 uint32_t iextdefsym;
144 uint32_t nextdefsym;
145 uint32_t iundefsym;
146 uint32_t nundefsym;
147 uint32_t tocoff;
148 uint32_t ntoc;
149 uint32_t modtaboff;
150 uint32_t nmodtab;
151 uint32_t extrefsymoff;
152 uint32_t nextrefsyms;
153 uint32_t indirectsymoff;
154 uint32_t nindirectsyms;
155 uint32_t extreloff;
156 uint32_t nextrel;
157 uint32_t locreloff;
158 uint32_t nlocrel;
159} _packed;
160
161struct dylib_table_of_contents {
162 uint32_t symbol_index;
163 uint32_t module_index;
164} _packed;
165
166struct dylib_module {
167 uint32_t module_name;
168 uint32_t iextdefsym;
169 uint32_t nextdefsym;
170 uint32_t irefsym;
171 uint32_t nrefsym;
172 uint32_t ilocalsym;
173 uint32_t nlocalsym;
174 uint32_t iextrel;
175 uint32_t nextrel;
176 uint32_t iinit_iterm;
177 uint32_t ninit_nterm;
178 uint32_t objc_module_info_addr;
179 uint32_t objc_module_info_size;
180} _packed;
181
182struct dylib_reference {
183 uint32_t isym:24;
184 uint32_t flags:8;
185} _packed;
186
187struct relocation_info {
188 int32_t r_address;
189 uint32_t r_symbolnum:24;
190 uint32_t r_pcrel:1;
191 uint32_t r_length:2;
192 uint32_t r_extern:1;
193 uint32_t r_type:4;
194} _packed;
195
196struct nlist {
197 union {
198 char *n_name;
199 int32_t n_strx;
200 } n_un;
201
202 uint8_t n_type;
203 uint8_t n_sect;
204 uint8_t n_desc;
205 uint32_t n_value;
206} _packed;
207
6e83315b
JF
208struct segment_command {
209 uint32_t cmd;
210 uint32_t cmdsize;
211 char segname[16];
212 uint32_t vmaddr;
213 uint32_t vmsize;
214 uint32_t fileoff;
215 uint32_t filesize;
216 uint32_t maxprot;
217 uint32_t initprot;
218 uint32_t nsects;
219 uint32_t flags;
429e34a5 220} _packed;
6e83315b 221
289ccbbc
JF
222struct segment_command_64 {
223 uint32_t cmd;
224 uint32_t cmdsize;
225 char segname[16];
226 uint64_t vmaddr;
227 uint64_t vmsize;
228 uint64_t fileoff;
229 uint64_t filesize;
230 uint32_t maxprot;
231 uint32_t initprot;
232 uint32_t nsects;
233 uint32_t flags;
429e34a5 234} _packed;
289ccbbc 235
6e83315b
JF
236struct section {
237 char sectname[16];
238 char segname[16];
239 uint32_t addr;
240 uint32_t size;
241 uint32_t offset;
242 uint32_t align;
243 uint32_t reloff;
244 uint32_t nreloc;
245 uint32_t flags;
246 uint32_t reserved1;
247 uint32_t reserved2;
429e34a5 248} _packed;
6e83315b 249
289ccbbc
JF
250struct section_64 {
251 char sectname[16];
252 char segname[16];
253 uint64_t addr;
254 uint64_t size;
255 uint32_t offset;
256 uint32_t align;
257 uint32_t reloff;
258 uint32_t nreloc;
259 uint32_t flags;
260 uint32_t reserved1;
261 uint32_t reserved2;
429e34a5 262} _packed;
289ccbbc 263
fdb119ef
JF
264struct linkedit_data_command {
265 uint32_t cmd;
266 uint32_t cmdsize;
267 uint32_t dataoff;
268 uint32_t datasize;
c05d9758 269} _packed;
fdb119ef 270
c0cc1574
JF
271struct encryption_info_command {
272 uint32_t cmd;
273 uint32_t cmdsize;
274 uint32_t cryptoff;
275 uint32_t cryptsize;
276 uint32_t cryptid;
277} _packed;
278
fdb119ef
JF
279uint16_t Swap_(uint16_t value) {
280 return
281 ((value >> 8) & 0x00ff) |
282 ((value << 8) & 0xff00);
283}
284
285uint32_t Swap_(uint32_t value) {
286 value = ((value >> 8) & 0x00ff00ff) |
287 ((value << 8) & 0xff00ff00);
288 value = ((value >> 16) & 0x0000ffff) |
289 ((value << 16) & 0xffff0000);
290 return value;
291}
292
293int16_t Swap_(int16_t value) {
294 return Swap_(static_cast<uint16_t>(value));
295}
296
297int32_t Swap_(int32_t value) {
298 return Swap_(static_cast<uint32_t>(value));
299}
300
5525a5a7
JF
301bool little_(true);
302
fdb119ef 303uint16_t Swap(uint16_t value) {
5525a5a7 304 return little_ ? Swap_(value) : value;
fdb119ef
JF
305}
306
307uint32_t Swap(uint32_t value) {
5525a5a7 308 return little_ ? Swap_(value) : value;
fdb119ef
JF
309}
310
311int16_t Swap(int16_t value) {
312 return Swap(static_cast<uint16_t>(value));
313}
314
315int32_t Swap(int32_t value) {
316 return Swap(static_cast<uint32_t>(value));
317}
318
6e83315b
JF
319template <typename Target_>
320class Pointer;
321
0a033524 322class Data {
a362a82f
JF
323 private:
324 void *base_;
325 size_t size_;
3cbc6463 326
0a033524 327 protected:
a362a82f
JF
328 bool swapped_;
329
330 public:
0a033524
JF
331 Data(void *base, size_t size) :
332 base_(base),
333 size_(size),
334 swapped_(false)
335 {
336 }
337
fdb119ef
JF
338 uint16_t Swap(uint16_t value) const {
339 return swapped_ ? Swap_(value) : value;
a362a82f
JF
340 }
341
fdb119ef
JF
342 uint32_t Swap(uint32_t value) const {
343 return swapped_ ? Swap_(value) : value;
a362a82f
JF
344 }
345
fdb119ef
JF
346 int16_t Swap(int16_t value) const {
347 return Swap(static_cast<uint16_t>(value));
a362a82f
JF
348 }
349
fdb119ef
JF
350 int32_t Swap(int32_t value) const {
351 return Swap(static_cast<uint32_t>(value));
a362a82f
JF
352 }
353
0a033524
JF
354 void *GetBase() const {
355 return base_;
356 }
a362a82f 357
0a033524
JF
358 size_t GetSize() const {
359 return size_;
360 }
361};
a362a82f 362
0a033524
JF
363class MachHeader :
364 public Data
365{
366 private:
367 bool bits64_;
368
369 struct mach_header *mach_header_;
370 struct load_command *load_command_;
371
372 public:
373 MachHeader(void *base, size_t size) :
374 Data(base, size)
375 {
376 mach_header_ = (mach_header *) base;
a362a82f 377
3cbc6463
JF
378 switch (Swap(mach_header_->magic)) {
379 case MH_CIGAM:
380 swapped_ = !swapped_;
381 case MH_MAGIC:
382 bits64_ = false;
383 break;
384
385 case MH_CIGAM_64:
386 swapped_ = !swapped_;
387 case MH_MAGIC_64:
388 bits64_ = true;
389 break;
390
391 default:
392 _assert(false);
393 }
394
395 void *post = mach_header_ + 1;
396 if (bits64_)
397 post = (uint32_t *) post + 1;
398 load_command_ = (struct load_command *) post;
a362a82f
JF
399
400 _assert(
401 Swap(mach_header_->filetype) == MH_EXECUTE ||
402 Swap(mach_header_->filetype) == MH_DYLIB ||
403 Swap(mach_header_->filetype) == MH_BUNDLE
404 );
405 }
406
afbb7c8e
JF
407 struct mach_header *operator ->() const {
408 return mach_header_;
409 }
410
04802ab1
JF
411 uint32_t GetCPUType() const {
412 return Swap(mach_header_->cputype);
413 }
414
415 uint16_t GetCPUSubtype() const {
416 return Swap(mach_header_->cpusubtype) & 0xff;
417 }
418
0a033524 419 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
420 std::vector<struct load_command *> load_commands;
421
3cbc6463 422 struct load_command *load_command = load_command_;
a362a82f
JF
423 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
424 load_commands.push_back(load_command);
425 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
426 }
427
428 return load_commands;
429 }
6e83315b 430
6f340f51 431 std::vector<segment_command *> GetSegments(const char *segment_name) const {
6e83315b
JF
432 std::vector<struct segment_command *> segment_commands;
433
289ccbbc 434 _foreach (load_command, GetLoadCommands()) {
0a033524
JF
435 if (Swap(load_command->cmd) == LC_SEGMENT) {
436 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
437 if (strncmp(segment_command->segname, segment_name, 16) == 0)
438 segment_commands.push_back(segment_command);
439 }
289ccbbc
JF
440 }
441
442 return segment_commands;
443 }
444
445 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) {
446 std::vector<struct segment_command_64 *> segment_commands;
447
448 _foreach (load_command, GetLoadCommands()) {
449 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
450 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
451 if (strncmp(segment_command->segname, segment_name, 16) == 0)
452 segment_commands.push_back(segment_command);
453 }
454 }
6e83315b
JF
455
456 return segment_commands;
457 }
458
6f340f51 459 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
6e83315b
JF
460 std::vector<section *> sections;
461
462 _foreach (segment, GetSegments(segment_name)) {
0a033524 463 section *section = (struct section *) (segment + 1);
6e83315b
JF
464
465 uint32_t sect;
0a033524 466 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
467 if (strncmp(section->sectname, section_name, 16) == 0)
468 sections.push_back(section);
469 ++section;
470 }
471 }
472
473 return sections;
474 }
475
476 template <typename Target_>
0a033524 477 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
478 load_command *load_command = (struct load_command *) (mach_header_ + 1);
479 uint32_t cmd;
480
481 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
482 if (Swap(load_command->cmd) == LC_SEGMENT) {
483 segment_command *segment_command = (struct segment_command *) load_command;
484 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
485 goto next_command;
486
487 section *sections = (struct section *) (segment_command + 1);
488
489 uint32_t sect;
490 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
491 section *section = &sections[sect];
492 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
493 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
494 //printf("0x%.8x %s\n", address, segment_command->segname);
495 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
496 }
497 }
498 }
499
500 next_command:
501 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
502 }
503
504 return Pointer<Target_>(this);
505 }
506
507 template <typename Target_>
508 Pointer<Target_> GetOffset(uint32_t offset) {
509 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
510 }
511};
512
289ccbbc
JF
513class FatMachHeader :
514 public MachHeader
515{
516 private:
517 fat_arch *fat_arch_;
518
519 public:
520 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
521 MachHeader(base, size),
522 fat_arch_(fat_arch)
523 {
524 }
525
526 fat_arch *GetFatArch() const {
527 return fat_arch_;
528 }
529};
530
0a033524
JF
531class FatHeader :
532 public Data
533{
534 private:
535 fat_header *fat_header_;
289ccbbc 536 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
537
538 public:
539 FatHeader(void *base, size_t size) :
540 Data(base, size)
541 {
542 fat_header_ = reinterpret_cast<struct fat_header *>(base);
543
544 if (Swap(fat_header_->magic) == FAT_CIGAM) {
545 swapped_ = !swapped_;
546 goto fat;
547 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
548 fat_header_ = NULL;
289ccbbc 549 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
550 } else fat: {
551 size_t fat_narch = Swap(fat_header_->nfat_arch);
552 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
553 size_t arch;
554 for (arch = 0; arch != fat_narch; ++arch) {
555 uint32_t arch_offset = Swap(fat_arch->offset);
556 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 557 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
558 ++fat_arch;
559 }
560 }
561 }
562
289ccbbc 563 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
564 return mach_headers_;
565 }
20e7eb29
JF
566
567 bool IsFat() const {
568 return fat_header_ != NULL;
569 }
6b38c173
JF
570
571 struct fat_header *operator ->() const {
572 return fat_header_;
573 }
0a033524
JF
574};
575
80fb9fad 576FatHeader Map(const char *path, bool ro = false) {
0a033524 577 size_t size;
80fb9fad 578 void *base(map(path, 0, _not(size_t), &size, ro));
0a033524
JF
579 return FatHeader(base, size);
580}
581
6e83315b
JF
582template <typename Target_>
583class Pointer {
584 private:
0a033524 585 const MachHeader *framework_;
6e83315b
JF
586 const Target_ *pointer_;
587
588 public:
0a033524 589 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
590 framework_(framework),
591 pointer_(pointer)
592 {
593 }
594
595 operator const Target_ *() const {
596 return pointer_;
597 }
598
599 const Target_ *operator ->() const {
600 return pointer_;
601 }
602
603 Pointer<Target_> &operator ++() {
604 ++pointer_;
605 return *this;
606 }
607
608 template <typename Value_>
609 Value_ Swap(Value_ value) {
610 return framework_->Swap(value);
611 }
a362a82f
JF
612};
613
645f8f12
JF
614#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
615#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
616#define CSMAGIC_ENTITLEMENTS uint32_t(0xfade7171)
c05d9758 617
645f8f12
JF
618#define CSSLOT_CODEDIRECTORY uint32_t(0)
619#define CSSLOT_REQUIREMENTS uint32_t(2)
620#define CSSLOT_ENTITLEMENTS uint32_t(5)
fdb119ef
JF
621
622struct BlobIndex {
623 uint32_t type;
624 uint32_t offset;
c05d9758 625} _packed;
fdb119ef 626
c05d9758 627struct Blob {
fdb119ef
JF
628 uint32_t magic;
629 uint32_t length;
c05d9758
JF
630} _packed;
631
632struct SuperBlob {
633 struct Blob blob;
fdb119ef
JF
634 uint32_t count;
635 struct BlobIndex index[];
c05d9758 636} _packed;
fdb119ef
JF
637
638struct CodeDirectory {
c05d9758 639 struct Blob blob;
fdb119ef
JF
640 uint32_t version;
641 uint32_t flags;
642 uint32_t hashOffset;
643 uint32_t identOffset;
644 uint32_t nSpecialSlots;
645 uint32_t nCodeSlots;
646 uint32_t codeLimit;
647 uint8_t hashSize;
648 uint8_t hashType;
649 uint8_t spare1;
650 uint8_t pageSize;
651 uint32_t spare2;
c05d9758 652} _packed;
fdb119ef 653
a362a82f
JF
654extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
655
fdb119ef
JF
656void sha1(uint8_t *hash, uint8_t *data, size_t size) {
657 SHA1Context context;
658 SHA1Reset(&context);
659 SHA1Input(&context, data, size);
660 SHA1Result(&context, hash);
661}
662
0a033524
JF
663struct CodesignAllocation {
664 uint32_t type_;
665 uint16_t subtype_;
666 size_t size_;
667
668 CodesignAllocation(uint32_t type, uint16_t subtype, size_t size) :
669 type_(type),
670 subtype_(subtype),
671 size_(size)
672 {
673 }
674};
675
a362a82f 676int main(int argc, const char *argv[]) {
5525a5a7
JF
677 union {
678 uint16_t word;
679 uint8_t byte[2];
680 } endian = {1};
681
682 little_ = endian.byte[0];
683
a362a82f 684 bool flag_R(false);
20e7eb29
JF
685 bool flag_r(false);
686
a362a82f
JF
687 bool flag_t(false);
688 bool flag_p(false);
689 bool flag_u(false);
9c83be90 690 bool flag_e(false);
a362a82f
JF
691
692 bool flag_T(false);
20c5f1e8 693
fdb119ef 694 bool flag_S(false);
20c5f1e8 695 bool flag_s(false);
a362a82f 696
6ab830a5
JF
697 bool flag_O(false);
698
c0cc1574
JF
699 bool flag_D(false);
700 bool flag_d(false);
701
8c417842
JF
702 bool flag_A(false);
703 bool flag_a(false);
704
c0cc1574
JF
705 uint32_t flag_CPUType(_not(uint32_t));
706 uint32_t flag_CPUSubtype(_not(uint32_t));
707
a362a82f
JF
708 bool timeh(false);
709 uint32_t timev(0);
710
c05d9758
JF
711 const void *xmld(NULL);
712 size_t xmls(0);
713
6e83315b
JF
714 uintptr_t noffset(_not(uintptr_t));
715 uintptr_t woffset(_not(uintptr_t));
716
a362a82f
JF
717 std::vector<std::string> files;
718
a960f392
JF
719 if (argc == 1) {
720 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 721 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
722 fprintf(stderr, " %s -S cat\n", argv[0]);
723 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
724 exit(0);
725 }
726
a362a82f
JF
727 for (int argi(1); argi != argc; ++argi)
728 if (argv[argi][0] != '-')
729 files.push_back(argv[argi]);
730 else switch (argv[argi][1]) {
731 case 'R': flag_R = true; break;
20e7eb29
JF
732 case 'r': flag_r = true; break;
733
a362a82f
JF
734 case 't': flag_t = true; break;
735 case 'u': flag_u = true; break;
736 case 'p': flag_p = true; break;
9c83be90 737 case 'e': flag_e = true; break;
6ab830a5 738 case 'O': flag_O = true; break;
c05d9758 739
c0cc1574
JF
740 case 'D': flag_D = true; break;
741 case 'd': flag_d = true; break;
742
8c417842
JF
743 case 'a': flag_a = true; break;
744
745 case 'A':
746 flag_A = true;
747 if (argv[argi][2] != '\0') {
748 const char *cpu = argv[argi] + 2;
749 const char *colon = strchr(cpu, ':');
750 _assert(colon != NULL);
751 char *arge;
752 flag_CPUType = strtoul(cpu, &arge, 0);
753 _assert(arge == colon);
754 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
755 _assert(arge == argv[argi] + strlen(argv[argi]));
756 }
757 break;
758
20c5f1e8
JF
759 case 's':
760 _assert(!flag_S);
761 flag_s = true;
762 break;
763
c05d9758 764 case 'S':
20c5f1e8 765 _assert(!flag_s);
c05d9758
JF
766 flag_S = true;
767 if (argv[argi][2] != '\0') {
768 const char *xml = argv[argi] + 2;
769 xmld = map(xml, 0, _not(size_t), &xmls, true);
770 }
771 break;
a362a82f
JF
772
773 case 'T': {
774 flag_T = true;
775 if (argv[argi][2] == '-')
776 timeh = true;
777 else {
778 char *arge;
779 timev = strtoul(argv[argi] + 2, &arge, 0);
780 _assert(arge == argv[argi] + strlen(argv[argi]));
781 }
782 } break;
783
6e83315b
JF
784 case 'n': {
785 char *arge;
786 noffset = strtoul(argv[argi] + 2, &arge, 0);
787 _assert(arge == argv[argi] + strlen(argv[argi]));
788 } break;
789
790 case 'w': {
791 char *arge;
792 woffset = strtoul(argv[argi] + 2, &arge, 0);
793 _assert(arge == argv[argi] + strlen(argv[argi]));
794 } break;
795
a362a82f
JF
796 default:
797 goto usage;
798 break;
799 }
800
801 if (files.empty()) usage: {
802 exit(0);
803 }
804
805 size_t filei(0), filee(0);
806 _foreach (file, files) try {
0a033524 807 const char *path(file.c_str());
fdb119ef
JF
808 const char *base = strrchr(path, '/');
809 char *temp(NULL), *dir;
810
811 if (base != NULL)
b8187ac7 812 dir = strndup_(path, base++ - path + 1);
fdb119ef
JF
813 else {
814 dir = strdup("");
815 base = path;
816 }
817
20e7eb29 818 if (flag_r) {
289ccbbc 819 uint32_t clip(0); {
20e7eb29
JF
820 FatHeader fat_header(Map(path));
821 _foreach (mach_header, fat_header.GetMachHeaders()) {
822 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
823
289ccbbc 824 uint32_t size(_not(uint32_t)); {
20e7eb29
JF
825 _foreach (load_command, mach_header.GetLoadCommands()) {
826 switch (mach_header.Swap(load_command->cmd)) {
827 case LC_CODE_SIGNATURE: {
828 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
289ccbbc 829 memset(reinterpret_cast<uint8_t *>(mach_header.GetBase()) + mach_header.Swap(signature->dataoff), 0, mach_header.Swap(signature->datasize));
20e7eb29
JF
830 memset(signature, 0, sizeof(struct linkedit_data_command));
831
289ccbbc
JF
832 mach_header->ncmds = mach_header.Swap(mach_header.Swap(mach_header->ncmds) - 1);
833 mach_header->sizeofcmds = mach_header.Swap(uint32_t(mach_header.Swap(mach_header->sizeofcmds) - sizeof(struct linkedit_data_command)));
20e7eb29
JF
834 } break;
835
836 case LC_SYMTAB: {
837 struct symtab_command *symtab = reinterpret_cast<struct symtab_command *>(load_command);
289ccbbc 838 size = mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize);
20e7eb29
JF
839 } break;
840 }
841 }
289ccbbc 842 }
20e7eb29 843
289ccbbc 844 _assert(size != _not(uint32_t));
20e7eb29 845
289ccbbc
JF
846 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments("__LINKEDIT")) {
847 segment->filesize -= mach_header.GetSize() - size;
848
849 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
850 fat_arch->size = fat_header.Swap(size);
851 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
852 } else
853 clip = std::max(clip, size);
854 }
855
856 _foreach (segment, const_cast<FatMachHeader &>(mach_header).GetSegments64("__LINKEDIT")) {
857 segment->filesize -= mach_header.GetSize() - size;
858
859 if (fat_arch *fat_arch = mach_header.GetFatArch()) {
860 fat_arch->size = fat_header.Swap(size);
861 clip = std::max(clip, fat_header.Swap(fat_arch->offset) + size);
862 } else
863 clip = std::max(clip, size);
20e7eb29
JF
864 }
865 }
866 }
867
289ccbbc
JF
868 _assert(clip != 0);
869 _syscall(truncate(path, clip));
20e7eb29
JF
870 }
871
fdb119ef
JF
872 if (flag_S) {
873 asprintf(&temp, "%s.%s.cs", dir, base);
874 const char *allocate = getenv("CODESIGN_ALLOCATE");
875 if (allocate == NULL)
876 allocate = "codesign_allocate";
877
0a033524
JF
878 std::vector<CodesignAllocation> allocations; {
879 FatHeader fat_header(Map(path));
880 _foreach (mach_header, fat_header.GetMachHeaders()) {
881 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
882
883 size_t size(_not(size_t)); {
884 _foreach (load_command, mach_header.GetLoadCommands()) {
885 uint32_t cmd(mach_header.Swap(load_command->cmd));
886 if (cmd == LC_CODE_SIGNATURE) {
887 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
888 size = mach_header.Swap(signature->dataoff);
889 _assert(size < mach_header.GetSize());
890 break;
891 }
892 }
893
894 if (size == _not(size_t))
895 size = mach_header.GetSize();
afbb7c8e 896 }
afbb7c8e 897
0a033524 898 allocations.push_back(CodesignAllocation(mach_header.GetCPUType(), mach_header.GetCPUSubtype(), size));
afbb7c8e 899 }
fdb119ef
JF
900 }
901
902 pid_t pid = fork();
903 _syscall(pid);
904 if (pid == 0) {
0a033524
JF
905 // XXX: this leaks memory, but it doesn't really matter
906 std::vector<const char *> args;
907 char *arg;
908
909 args.push_back(allocate);
910
911 args.push_back("-i");
912 args.push_back(path);
913
914 _foreach (allocation, allocations) {
915 args.push_back("-A");
916
917 asprintf(&arg, "%u", allocation.type_);
918 args.push_back(arg);
919
920 asprintf(&arg, "%u", allocation.subtype_);
921 args.push_back(arg);
922
923 size_t alloc(0);
924 alloc += sizeof(struct SuperBlob);
925 uint32_t special(0);
926
927 special = std::max(special, CSSLOT_CODEDIRECTORY);
928 alloc += sizeof(struct BlobIndex);
929 alloc += sizeof(struct CodeDirectory);
930 alloc += strlen(base) + 1;
931
932 special = std::max(special, CSSLOT_REQUIREMENTS);
933 alloc += sizeof(struct BlobIndex);
934 alloc += 0xc;
935
936 if (xmld != NULL) {
937 special = std::max(special, CSSLOT_ENTITLEMENTS);
938 alloc += sizeof(struct BlobIndex);
939 alloc += sizeof(struct Blob);
940 alloc += xmls;
941 }
942
943 size_t normal((allocation.size_ + 0x1000 - 1) / 0x1000);
944 alloc += (special + normal) * 0x14;
945
946 alloc += 15;
947 alloc /= 16;
948 alloc *= 16;
949
6f340f51 950 asprintf(&arg, "%zu", alloc);
0a033524
JF
951 args.push_back(arg);
952 }
953
954 args.push_back("-o");
955 args.push_back(temp);
956
957 args.push_back(NULL);
958
959 if (false) {
960 printf("run:");
961 _foreach (arg, args)
962 printf(" %s", arg);
963 printf("\n");
964 }
965
966 execvp(allocate, (char **) &args[0]);
fdb119ef
JF
967 _assert(false);
968 }
969
970 int status;
971 _syscall(waitpid(pid, &status, 0));
972 _assert(WIFEXITED(status));
973 _assert(WEXITSTATUS(status) == 0);
974 }
975
0a033524
JF
976 if (flag_p)
977 printf("path%zu='%s'\n", filei, file.c_str());
978
c0cc1574 979 FatHeader fat_header(Map(temp == NULL ? path : temp, !(flag_R | flag_T | flag_s | flag_S | flag_O | flag_D)));
fdb119ef 980 struct linkedit_data_command *signature(NULL);
a362a82f 981
0a033524 982 _foreach (mach_header, fat_header.GetMachHeaders()) {
8c417842
JF
983 if (flag_A) {
984 if (mach_header.GetCPUType() != flag_CPUType)
985 continue;
986 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
987 continue;
988 }
989
990 if (flag_a)
991 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
992
c0cc1574
JF
993 if (flag_d) {
994 if (struct fat_arch *fat_arch = mach_header.GetFatArch())
995 printf("offset=0x%x\n", Swap(fat_arch->offset));
996 else
997 printf("offset=0x0\n");
998 }
999
0a033524
JF
1000 if (woffset != _not(uintptr_t)) {
1001 Pointer<uint32_t> wvalue(mach_header.GetPointer<uint32_t>(woffset));
1002 if (wvalue == NULL)
1003 printf("(null) %p\n", reinterpret_cast<void *>(woffset));
1004 else
1005 printf("0x%.08x\n", *wvalue);
1006 }
6e83315b 1007
0a033524
JF
1008 if (noffset != _not(uintptr_t))
1009 printf("%s\n", &*mach_header.GetPointer<char>(noffset));
1010
c0cc1574
JF
1011 if (flag_d)
1012 _foreach(segment, mach_header.GetSegments("__TEXT")) {
1013 printf("vmaddr=0x%x\n", mach_header.Swap(segment->vmaddr));
1014 printf("fileoff=0x%x\n", mach_header.Swap(segment->fileoff));
1015 }
1016
6ab830a5
JF
1017 if (flag_O) {
1018 _foreach(section, mach_header.GetSections("__TEXT", "__text"))
1019 section->addr = mach_header.Swap(0);
1020 }
1021
0a033524
JF
1022 _foreach (load_command, mach_header.GetLoadCommands()) {
1023 uint32_t cmd(mach_header.Swap(load_command->cmd));
1024
1025 if (flag_R && cmd == LC_REEXPORT_DYLIB)
1026 load_command->cmd = mach_header.Swap(LC_LOAD_DYLIB);
1027 else if (cmd == LC_CODE_SIGNATURE)
1028 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1029 else if (cmd == LC_UUID) {
1030 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(load_command));
1031
1032 if (flag_u) {
1033 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
1034 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
1035 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
1036 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
1037 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
1038 );
1039 }
1040 } else if (cmd == LC_ID_DYLIB) {
1041 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 1042
0a033524
JF
1043 if (flag_t)
1044 printf("time%zu=0x%.8x\n", filei, mach_header.Swap(dylib_command->dylib.timestamp));
a362a82f 1045
0a033524
JF
1046 if (flag_T) {
1047 uint32_t timed;
a362a82f 1048
0a033524
JF
1049 if (!timeh)
1050 timed = timev;
1051 else {
1052 dylib_command->dylib.timestamp = 0;
1053 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1054 }
a362a82f 1055
0a033524
JF
1056 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1057 }
c0cc1574
JF
1058 } else if (cmd == LC_ENCRYPTION_INFO) {
1059 volatile struct encryption_info_command *encryption_info_command(reinterpret_cast<struct encryption_info_command *>(load_command));
1060
1061 if (flag_D)
1062 encryption_info_command->cryptid = mach_header.Swap(0);
1063
1064 if (flag_d) {
1065 printf("cryptoff=0x%x\n", mach_header.Swap(encryption_info_command->cryptoff));
1066 printf("cryptsize=0x%x\n", mach_header.Swap(encryption_info_command->cryptsize));
1067 }
a362a82f
JF
1068 }
1069 }
a362a82f 1070
0a033524
JF
1071 if (flag_e) {
1072 _assert(signature != NULL);
9c83be90 1073
0a033524 1074 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 1075
0a033524
JF
1076 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1077 uint8_t *blob = top + data;
1078 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 1079
0a033524
JF
1080 for (size_t index(0); index != Swap(super->count); ++index)
1081 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1082 uint32_t begin = Swap(super->index[index].offset);
1083 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1084 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
1085 }
1086 }
9c83be90 1087
0a033524
JF
1088 if (flag_s) {
1089 _assert(signature != NULL);
20c5f1e8 1090
0a033524 1091 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 1092
0a033524
JF
1093 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1094 uint8_t *blob = top + data;
1095 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 1096
0a033524
JF
1097 for (size_t index(0); index != Swap(super->count); ++index)
1098 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1099 uint32_t begin = Swap(super->index[index].offset);
1100 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 1101
0a033524
JF
1102 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + begin + Swap(directory->hashOffset));
1103 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 1104
0a033524
JF
1105 if (pages != 1)
1106 for (size_t i = 0; i != pages - 1; ++i)
1107 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1108 if (pages != 0)
1109 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1110 }
1111 }
20c5f1e8 1112
0a033524
JF
1113 if (flag_S) {
1114 _assert(signature != NULL);
fdb119ef 1115
0a033524
JF
1116 uint32_t data = mach_header.Swap(signature->dataoff);
1117 uint32_t size = mach_header.Swap(signature->datasize);
fdb119ef 1118
0a033524
JF
1119 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1120 uint8_t *blob = top + data;
1121 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1122 super->blob.magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
fdb119ef 1123
0a033524
JF
1124 uint32_t count = xmld == NULL ? 2 : 3;
1125 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
fdb119ef 1126
0a033524
JF
1127 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
1128 super->index[0].offset = Swap(offset);
fdb119ef 1129
0a033524
JF
1130 uint32_t begin = offset;
1131 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1132 offset += sizeof(struct CodeDirectory);
fdb119ef 1133
0a033524
JF
1134 directory->blob.magic = Swap(CSMAGIC_CODEDIRECTORY);
1135 directory->version = Swap(uint32_t(0x00020001));
1136 directory->flags = Swap(uint32_t(0));
1137 directory->codeLimit = Swap(data);
1138 directory->hashSize = 0x14;
1139 directory->hashType = 0x01;
1140 directory->spare1 = 0x00;
1141 directory->pageSize = 0x0c;
1142 directory->spare2 = Swap(uint32_t(0));
fdb119ef 1143
0a033524
JF
1144 directory->identOffset = Swap(offset - begin);
1145 strcpy(reinterpret_cast<char *>(blob + offset), base);
1146 offset += strlen(base) + 1;
fdb119ef 1147
0a033524
JF
1148 uint32_t special = xmld == NULL ? CSSLOT_REQUIREMENTS : CSSLOT_ENTITLEMENTS;
1149 directory->nSpecialSlots = Swap(special);
20c5f1e8 1150
0a033524
JF
1151 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
1152 memset(hashes, 0, sizeof(*hashes) * special);
20c5f1e8 1153
0a033524
JF
1154 offset += sizeof(*hashes) * special;
1155 hashes += special;
fdb119ef 1156
0a033524
JF
1157 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
1158 directory->nCodeSlots = Swap(pages);
fdb119ef 1159
0a033524
JF
1160 if (pages != 1)
1161 for (size_t i = 0; i != pages - 1; ++i)
1162 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1163 if (pages != 0)
1164 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
fdb119ef 1165
0a033524
JF
1166 directory->hashOffset = Swap(offset - begin);
1167 offset += sizeof(*hashes) * pages;
1168 directory->blob.length = Swap(offset - begin);
fdb119ef 1169
0a033524
JF
1170 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
1171 super->index[1].offset = Swap(offset);
afbb7c8e 1172
0a033524
JF
1173 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
1174 offset += 0xc;
afbb7c8e 1175
0a033524
JF
1176 if (xmld != NULL) {
1177 super->index[2].type = Swap(CSSLOT_ENTITLEMENTS);
1178 super->index[2].offset = Swap(offset);
c05d9758 1179
0a033524
JF
1180 uint32_t begin = offset;
1181 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1182 offset += sizeof(struct Blob);
c05d9758 1183
0a033524
JF
1184 memcpy(blob + offset, xmld, xmls);
1185 offset += xmls;
c05d9758 1186
0a033524
JF
1187 entitlements->magic = Swap(CSMAGIC_ENTITLEMENTS);
1188 entitlements->length = Swap(offset - begin);
1189 }
c05d9758 1190
0a033524
JF
1191 for (size_t index(0); index != count; ++index) {
1192 uint32_t type = Swap(super->index[index].type);
1193 if (type != 0 && type <= special) {
1194 uint32_t offset = Swap(super->index[index].offset);
1195 struct Blob *local = (struct Blob *) (blob + offset);
1196 sha1((uint8_t *) (hashes - type), (uint8_t *) local, Swap(local->length));
1197 }
20c5f1e8 1198 }
20c5f1e8 1199
0a033524
JF
1200 super->count = Swap(count);
1201 super->blob.length = Swap(offset);
c05d9758 1202
0a033524
JF
1203 if (offset > size) {
1204 fprintf(stderr, "offset (%u) > size (%u)\n", offset, size);
1205 _assert(false);
1206 } //else fprintf(stderr, "offset (%zu) <= size (%zu)\n", offset, size);
fdb119ef 1207
0a033524
JF
1208 memset(blob + offset, 0, size - offset);
1209 }
fdb119ef
JF
1210 }
1211
122621c5 1212 if (flag_S) {
0a033524
JF
1213 uint8_t *top = reinterpret_cast<uint8_t *>(fat_header.GetBase());
1214 size_t size = fat_header.GetSize();
122621c5
JF
1215
1216 char *copy;
1217 asprintf(&copy, "%s.%s.cp", dir, base);
1218 FILE *file = fopen(copy, "w+");
1219 size_t writ = fwrite(top, 1, size, file);
1220 _assert(writ == size);
1221 fclose(file);
1222
1223 _syscall(unlink(temp));
1224 free(temp);
1225 temp = copy;
1226 }
1227
0a033524 1228 if (temp != NULL) {
31ad673b
JF
1229 struct stat info;
1230 _syscall(stat(path, &info));
1231 _syscall(chown(temp, info.st_uid, info.st_gid));
1232 _syscall(chmod(temp, info.st_mode));
fdb119ef
JF
1233 _syscall(unlink(path));
1234 _syscall(rename(temp, path));
1235 free(temp);
1236 }
1237
1238 free(dir);
a362a82f
JF
1239 ++filei;
1240 } catch (const char *) {
1241 ++filee;
1242 ++filei;
1243 }
1244
1245 return filee;
1246}