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