]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Support universal (fat) binaries.
[ldid.git] / ldid.cpp
CommitLineData
ab113d22
JF
1/* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2010 Jay Freeman (saurik)
a362a82f
JF
3*/
4
5/*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
17 * distribution.
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36*/
37
38#include "minimal/stdlib.h"
b8187ac7 39#include "minimal/string.h"
a362a82f
JF
40#include "minimal/mapping.h"
41
fdb119ef
JF
42#include "sha1.h"
43
a362a82f
JF
44#include <cstring>
45#include <string>
46#include <vector>
47
fdb119ef 48#include <sys/wait.h>
31ad673b
JF
49#include <sys/types.h>
50#include <sys/stat.h>
fdb119ef 51
a362a82f
JF
52struct fat_header {
53 uint32_t magic;
54 uint32_t nfat_arch;
c05d9758 55} _packed;
a362a82f
JF
56
57#define FAT_MAGIC 0xcafebabe
58#define FAT_CIGAM 0xbebafeca
59
60struct fat_arch {
61 uint32_t cputype;
62 uint32_t cpusubtype;
63 uint32_t offset;
64 uint32_t size;
65 uint32_t align;
c05d9758 66} _packed;
a362a82f
JF
67
68struct mach_header {
69 uint32_t magic;
70 uint32_t cputype;
04802ab1 71 uint32_t cpusubtype;
a362a82f
JF
72 uint32_t filetype;
73 uint32_t ncmds;
74 uint32_t sizeofcmds;
75 uint32_t flags;
c05d9758 76} _packed;
a362a82f 77
fdb119ef 78#define MH_MAGIC 0xfeedface
a362a82f
JF
79#define MH_CIGAM 0xcefaedfe
80
3cbc6463
JF
81#define MH_MAGIC_64 0xfeedfacf
82#define MH_CIGAM_64 0xcffaedfe
83
82813bde
JF
84#define MH_DYLDLINK 0x4
85
efd6cd4a
JF
86#define MH_EXECUTE 0x2
87#define MH_DYLIB 0x6
88#define MH_BUNDLE 0x8
89#define MH_DYLIB_STUB 0x9
a362a82f
JF
90
91struct load_command {
92 uint32_t cmd;
93 uint32_t cmdsize;
c05d9758 94} _packed;
a362a82f 95
645f8f12 96#define LC_REQ_DYLD uint32_t(0x80000000)
a362a82f 97
645f8f12
JF
98#define LC_SEGMENT uint32_t(0x01)
99#define LC_LOAD_DYLIB uint32_t(0x0c)
100#define LC_ID_DYLIB uint32_t(0x0d)
101#define LC_UUID uint32_t(0x1b)
102#define LC_CODE_SIGNATURE uint32_t(0x1d)
103#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
a362a82f
JF
104
105struct dylib {
106 uint32_t name;
107 uint32_t timestamp;
108 uint32_t current_version;
109 uint32_t compatibility_version;
c05d9758 110} _packed;
a362a82f
JF
111
112struct dylib_command {
113 uint32_t cmd;
114 uint32_t cmdsize;
115 struct dylib dylib;
c05d9758 116} _packed;
a362a82f
JF
117
118struct uuid_command {
119 uint32_t cmd;
120 uint32_t cmdsize;
121 uint8_t uuid[16];
c05d9758 122} _packed;
a362a82f 123
6e83315b
JF
124struct segment_command {
125 uint32_t cmd;
126 uint32_t cmdsize;
127 char segname[16];
128 uint32_t vmaddr;
129 uint32_t vmsize;
130 uint32_t fileoff;
131 uint32_t filesize;
132 uint32_t maxprot;
133 uint32_t initprot;
134 uint32_t nsects;
135 uint32_t flags;
136};
137
138struct section {
139 char sectname[16];
140 char segname[16];
141 uint32_t addr;
142 uint32_t size;
143 uint32_t offset;
144 uint32_t align;
145 uint32_t reloff;
146 uint32_t nreloc;
147 uint32_t flags;
148 uint32_t reserved1;
149 uint32_t reserved2;
150};
151
fdb119ef
JF
152struct linkedit_data_command {
153 uint32_t cmd;
154 uint32_t cmdsize;
155 uint32_t dataoff;
156 uint32_t datasize;
c05d9758 157} _packed;
fdb119ef
JF
158
159uint16_t Swap_(uint16_t value) {
160 return
161 ((value >> 8) & 0x00ff) |
162 ((value << 8) & 0xff00);
163}
164
165uint32_t Swap_(uint32_t value) {
166 value = ((value >> 8) & 0x00ff00ff) |
167 ((value << 8) & 0xff00ff00);
168 value = ((value >> 16) & 0x0000ffff) |
169 ((value << 16) & 0xffff0000);
170 return value;
171}
172
173int16_t Swap_(int16_t value) {
174 return Swap_(static_cast<uint16_t>(value));
175}
176
177int32_t Swap_(int32_t value) {
178 return Swap_(static_cast<uint32_t>(value));
179}
180
5525a5a7
JF
181bool little_(true);
182
fdb119ef 183uint16_t Swap(uint16_t value) {
5525a5a7 184 return little_ ? Swap_(value) : value;
fdb119ef
JF
185}
186
187uint32_t Swap(uint32_t value) {
5525a5a7 188 return little_ ? Swap_(value) : value;
fdb119ef
JF
189}
190
191int16_t Swap(int16_t value) {
192 return Swap(static_cast<uint16_t>(value));
193}
194
195int32_t Swap(int32_t value) {
196 return Swap(static_cast<uint32_t>(value));
197}
198
6e83315b
JF
199template <typename Target_>
200class Pointer;
201
0a033524 202class Data {
a362a82f
JF
203 private:
204 void *base_;
205 size_t size_;
3cbc6463 206
0a033524 207 protected:
a362a82f
JF
208 bool swapped_;
209
210 public:
0a033524
JF
211 Data(void *base, size_t size) :
212 base_(base),
213 size_(size),
214 swapped_(false)
215 {
216 }
217
fdb119ef
JF
218 uint16_t Swap(uint16_t value) const {
219 return swapped_ ? Swap_(value) : value;
a362a82f
JF
220 }
221
fdb119ef
JF
222 uint32_t Swap(uint32_t value) const {
223 return swapped_ ? Swap_(value) : value;
a362a82f
JF
224 }
225
fdb119ef
JF
226 int16_t Swap(int16_t value) const {
227 return Swap(static_cast<uint16_t>(value));
a362a82f
JF
228 }
229
fdb119ef
JF
230 int32_t Swap(int32_t value) const {
231 return Swap(static_cast<uint32_t>(value));
a362a82f
JF
232 }
233
0a033524
JF
234 void *GetBase() const {
235 return base_;
236 }
a362a82f 237
0a033524
JF
238 size_t GetSize() const {
239 return size_;
240 }
241};
a362a82f 242
0a033524
JF
243class MachHeader :
244 public Data
245{
246 private:
247 bool bits64_;
248
249 struct mach_header *mach_header_;
250 struct load_command *load_command_;
251
252 public:
253 MachHeader(void *base, size_t size) :
254 Data(base, size)
255 {
256 mach_header_ = (mach_header *) base;
a362a82f 257
3cbc6463
JF
258 switch (Swap(mach_header_->magic)) {
259 case MH_CIGAM:
260 swapped_ = !swapped_;
261 case MH_MAGIC:
262 bits64_ = false;
263 break;
264
265 case MH_CIGAM_64:
266 swapped_ = !swapped_;
267 case MH_MAGIC_64:
268 bits64_ = true;
269 break;
270
271 default:
272 _assert(false);
273 }
274
275 void *post = mach_header_ + 1;
276 if (bits64_)
277 post = (uint32_t *) post + 1;
278 load_command_ = (struct load_command *) post;
a362a82f
JF
279
280 _assert(
281 Swap(mach_header_->filetype) == MH_EXECUTE ||
282 Swap(mach_header_->filetype) == MH_DYLIB ||
283 Swap(mach_header_->filetype) == MH_BUNDLE
284 );
285 }
286
afbb7c8e
JF
287 struct mach_header *operator ->() const {
288 return mach_header_;
289 }
290
04802ab1
JF
291 uint32_t GetCPUType() const {
292 return Swap(mach_header_->cputype);
293 }
294
295 uint16_t GetCPUSubtype() const {
296 return Swap(mach_header_->cpusubtype) & 0xff;
297 }
298
0a033524 299 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
300 std::vector<struct load_command *> load_commands;
301
3cbc6463 302 struct load_command *load_command = load_command_;
a362a82f
JF
303 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
304 load_commands.push_back(load_command);
305 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
306 }
307
308 return load_commands;
309 }
6e83315b
JF
310
311 std::vector<segment_command *> GetSegments(const char *segment_name) {
312 std::vector<struct segment_command *> segment_commands;
313
314 _foreach (load_command, GetLoadCommands())
0a033524
JF
315 if (Swap(load_command->cmd) == LC_SEGMENT) {
316 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
317 if (strncmp(segment_command->segname, segment_name, 16) == 0)
318 segment_commands.push_back(segment_command);
319 }
320
321 return segment_commands;
322 }
323
324 std::vector<section *> GetSections(const char *segment_name, const char *section_name) {
325 std::vector<section *> sections;
326
327 _foreach (segment, GetSegments(segment_name)) {
0a033524 328 section *section = (struct section *) (segment + 1);
6e83315b
JF
329
330 uint32_t sect;
0a033524 331 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
332 if (strncmp(section->sectname, section_name, 16) == 0)
333 sections.push_back(section);
334 ++section;
335 }
336 }
337
338 return sections;
339 }
340
341 template <typename Target_>
0a033524 342 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
343 load_command *load_command = (struct load_command *) (mach_header_ + 1);
344 uint32_t cmd;
345
346 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
347 if (Swap(load_command->cmd) == LC_SEGMENT) {
348 segment_command *segment_command = (struct segment_command *) load_command;
349 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
350 goto next_command;
351
352 section *sections = (struct section *) (segment_command + 1);
353
354 uint32_t sect;
355 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
356 section *section = &sections[sect];
357 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
358 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
359 //printf("0x%.8x %s\n", address, segment_command->segname);
360 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
361 }
362 }
363 }
364
365 next_command:
366 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
367 }
368
369 return Pointer<Target_>(this);
370 }
371
372 template <typename Target_>
373 Pointer<Target_> GetOffset(uint32_t offset) {
374 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
375 }
376};
377
0a033524
JF
378class FatHeader :
379 public Data
380{
381 private:
382 fat_header *fat_header_;
383 std::vector<MachHeader> mach_headers_;
384
385 public:
386 FatHeader(void *base, size_t size) :
387 Data(base, size)
388 {
389 fat_header_ = reinterpret_cast<struct fat_header *>(base);
390
391 if (Swap(fat_header_->magic) == FAT_CIGAM) {
392 swapped_ = !swapped_;
393 goto fat;
394 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
395 fat_header_ = NULL;
396 mach_headers_.push_back(MachHeader(base, size));
397 } else fat: {
398 size_t fat_narch = Swap(fat_header_->nfat_arch);
399 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
400 size_t arch;
401 for (arch = 0; arch != fat_narch; ++arch) {
402 uint32_t arch_offset = Swap(fat_arch->offset);
403 uint32_t arch_size = Swap(fat_arch->size);
404 mach_headers_.push_back(MachHeader((uint8_t *) base + arch_offset, size));
405 ++fat_arch;
406 }
407 }
408 }
409
410 std::vector<MachHeader> &GetMachHeaders() {
411 return mach_headers_;
412 }
413};
414
415FatHeader Map(const char *path) {
416 size_t size;
417 void *base(map(path, 0, _not(size_t), &size, false));
418 return FatHeader(base, size);
419}
420
6e83315b
JF
421template <typename Target_>
422class Pointer {
423 private:
0a033524 424 const MachHeader *framework_;
6e83315b
JF
425 const Target_ *pointer_;
426
427 public:
0a033524 428 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
429 framework_(framework),
430 pointer_(pointer)
431 {
432 }
433
434 operator const Target_ *() const {
435 return pointer_;
436 }
437
438 const Target_ *operator ->() const {
439 return pointer_;
440 }
441
442 Pointer<Target_> &operator ++() {
443 ++pointer_;
444 return *this;
445 }
446
447 template <typename Value_>
448 Value_ Swap(Value_ value) {
449 return framework_->Swap(value);
450 }
a362a82f
JF
451};
452
645f8f12
JF
453#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
454#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
455#define CSMAGIC_ENTITLEMENTS uint32_t(0xfade7171)
c05d9758 456
645f8f12
JF
457#define CSSLOT_CODEDIRECTORY uint32_t(0)
458#define CSSLOT_REQUIREMENTS uint32_t(2)
459#define CSSLOT_ENTITLEMENTS uint32_t(5)
fdb119ef
JF
460
461struct BlobIndex {
462 uint32_t type;
463 uint32_t offset;
c05d9758 464} _packed;
fdb119ef 465
c05d9758 466struct Blob {
fdb119ef
JF
467 uint32_t magic;
468 uint32_t length;
c05d9758
JF
469} _packed;
470
471struct SuperBlob {
472 struct Blob blob;
fdb119ef
JF
473 uint32_t count;
474 struct BlobIndex index[];
c05d9758 475} _packed;
fdb119ef
JF
476
477struct CodeDirectory {
c05d9758 478 struct Blob blob;
fdb119ef
JF
479 uint32_t version;
480 uint32_t flags;
481 uint32_t hashOffset;
482 uint32_t identOffset;
483 uint32_t nSpecialSlots;
484 uint32_t nCodeSlots;
485 uint32_t codeLimit;
486 uint8_t hashSize;
487 uint8_t hashType;
488 uint8_t spare1;
489 uint8_t pageSize;
490 uint32_t spare2;
c05d9758 491} _packed;
fdb119ef 492
a362a82f
JF
493extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
494
fdb119ef
JF
495void sha1(uint8_t *hash, uint8_t *data, size_t size) {
496 SHA1Context context;
497 SHA1Reset(&context);
498 SHA1Input(&context, data, size);
499 SHA1Result(&context, hash);
500}
501
0a033524
JF
502struct CodesignAllocation {
503 uint32_t type_;
504 uint16_t subtype_;
505 size_t size_;
506
507 CodesignAllocation(uint32_t type, uint16_t subtype, size_t size) :
508 type_(type),
509 subtype_(subtype),
510 size_(size)
511 {
512 }
513};
514
a362a82f 515int main(int argc, const char *argv[]) {
5525a5a7
JF
516 union {
517 uint16_t word;
518 uint8_t byte[2];
519 } endian = {1};
520
521 little_ = endian.byte[0];
522
a362a82f
JF
523 bool flag_R(false);
524 bool flag_t(false);
525 bool flag_p(false);
526 bool flag_u(false);
9c83be90 527 bool flag_e(false);
a362a82f
JF
528
529 bool flag_T(false);
20c5f1e8 530
fdb119ef 531 bool flag_S(false);
20c5f1e8 532 bool flag_s(false);
a362a82f
JF
533
534 bool timeh(false);
535 uint32_t timev(0);
536
c05d9758
JF
537 const void *xmld(NULL);
538 size_t xmls(0);
539
6e83315b
JF
540 uintptr_t noffset(_not(uintptr_t));
541 uintptr_t woffset(_not(uintptr_t));
542
a362a82f
JF
543 std::vector<std::string> files;
544
a960f392
JF
545 if (argc == 1) {
546 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 547 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
548 fprintf(stderr, " %s -S cat\n", argv[0]);
549 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
550 exit(0);
551 }
552
a362a82f
JF
553 for (int argi(1); argi != argc; ++argi)
554 if (argv[argi][0] != '-')
555 files.push_back(argv[argi]);
556 else switch (argv[argi][1]) {
557 case 'R': flag_R = true; break;
558 case 't': flag_t = true; break;
559 case 'u': flag_u = true; break;
560 case 'p': flag_p = true; break;
9c83be90 561 case 'e': flag_e = true; break;
c05d9758 562
20c5f1e8
JF
563 case 's':
564 _assert(!flag_S);
565 flag_s = true;
566 break;
567
c05d9758 568 case 'S':
20c5f1e8 569 _assert(!flag_s);
c05d9758
JF
570 flag_S = true;
571 if (argv[argi][2] != '\0') {
572 const char *xml = argv[argi] + 2;
573 xmld = map(xml, 0, _not(size_t), &xmls, true);
574 }
575 break;
a362a82f
JF
576
577 case 'T': {
578 flag_T = true;
579 if (argv[argi][2] == '-')
580 timeh = true;
581 else {
582 char *arge;
583 timev = strtoul(argv[argi] + 2, &arge, 0);
584 _assert(arge == argv[argi] + strlen(argv[argi]));
585 }
586 } break;
587
6e83315b
JF
588 case 'n': {
589 char *arge;
590 noffset = strtoul(argv[argi] + 2, &arge, 0);
591 _assert(arge == argv[argi] + strlen(argv[argi]));
592 } break;
593
594 case 'w': {
595 char *arge;
596 woffset = strtoul(argv[argi] + 2, &arge, 0);
597 _assert(arge == argv[argi] + strlen(argv[argi]));
598 } break;
599
a362a82f
JF
600 default:
601 goto usage;
602 break;
603 }
604
605 if (files.empty()) usage: {
606 exit(0);
607 }
608
609 size_t filei(0), filee(0);
610 _foreach (file, files) try {
0a033524 611 const char *path(file.c_str());
fdb119ef
JF
612 const char *base = strrchr(path, '/');
613 char *temp(NULL), *dir;
614
615 if (base != NULL)
b8187ac7 616 dir = strndup_(path, base++ - path + 1);
fdb119ef
JF
617 else {
618 dir = strdup("");
619 base = path;
620 }
621
622 if (flag_S) {
623 asprintf(&temp, "%s.%s.cs", dir, base);
624 const char *allocate = getenv("CODESIGN_ALLOCATE");
625 if (allocate == NULL)
626 allocate = "codesign_allocate";
627
0a033524
JF
628 std::vector<CodesignAllocation> allocations; {
629 FatHeader fat_header(Map(path));
630 _foreach (mach_header, fat_header.GetMachHeaders()) {
631 mach_header->flags = mach_header.Swap(mach_header.Swap(mach_header->flags) | MH_DYLDLINK);
632
633 size_t size(_not(size_t)); {
634 _foreach (load_command, mach_header.GetLoadCommands()) {
635 uint32_t cmd(mach_header.Swap(load_command->cmd));
636 if (cmd == LC_CODE_SIGNATURE) {
637 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
638 size = mach_header.Swap(signature->dataoff);
639 _assert(size < mach_header.GetSize());
640 break;
641 }
642 }
643
644 if (size == _not(size_t))
645 size = mach_header.GetSize();
afbb7c8e 646 }
afbb7c8e 647
0a033524 648 allocations.push_back(CodesignAllocation(mach_header.GetCPUType(), mach_header.GetCPUSubtype(), size));
afbb7c8e 649 }
fdb119ef
JF
650 }
651
652 pid_t pid = fork();
653 _syscall(pid);
654 if (pid == 0) {
0a033524
JF
655 // XXX: this leaks memory, but it doesn't really matter
656 std::vector<const char *> args;
657 char *arg;
658
659 args.push_back(allocate);
660
661 args.push_back("-i");
662 args.push_back(path);
663
664 _foreach (allocation, allocations) {
665 args.push_back("-A");
666
667 asprintf(&arg, "%u", allocation.type_);
668 args.push_back(arg);
669
670 asprintf(&arg, "%u", allocation.subtype_);
671 args.push_back(arg);
672
673 size_t alloc(0);
674 alloc += sizeof(struct SuperBlob);
675 uint32_t special(0);
676
677 special = std::max(special, CSSLOT_CODEDIRECTORY);
678 alloc += sizeof(struct BlobIndex);
679 alloc += sizeof(struct CodeDirectory);
680 alloc += strlen(base) + 1;
681
682 special = std::max(special, CSSLOT_REQUIREMENTS);
683 alloc += sizeof(struct BlobIndex);
684 alloc += 0xc;
685
686 if (xmld != NULL) {
687 special = std::max(special, CSSLOT_ENTITLEMENTS);
688 alloc += sizeof(struct BlobIndex);
689 alloc += sizeof(struct Blob);
690 alloc += xmls;
691 }
692
693 size_t normal((allocation.size_ + 0x1000 - 1) / 0x1000);
694 alloc += (special + normal) * 0x14;
695
696 alloc += 15;
697 alloc /= 16;
698 alloc *= 16;
699
700 asprintf(&arg, "%u", alloc);
701 args.push_back(arg);
702 }
703
704 args.push_back("-o");
705 args.push_back(temp);
706
707 args.push_back(NULL);
708
709 if (false) {
710 printf("run:");
711 _foreach (arg, args)
712 printf(" %s", arg);
713 printf("\n");
714 }
715
716 execvp(allocate, (char **) &args[0]);
fdb119ef
JF
717 _assert(false);
718 }
719
720 int status;
721 _syscall(waitpid(pid, &status, 0));
722 _assert(WIFEXITED(status));
723 _assert(WEXITSTATUS(status) == 0);
724 }
725
0a033524
JF
726 if (flag_p)
727 printf("path%zu='%s'\n", filei, file.c_str());
728
729 FatHeader fat_header(Map(temp == NULL ? path : temp));
fdb119ef 730 struct linkedit_data_command *signature(NULL);
a362a82f 731
0a033524
JF
732 _foreach (mach_header, fat_header.GetMachHeaders()) {
733 if (woffset != _not(uintptr_t)) {
734 Pointer<uint32_t> wvalue(mach_header.GetPointer<uint32_t>(woffset));
735 if (wvalue == NULL)
736 printf("(null) %p\n", reinterpret_cast<void *>(woffset));
737 else
738 printf("0x%.08x\n", *wvalue);
739 }
6e83315b 740
0a033524
JF
741 if (noffset != _not(uintptr_t))
742 printf("%s\n", &*mach_header.GetPointer<char>(noffset));
743
744 _foreach (load_command, mach_header.GetLoadCommands()) {
745 uint32_t cmd(mach_header.Swap(load_command->cmd));
746
747 if (flag_R && cmd == LC_REEXPORT_DYLIB)
748 load_command->cmd = mach_header.Swap(LC_LOAD_DYLIB);
749 else if (cmd == LC_CODE_SIGNATURE)
750 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
751 else if (cmd == LC_UUID) {
752 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(load_command));
753
754 if (flag_u) {
755 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
756 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
757 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
758 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
759 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
760 );
761 }
762 } else if (cmd == LC_ID_DYLIB) {
763 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 764
0a033524
JF
765 if (flag_t)
766 printf("time%zu=0x%.8x\n", filei, mach_header.Swap(dylib_command->dylib.timestamp));
a362a82f 767
0a033524
JF
768 if (flag_T) {
769 uint32_t timed;
a362a82f 770
0a033524
JF
771 if (!timeh)
772 timed = timev;
773 else {
774 dylib_command->dylib.timestamp = 0;
775 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
776 }
a362a82f 777
0a033524
JF
778 dylib_command->dylib.timestamp = mach_header.Swap(timed);
779 }
a362a82f
JF
780 }
781 }
a362a82f 782
0a033524
JF
783 if (flag_e) {
784 _assert(signature != NULL);
9c83be90 785
0a033524
JF
786 uint32_t data = mach_header.Swap(signature->dataoff);
787 uint32_t size = mach_header.Swap(signature->datasize);
9c83be90 788
0a033524
JF
789 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
790 uint8_t *blob = top + data;
791 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 792
0a033524
JF
793 for (size_t index(0); index != Swap(super->count); ++index)
794 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
795 uint32_t begin = Swap(super->index[index].offset);
796 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
797 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
798 }
799 }
9c83be90 800
0a033524
JF
801 if (flag_s) {
802 _assert(signature != NULL);
20c5f1e8 803
0a033524
JF
804 uint32_t data = mach_header.Swap(signature->dataoff);
805 uint32_t size = mach_header.Swap(signature->datasize);
20c5f1e8 806
0a033524
JF
807 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
808 uint8_t *blob = top + data;
809 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 810
0a033524
JF
811 for (size_t index(0); index != Swap(super->count); ++index)
812 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
813 uint32_t begin = Swap(super->index[index].offset);
814 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 815
0a033524
JF
816 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + begin + Swap(directory->hashOffset));
817 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 818
0a033524
JF
819 if (pages != 1)
820 for (size_t i = 0; i != pages - 1; ++i)
821 sha1(hashes[i], top + 0x1000 * i, 0x1000);
822 if (pages != 0)
823 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
824 }
825 }
20c5f1e8 826
0a033524
JF
827 if (flag_S) {
828 _assert(signature != NULL);
fdb119ef 829
0a033524
JF
830 uint32_t data = mach_header.Swap(signature->dataoff);
831 uint32_t size = mach_header.Swap(signature->datasize);
fdb119ef 832
0a033524
JF
833 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
834 uint8_t *blob = top + data;
835 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
836 super->blob.magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
fdb119ef 837
0a033524
JF
838 uint32_t count = xmld == NULL ? 2 : 3;
839 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
fdb119ef 840
0a033524
JF
841 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
842 super->index[0].offset = Swap(offset);
fdb119ef 843
0a033524
JF
844 uint32_t begin = offset;
845 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
846 offset += sizeof(struct CodeDirectory);
fdb119ef 847
0a033524
JF
848 directory->blob.magic = Swap(CSMAGIC_CODEDIRECTORY);
849 directory->version = Swap(uint32_t(0x00020001));
850 directory->flags = Swap(uint32_t(0));
851 directory->codeLimit = Swap(data);
852 directory->hashSize = 0x14;
853 directory->hashType = 0x01;
854 directory->spare1 = 0x00;
855 directory->pageSize = 0x0c;
856 directory->spare2 = Swap(uint32_t(0));
fdb119ef 857
0a033524
JF
858 directory->identOffset = Swap(offset - begin);
859 strcpy(reinterpret_cast<char *>(blob + offset), base);
860 offset += strlen(base) + 1;
fdb119ef 861
0a033524
JF
862 uint32_t special = xmld == NULL ? CSSLOT_REQUIREMENTS : CSSLOT_ENTITLEMENTS;
863 directory->nSpecialSlots = Swap(special);
20c5f1e8 864
0a033524
JF
865 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
866 memset(hashes, 0, sizeof(*hashes) * special);
20c5f1e8 867
0a033524
JF
868 offset += sizeof(*hashes) * special;
869 hashes += special;
fdb119ef 870
0a033524
JF
871 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
872 directory->nCodeSlots = Swap(pages);
fdb119ef 873
0a033524
JF
874 if (pages != 1)
875 for (size_t i = 0; i != pages - 1; ++i)
876 sha1(hashes[i], top + 0x1000 * i, 0x1000);
877 if (pages != 0)
878 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
fdb119ef 879
0a033524
JF
880 directory->hashOffset = Swap(offset - begin);
881 offset += sizeof(*hashes) * pages;
882 directory->blob.length = Swap(offset - begin);
fdb119ef 883
0a033524
JF
884 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
885 super->index[1].offset = Swap(offset);
afbb7c8e 886
0a033524
JF
887 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
888 offset += 0xc;
afbb7c8e 889
0a033524
JF
890 if (xmld != NULL) {
891 super->index[2].type = Swap(CSSLOT_ENTITLEMENTS);
892 super->index[2].offset = Swap(offset);
c05d9758 893
0a033524
JF
894 uint32_t begin = offset;
895 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
896 offset += sizeof(struct Blob);
c05d9758 897
0a033524
JF
898 memcpy(blob + offset, xmld, xmls);
899 offset += xmls;
c05d9758 900
0a033524
JF
901 entitlements->magic = Swap(CSMAGIC_ENTITLEMENTS);
902 entitlements->length = Swap(offset - begin);
903 }
c05d9758 904
0a033524
JF
905 for (size_t index(0); index != count; ++index) {
906 uint32_t type = Swap(super->index[index].type);
907 if (type != 0 && type <= special) {
908 uint32_t offset = Swap(super->index[index].offset);
909 struct Blob *local = (struct Blob *) (blob + offset);
910 sha1((uint8_t *) (hashes - type), (uint8_t *) local, Swap(local->length));
911 }
20c5f1e8 912 }
20c5f1e8 913
0a033524
JF
914 super->count = Swap(count);
915 super->blob.length = Swap(offset);
c05d9758 916
0a033524
JF
917 if (offset > size) {
918 fprintf(stderr, "offset (%u) > size (%u)\n", offset, size);
919 _assert(false);
920 } //else fprintf(stderr, "offset (%zu) <= size (%zu)\n", offset, size);
fdb119ef 921
0a033524
JF
922 memset(blob + offset, 0, size - offset);
923 }
fdb119ef
JF
924 }
925
122621c5 926 if (flag_S) {
0a033524
JF
927 uint8_t *top = reinterpret_cast<uint8_t *>(fat_header.GetBase());
928 size_t size = fat_header.GetSize();
122621c5
JF
929
930 char *copy;
931 asprintf(&copy, "%s.%s.cp", dir, base);
932 FILE *file = fopen(copy, "w+");
933 size_t writ = fwrite(top, 1, size, file);
934 _assert(writ == size);
935 fclose(file);
936
937 _syscall(unlink(temp));
938 free(temp);
939 temp = copy;
940 }
941
0a033524 942 if (temp != NULL) {
31ad673b
JF
943 struct stat info;
944 _syscall(stat(path, &info));
945 _syscall(chown(temp, info.st_uid, info.st_gid));
946 _syscall(chmod(temp, info.st_mode));
fdb119ef
JF
947 _syscall(unlink(path));
948 _syscall(rename(temp, path));
949 free(temp);
950 }
951
952 free(dir);
a362a82f
JF
953 ++filei;
954 } catch (const char *) {
955 ++filee;
956 ++filei;
957 }
958
959 return filee;
960}