]> git.saurik.com Git - ldid.git/blob - ldid.cpp
d38e6b3f3a5fe25698e060a0abed8a376a4711ab
[ldid.git] / ldid.cpp
1 /* JocStrap - Java/Objective-C Bootstrap
2 * Copyright (C) 2007 Jay Freeman (saurik)
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"
39 #include "minimal/mapping.h"
40
41 #include "sha1.h"
42
43 #include <cstring>
44 #include <string>
45 #include <vector>
46
47 #include <sys/wait.h>
48
49 struct fat_header {
50 uint32_t magic;
51 uint32_t nfat_arch;
52 };
53
54 #define FAT_MAGIC 0xcafebabe
55 #define FAT_CIGAM 0xbebafeca
56
57 struct fat_arch {
58 uint32_t cputype;
59 uint32_t cpusubtype;
60 uint32_t offset;
61 uint32_t size;
62 uint32_t align;
63 };
64
65 struct mach_header {
66 uint32_t magic;
67 uint32_t cputype;
68 uint32_t cpusubtype;
69 uint32_t filetype;
70 uint32_t ncmds;
71 uint32_t sizeofcmds;
72 uint32_t flags;
73 };
74
75 #define MH_MAGIC 0xfeedface
76 #define MH_CIGAM 0xcefaedfe
77
78 #define MH_EXECUTE 0x2
79 #define MH_DYLIB 0x6
80 #define MH_BUNDLE 0x8
81
82 struct load_command {
83 uint32_t cmd;
84 uint32_t cmdsize;
85 };
86
87 #define LC_REQ_DYLD 0x80000000
88
89 #define LC_LOAD_DYLIB 0x0c
90 #define LC_ID_DYLIB 0x0d
91 #define LC_UUID 0x1b
92 #define LC_CODE_SIGNATURE 0x1d
93 #define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD)
94
95 struct dylib {
96 uint32_t name;
97 uint32_t timestamp;
98 uint32_t current_version;
99 uint32_t compatibility_version;
100 };
101
102 struct dylib_command {
103 uint32_t cmd;
104 uint32_t cmdsize;
105 struct dylib dylib;
106 };
107
108 struct uuid_command {
109 uint32_t cmd;
110 uint32_t cmdsize;
111 uint8_t uuid[16];
112 };
113
114 struct linkedit_data_command {
115 uint32_t cmd;
116 uint32_t cmdsize;
117 uint32_t dataoff;
118 uint32_t datasize;
119 };
120
121 uint16_t Swap_(uint16_t value) {
122 return
123 ((value >> 8) & 0x00ff) |
124 ((value << 8) & 0xff00);
125 }
126
127 uint32_t Swap_(uint32_t value) {
128 value = ((value >> 8) & 0x00ff00ff) |
129 ((value << 8) & 0xff00ff00);
130 value = ((value >> 16) & 0x0000ffff) |
131 ((value << 16) & 0xffff0000);
132 return value;
133 }
134
135 int16_t Swap_(int16_t value) {
136 return Swap_(static_cast<uint16_t>(value));
137 }
138
139 int32_t Swap_(int32_t value) {
140 return Swap_(static_cast<uint32_t>(value));
141 }
142
143 uint16_t Swap(uint16_t value) {
144 return true ? Swap_(value) : value;
145 }
146
147 uint32_t Swap(uint32_t value) {
148 return true ? Swap_(value) : value;
149 }
150
151 int16_t Swap(int16_t value) {
152 return Swap(static_cast<uint16_t>(value));
153 }
154
155 int32_t Swap(int32_t value) {
156 return Swap(static_cast<uint32_t>(value));
157 }
158
159 class Framework {
160 private:
161 void *base_;
162 size_t size_;
163 mach_header *mach_header_;
164 bool swapped_;
165
166 public:
167 uint16_t Swap(uint16_t value) const {
168 return swapped_ ? Swap_(value) : value;
169 }
170
171 uint32_t Swap(uint32_t value) const {
172 return swapped_ ? Swap_(value) : value;
173 }
174
175 int16_t Swap(int16_t value) const {
176 return Swap(static_cast<uint16_t>(value));
177 }
178
179 int32_t Swap(int32_t value) const {
180 return Swap(static_cast<uint32_t>(value));
181 }
182
183 Framework(const char *framework_path) :
184 swapped_(false)
185 {
186 base_ = map(framework_path, 0, _not(size_t), &size_, false);
187 fat_header *fat_header = reinterpret_cast<struct fat_header *>(base_);
188
189 if (Swap(fat_header->magic) == FAT_CIGAM) {
190 swapped_ = !swapped_;
191 goto fat;
192 } else if (Swap(fat_header->magic) != FAT_MAGIC)
193 mach_header_ = (mach_header *) base_;
194 else fat: {
195 size_t fat_narch = Swap(fat_header->nfat_arch);
196 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header + 1);
197 size_t arch;
198 for (arch = 0; arch != fat_narch; ++arch) {
199 uint32_t arch_offset = Swap(fat_arch->offset);
200 mach_header_ = (mach_header *) ((uint8_t *) base_ + arch_offset);
201 goto found;
202 ++fat_arch;
203 }
204
205 _assert(false);
206 }
207
208 found:
209 if (Swap(mach_header_->magic) == MH_CIGAM)
210 swapped_ = !swapped_;
211 else _assert(Swap(mach_header_->magic) == MH_MAGIC);
212
213 _assert(
214 Swap(mach_header_->filetype) == MH_EXECUTE ||
215 Swap(mach_header_->filetype) == MH_DYLIB ||
216 Swap(mach_header_->filetype) == MH_BUNDLE
217 );
218 }
219
220 struct mach_header *operator ->() const {
221 return mach_header_;
222 }
223
224 void *GetBase() {
225 return base_;
226 }
227
228 size_t GetSize() {
229 return size_;
230 }
231
232 std::vector<struct load_command *> GetLoadCommands() {
233 std::vector<struct load_command *> load_commands;
234
235 struct load_command *load_command = reinterpret_cast<struct load_command *>(mach_header_ + 1);
236 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
237 load_commands.push_back(load_command);
238 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
239 }
240
241 return load_commands;
242 }
243 };
244
245 #define CSMAGIC_CODEDIRECTORY 0xfade0c02
246 #define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
247 #define CSSLOT_CODEDIRECTORY 0
248 #define CSSLOT_REQUIREMENTS 2
249
250 struct BlobIndex {
251 uint32_t type;
252 uint32_t offset;
253 };
254
255 struct SuperBlob {
256 uint32_t magic;
257 uint32_t length;
258 uint32_t count;
259 struct BlobIndex index[];
260 };
261
262 struct CodeDirectory {
263 uint32_t magic;
264 uint32_t length;
265 uint32_t version;
266 uint32_t flags;
267 uint32_t hashOffset;
268 uint32_t identOffset;
269 uint32_t nSpecialSlots;
270 uint32_t nCodeSlots;
271 uint32_t codeLimit;
272 uint8_t hashSize;
273 uint8_t hashType;
274 uint8_t spare1;
275 uint8_t pageSize;
276 uint32_t spare2;
277 };
278
279 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
280
281 #define CODESIGN_ALLOCATE "arm-apple-darwin9-codesign_allocate"
282
283 void sha1(uint8_t *hash, uint8_t *data, size_t size) {
284 SHA1Context context;
285 SHA1Reset(&context);
286 SHA1Input(&context, data, size);
287 SHA1Result(&context, hash);
288 }
289
290 int main(int argc, const char *argv[]) {
291 bool flag_R(false);
292 bool flag_t(false);
293 bool flag_p(false);
294 bool flag_u(false);
295
296 bool flag_T(false);
297 bool flag_S(false);
298
299 bool timeh(false);
300 uint32_t timev(0);
301
302 std::vector<std::string> files;
303
304 _assert(argc != 0);
305 for (int argi(1); argi != argc; ++argi)
306 if (argv[argi][0] != '-')
307 files.push_back(argv[argi]);
308 else switch (argv[argi][1]) {
309 case 'R': flag_R = true; break;
310 case 't': flag_t = true; break;
311 case 'u': flag_u = true; break;
312 case 'p': flag_p = true; break;
313 case 'S': flag_S = true; break;
314
315 case 'T': {
316 flag_T = true;
317 if (argv[argi][2] == '-')
318 timeh = true;
319 else {
320 char *arge;
321 timev = strtoul(argv[argi] + 2, &arge, 0);
322 _assert(arge == argv[argi] + strlen(argv[argi]));
323 }
324 } break;
325
326 default:
327 goto usage;
328 break;
329 }
330
331 if (files.empty()) usage: {
332 exit(0);
333 }
334
335 size_t filei(0), filee(0);
336 _foreach (file, files) try {
337 const char *path(file->c_str());
338 const char *base = strrchr(path, '/');
339 char *temp(NULL), *dir;
340
341 if (base != NULL)
342 dir = strndup(path, base++ - path + 1);
343 else {
344 dir = strdup("");
345 base = path;
346 }
347
348 if (flag_S) {
349 asprintf(&temp, "%s.%s.cs", dir, base);
350 const char *allocate = getenv("CODESIGN_ALLOCATE");
351 if (allocate == NULL)
352 allocate = "codesign_allocate";
353
354 size_t size = _not(size_t);
355 const char *arch; {
356 Framework framework(path);
357 _foreach (load_command, framework.GetLoadCommands()) {
358 uint32_t cmd(framework.Swap((*load_command)->cmd));
359 if (cmd == LC_CODE_SIGNATURE) {
360 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(*load_command);
361 size = framework.Swap(signature->dataoff);
362 _assert(size < framework.GetSize());
363 break;
364 }
365 }
366
367 if (size == _not(size_t))
368 size = framework.GetSize();
369
370 switch (framework->cputype) {
371 case 12: switch (framework->cpusubtype) {
372 case 0: arch = "arm"; break;
373 case 6: arch = "armv6"; break;
374 default: arch = NULL; break;
375 } break;
376
377 default: arch = NULL; break;
378 }
379 }
380
381 _assert(arch != NULL);
382
383 pid_t pid = fork();
384 _syscall(pid);
385 if (pid == 0) {
386 char *ssize;
387 asprintf(&ssize, "%u", (sizeof(struct SuperBlob) + 2 * sizeof(struct BlobIndex) + sizeof(struct CodeDirectory) + strlen(base) + 1 + (size + 0x1000 - 1) / 0x1000 * 0x14 + 0xc + 15) / 16 * 16);
388 execlp(allocate, allocate, "-i", path, "-a", arch, ssize, "-o", temp, NULL);
389 _assert(false);
390 }
391
392 int status;
393 _syscall(waitpid(pid, &status, 0));
394 _assert(WIFEXITED(status));
395 _assert(WEXITSTATUS(status) == 0);
396 }
397
398 Framework framework(temp == NULL ? path : temp);
399 struct linkedit_data_command *signature(NULL);
400
401 if (flag_p)
402 printf("path%zu='%s'\n", filei, file->c_str());
403
404 _foreach (load_command, framework.GetLoadCommands()) {
405 uint32_t cmd(framework.Swap((*load_command)->cmd));
406
407 if (flag_R && cmd == LC_REEXPORT_DYLIB)
408 (*load_command)->cmd = framework.Swap(LC_LOAD_DYLIB);
409 else if (cmd == LC_CODE_SIGNATURE)
410 signature = reinterpret_cast<struct linkedit_data_command *>(*load_command);
411 else if (cmd == LC_UUID) {
412 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(*load_command));
413
414 if (flag_u) {
415 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
416 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
417 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
418 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
419 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
420 );
421 }
422 } else if (cmd == LC_ID_DYLIB) {
423 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(*load_command));
424
425 if (flag_t)
426 printf("time%zu=0x%.8x\n", filei, framework.Swap(dylib_command->dylib.timestamp));
427
428 if (flag_T) {
429 uint32_t timed;
430
431 if (!timeh)
432 timed = timev;
433 else {
434 dylib_command->dylib.timestamp = 0;
435 timed = hash(reinterpret_cast<uint8_t *>(framework.GetBase()), framework.GetSize(), timev);
436 }
437
438 dylib_command->dylib.timestamp = framework.Swap(timed);
439 }
440 }
441 }
442
443 if (flag_S) {
444 _assert(signature != NULL);
445
446 uint32_t data = framework.Swap(signature->dataoff);
447 uint32_t size = framework.Swap(signature->datasize);
448
449 uint8_t *top = reinterpret_cast<uint8_t *>(framework.GetBase());
450 uint8_t *blob = top + data;
451 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
452 super->magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
453
454 uint32_t count = 2;
455 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
456
457 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
458 super->index[0].offset = Swap(offset);
459
460 uint32_t begin = offset;
461 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
462 offset += sizeof(struct CodeDirectory);
463
464 directory->magic = Swap(CSMAGIC_CODEDIRECTORY);
465 directory->version = Swap(0x00020001);
466 directory->flags = Swap(0);
467 directory->codeLimit = Swap(data);
468 directory->hashSize = 0x14;
469 directory->hashType = 0x01;
470 directory->spare1 = 0x00;
471 directory->pageSize = 0x0c;
472 directory->spare2 = Swap(0);
473
474 directory->identOffset = Swap(offset - begin);
475 strcpy(reinterpret_cast<char *>(blob + offset), base);
476 offset += strlen(base) + 1;
477
478 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
479 uint32_t special = 0;
480
481 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
482 directory->nSpecialSlots = Swap(special);
483 directory->nCodeSlots = Swap(pages);
484
485 if (pages != 1)
486 for (size_t i = 0; i != pages - 1; ++i)
487 sha1(hashes[special + i], top + 0x1000 * i, 0x1000);
488 if (pages != 0)
489 sha1(hashes[special + pages - 1], top + 0x1000 * (pages - 1), data % 0x1000);
490
491 directory->hashOffset = Swap(offset - begin);
492 offset += sizeof(*hashes) * (special + pages);
493 directory->length = Swap(offset - begin);
494
495 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
496 super->index[1].offset = Swap(offset);
497
498 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
499 offset += 0xc;
500
501 super->count = Swap(count);
502 super->length = Swap(offset);
503
504 _assert(offset <= size);
505 memset(blob + offset, 0, size - offset);
506 }
507
508 if (temp) {
509 _syscall(unlink(path));
510 _syscall(rename(temp, path));
511 free(temp);
512 }
513
514 free(dir);
515 ++filei;
516 } catch (const char *) {
517 ++filee;
518 ++filei;
519 }
520
521 return filee;
522 }