]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoaderMachOCompressed.cpp
dyld-519.2.1.tar.gz
[apple/dyld.git] / src / ImageLoaderMachOCompressed.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2008 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #if __arm__ || __arm64__
27 #include <System/sys/mman.h>
28 #else
29 #include <sys/mman.h>
30 #endif
31 #include <string.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/fcntl.h>
36 #include <sys/stat.h>
37 #include <sys/param.h>
38 #include <sys/sysctl.h>
39 #include <mach/mach.h>
40 #include <mach/thread_status.h>
41 #include <mach-o/loader.h>
42 #include "ImageLoaderMachOCompressed.h"
43 #include "mach-o/dyld_images.h"
44
45 #ifndef EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
46 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
47 #endif
48
49 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
50 #if __LP64__
51 #define RELOC_SIZE 3
52 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
53 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
54 struct macho_segment_command : public segment_command_64 {};
55 struct macho_section : public section_64 {};
56 struct macho_routines_command : public routines_command_64 {};
57 #else
58 #define RELOC_SIZE 2
59 #define LC_SEGMENT_COMMAND LC_SEGMENT
60 #define LC_ROUTINES_COMMAND LC_ROUTINES
61 struct macho_segment_command : public segment_command {};
62 struct macho_section : public section {};
63 struct macho_routines_command : public routines_command {};
64 #endif
65
66 #if __arm__ || __arm64__
67 bool ImageLoaderMachOCompressed::sVmAccountingDisabled = false;
68 bool ImageLoaderMachOCompressed::sVmAccountingSuspended = false;
69 #endif
70
71
72
73 // create image for main executable
74 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header* mh, uintptr_t slide, const char* path,
75 unsigned int segCount, unsigned int libCount, const LinkContext& context)
76 {
77 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, path, segCount, libCount);
78
79 // set slide for PIE programs
80 image->setSlide(slide);
81
82 // for PIE record end of program, to know where to start loading dylibs
83 if ( slide != 0 )
84 fgNextPIEDylibAddress = (uintptr_t)image->getEnd();
85
86 image->disableCoverageCheck();
87 image->instantiateFinish(context);
88 image->setMapped(context);
89
90 if ( context.verboseMapping ) {
91 dyld::log("dyld: Main executable mapped %s\n", path);
92 for(unsigned int i=0, e=image->segmentCount(); i < e; ++i) {
93 const char* name = image->segName(i);
94 if ( (strcmp(name, "__PAGEZERO") == 0) || (strcmp(name, "__UNIXSTACK") == 0) )
95 dyld::log("%18s at 0x%08lX->0x%08lX\n", name, image->segPreferredLoadAddress(i), image->segPreferredLoadAddress(i)+image->segSize(i));
96 else
97 dyld::log("%18s at 0x%08lX->0x%08lX\n", name, image->segActualLoadAddress(i), image->segActualEndAddress(i));
98 }
99 }
100
101 return image;
102 }
103
104 // create image by mapping in a mach-o file
105 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromFile(const char* path, int fd, const uint8_t* fileData, size_t lenFileData,
106 uint64_t offsetInFat, uint64_t lenInFat, const struct stat& info,
107 unsigned int segCount, unsigned int libCount,
108 const struct linkedit_data_command* codeSigCmd,
109 const struct encryption_info_command* encryptCmd,
110 const LinkContext& context)
111 {
112 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart((macho_header*)fileData, path, segCount, libCount);
113
114 try {
115 // record info about file
116 image->setFileInfo(info.st_dev, info.st_ino, info.st_mtime);
117
118 // if this image is code signed, let kernel validate signature before mapping any pages from image
119 image->loadCodeSignature(codeSigCmd, fd, offsetInFat, context);
120
121 // Validate that first data we read with pread actually matches with code signature
122 image->validateFirstPages(codeSigCmd, fd, fileData, lenFileData, offsetInFat, context);
123
124 // mmap segments
125 image->mapSegments(fd, offsetInFat, lenInFat, info.st_size, context);
126
127 // if framework is FairPlay encrypted, register with kernel
128 image->registerEncryption(encryptCmd, context);
129
130 // probe to see if code signed correctly
131 image->crashIfInvalidCodeSignature();
132
133 // finish construction
134 image->instantiateFinish(context);
135
136 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
137 const char* installName = image->getInstallPath();
138 if ( (installName != NULL) && (strcmp(installName, path) == 0) && (path[0] == '/') )
139 image->setPathUnowned(installName);
140 #if __MAC_OS_X_VERSION_MIN_REQUIRED
141 // <rdar://problem/6563887> app crashes when libSystem cannot be found
142 else if ( (installName != NULL) && (strcmp(path, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName, "/usr/lib/libSystem.B.dylib") == 0) )
143 image->setPathUnowned("/usr/lib/libSystem.B.dylib");
144 #endif
145 else if ( (path[0] != '/') || (strstr(path, "../") != NULL) ) {
146 // rdar://problem/10733082 Fix up @rpath based paths during introspection
147 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
148 char realPath[MAXPATHLEN];
149 if ( fcntl(fd, F_GETPATH, realPath) == 0 )
150 image->setPaths(path, realPath);
151 else
152 image->setPath(path);
153 }
154 else
155 image->setPath(path);
156
157 // make sure path is stable before recording in dyld_all_image_infos
158 image->setMapped(context);
159
160 // dylibs with thread local variables cannot be unloaded because there is no way to clean up all threads
161 if ( image->machHeader()->flags & MH_HAS_TLV_DESCRIPTORS )
162 image->setNeverUnload();
163
164 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
165 // don't do this on prebound images or if prefetching is disabled
166 if ( !context.preFetchDisabled && !image->isPrebindable()) {
167 image->preFetchDATA(fd, offsetInFat, context);
168 image->markSequentialLINKEDIT(context);
169 }
170 }
171 catch (...) {
172 // ImageLoader::setMapped() can throw an exception to block loading of image
173 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
174 delete image;
175 throw;
176 }
177
178 return image;
179 }
180
181 // create image by using cached mach-o file
182 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header* mh, const char* path, long slide,
183 const struct stat& info, unsigned int segCount,
184 unsigned int libCount, const LinkContext& context)
185 {
186 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, path, segCount, libCount);
187 try {
188 // record info about file
189 image->setFileInfo(info.st_dev, info.st_ino, info.st_mtime);
190
191 // remember this is from shared cache and cannot be unloaded
192 image->fInSharedCache = true;
193 image->setNeverUnload();
194 image->setSlide(slide);
195 image->disableCoverageCheck();
196
197 // segments already mapped in cache
198 if ( context.verboseMapping ) {
199 dyld::log("dyld: Using shared cached for %s\n", path);
200 for(unsigned int i=0; i < image->fSegmentsCount; ++i) {
201 dyld::log("%18s at 0x%08lX->0x%08lX\n", image->segName(i), image->segActualLoadAddress(i), image->segActualEndAddress(i));
202 }
203 }
204
205 image->instantiateFinish(context);
206 image->setMapped(context);
207 }
208 catch (...) {
209 // ImageLoader::setMapped() can throw an exception to block loading of image
210 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
211 delete image;
212 throw;
213 }
214
215 return image;
216 }
217
218 // create image by copying an in-memory mach-o file
219 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName, const macho_header* mh, uint64_t len,
220 unsigned int segCount, unsigned int libCount, const LinkContext& context)
221 {
222 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, moduleName, segCount, libCount);
223 try {
224 // map segments
225 if ( mh->filetype == MH_EXECUTE )
226 throw "can't load another MH_EXECUTE";
227
228 // vmcopy segments
229 image->mapSegments((const void*)mh, len, context);
230
231 // for compatibility, never unload dylibs loaded from memory
232 image->setNeverUnload();
233
234 image->disableCoverageCheck();
235
236 // bundle loads need path copied
237 if ( moduleName != NULL )
238 image->setPath(moduleName);
239
240 image->instantiateFinish(context);
241 image->setMapped(context);
242 }
243 catch (...) {
244 // ImageLoader::setMapped() can throw an exception to block loading of image
245 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
246 delete image;
247 throw;
248 }
249
250 return image;
251 }
252
253
254 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header* mh, const char* path, unsigned int segCount,
255 uint32_t segOffsets[], unsigned int libCount)
256 : ImageLoaderMachO(mh, path, segCount, segOffsets, libCount), fDyldInfo(NULL)
257 {
258 }
259
260 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
261 {
262 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
263 destroy();
264 }
265
266
267
268 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
269 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateStart(const macho_header* mh, const char* path,
270 unsigned int segCount, unsigned int libCount)
271 {
272 size_t size = sizeof(ImageLoaderMachOCompressed) + segCount * sizeof(uint32_t) + libCount * sizeof(ImageLoader*);
273 ImageLoaderMachOCompressed* allocatedSpace = static_cast<ImageLoaderMachOCompressed*>(malloc(size));
274 if ( allocatedSpace == NULL )
275 throw "malloc failed";
276 uint32_t* segOffsets = ((uint32_t*)(((uint8_t*)allocatedSpace) + sizeof(ImageLoaderMachOCompressed)));
277 bzero(&segOffsets[segCount], libCount*sizeof(void*)); // zero out lib array
278 return new (allocatedSpace) ImageLoaderMachOCompressed(mh, path, segCount, segOffsets, libCount);
279 }
280
281
282 // common code to finish initializing object
283 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext& context)
284 {
285 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
286 this->parseLoadCmds(context);
287 }
288
289 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
290 {
291 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed)));
292 }
293
294
295 ImageLoader* ImageLoaderMachOCompressed::libImage(unsigned int libIndex) const
296 {
297 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
298 // mask off low bits
299 return (ImageLoader*)(images[libIndex] & (-4));
300 }
301
302 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex) const
303 {
304 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
305 // re-export flag is low bit
306 return ((images[libIndex] & 1) != 0);
307 }
308
309 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex) const
310 {
311 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
312 // re-export flag is second bit
313 return ((images[libIndex] & 2) != 0);
314 }
315
316
317 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex, ImageLoader* image, bool reExported, bool upward)
318 {
319 uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
320 uintptr_t value = (uintptr_t)image;
321 if ( reExported )
322 value |= 1;
323 if ( upward )
324 value |= 2;
325 images[libIndex] = value;
326 }
327
328
329 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext& context)
330 {
331 // mark that we are done with rebase and bind info
332 markLINKEDIT(context, MADV_FREE);
333 }
334
335 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext& context)
336 {
337 // mark the rebase and bind info and using sequential access
338 markLINKEDIT(context, MADV_SEQUENTIAL);
339 }
340
341 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext& context, int advise)
342 {
343 // if not loaded at preferred address, mark rebase info
344 uintptr_t start = 0;
345 if ( (fSlide != 0) && (fDyldInfo->rebase_size != 0) )
346 start = (uintptr_t)fLinkEditBase + fDyldInfo->rebase_off;
347 else if ( fDyldInfo->bind_off != 0 )
348 start = (uintptr_t)fLinkEditBase + fDyldInfo->bind_off;
349 else
350 return; // no binding info to prefetch
351
352 // end is at end of bind info
353 uintptr_t end = 0;
354 if ( fDyldInfo->bind_off != 0 )
355 end = (uintptr_t)fLinkEditBase + fDyldInfo->bind_off + fDyldInfo->bind_size;
356 else if ( fDyldInfo->rebase_off != 0 )
357 end = (uintptr_t)fLinkEditBase + fDyldInfo->rebase_off + fDyldInfo->rebase_size;
358 else
359 return;
360
361
362 // round to whole pages
363 start = dyld_page_trunc(start);
364 end = dyld_page_round(end);
365
366 // do nothing if only one page of rebase/bind info
367 if ( (end-start) <= dyld_page_size )
368 return;
369
370 // tell kernel about our access to these pages
371 madvise((void*)start, end-start, advise);
372 if ( context.verboseMapping ) {
373 const char* adstr = "sequential";
374 if ( advise == MADV_FREE )
375 adstr = "free";
376 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr, start, end-1, this->getPath());
377 }
378 }
379
380
381
382 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext& context, uintptr_t addr, uintptr_t slide, uint8_t type)
383 {
384 if ( context.verboseRebase ) {
385 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr, slide);
386 }
387 //dyld::log("0x%08lX type=%d\n", addr, type);
388 uintptr_t* locationToFix = (uintptr_t*)addr;
389 switch (type) {
390 case REBASE_TYPE_POINTER:
391 *locationToFix += slide;
392 break;
393 case REBASE_TYPE_TEXT_ABSOLUTE32:
394 *locationToFix += slide;
395 break;
396 default:
397 dyld::throwf("bad rebase type %d", type);
398 }
399 }
400
401 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address, uintptr_t segmentEndAddress, int segmentIndex,
402 const uint8_t* startOpcodes, const uint8_t* endOpcodes, const uint8_t* pos)
403 {
404 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
405 (intptr_t)(pos-startOpcodes), (intptr_t)(endOpcodes-startOpcodes), address, segName(segmentIndex),
406 segActualLoadAddress(segmentIndex), segmentEndAddress);
407 }
408
409 void ImageLoaderMachOCompressed::rebase(const LinkContext& context, uintptr_t slide)
410 {
411 CRSetCrashLogMessage2(this->getPath());
412 const uint8_t* const start = fLinkEditBase + fDyldInfo->rebase_off;
413 const uint8_t* const end = &start[fDyldInfo->rebase_size];
414 const uint8_t* p = start;
415
416 try {
417 uint8_t type = 0;
418 int segmentIndex = 0;
419 uintptr_t address = segActualLoadAddress(0);
420 uintptr_t segmentStartAddress = segActualLoadAddress(0);
421 uintptr_t segmentEndAddress = segActualEndAddress(0);
422 uintptr_t count;
423 uintptr_t skip;
424 bool done = false;
425 while ( !done && (p < end) ) {
426 uint8_t immediate = *p & REBASE_IMMEDIATE_MASK;
427 uint8_t opcode = *p & REBASE_OPCODE_MASK;
428 ++p;
429 switch (opcode) {
430 case REBASE_OPCODE_DONE:
431 done = true;
432 break;
433 case REBASE_OPCODE_SET_TYPE_IMM:
434 type = immediate;
435 break;
436 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
437 segmentIndex = immediate;
438 if ( segmentIndex >= fSegmentsCount )
439 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
440 segmentIndex, fSegmentsCount-1);
441 #if TEXT_RELOC_SUPPORT
442 if ( !segWriteable(segmentIndex) && !segHasRebaseFixUps(segmentIndex) && !segHasBindFixUps(segmentIndex) )
443 #else
444 if ( !segWriteable(segmentIndex) )
445 #endif
446 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
447 segmentIndex, segName(segmentIndex));
448 segmentStartAddress = segActualLoadAddress(segmentIndex);
449 segmentEndAddress = segActualEndAddress(segmentIndex);
450 address = segmentStartAddress + read_uleb128(p, end);
451 break;
452 case REBASE_OPCODE_ADD_ADDR_ULEB:
453 address += read_uleb128(p, end);
454 break;
455 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
456 address += immediate*sizeof(uintptr_t);
457 break;
458 case REBASE_OPCODE_DO_REBASE_IMM_TIMES:
459 for (int i=0; i < immediate; ++i) {
460 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
461 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
462 rebaseAt(context, address, slide, type);
463 address += sizeof(uintptr_t);
464 }
465 fgTotalRebaseFixups += immediate;
466 break;
467 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
468 count = read_uleb128(p, end);
469 for (uint32_t i=0; i < count; ++i) {
470 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
471 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
472 rebaseAt(context, address, slide, type);
473 address += sizeof(uintptr_t);
474 }
475 fgTotalRebaseFixups += count;
476 break;
477 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
478 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
479 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
480 rebaseAt(context, address, slide, type);
481 address += read_uleb128(p, end) + sizeof(uintptr_t);
482 ++fgTotalRebaseFixups;
483 break;
484 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
485 count = read_uleb128(p, end);
486 skip = read_uleb128(p, end);
487 for (uint32_t i=0; i < count; ++i) {
488 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
489 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
490 rebaseAt(context, address, slide, type);
491 address += skip + sizeof(uintptr_t);
492 }
493 fgTotalRebaseFixups += count;
494 break;
495 default:
496 dyld::throwf("bad rebase opcode %d", *p);
497 }
498 }
499 }
500 catch (const char* msg) {
501 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
502 free((void*)msg);
503 throw newMsg;
504 }
505 CRSetCrashLogMessage2(NULL);
506 }
507
508 const ImageLoader::Symbol* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol, const ImageLoader** foundIn) const
509 {
510 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
511 if ( fDyldInfo->export_size == 0 )
512 return NULL;
513 #if LOG_BINDINGS
514 dyld::logBindings("%s: %s\n", this->getShortName(), symbol);
515 #endif
516 ++ImageLoaderMachO::fgSymbolTrieSearchs;
517 const uint8_t* start = &fLinkEditBase[fDyldInfo->export_off];
518 const uint8_t* end = &start[fDyldInfo->export_size];
519 const uint8_t* foundNodeStart = this->trieWalk(start, end, symbol);
520 if ( foundNodeStart != NULL ) {
521 const uint8_t* p = foundNodeStart;
522 const uintptr_t flags = read_uleb128(p, end);
523 // found match, return pointer to terminal part of node
524 if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) {
525 // re-export from another dylib, lookup there
526 const uintptr_t ordinal = read_uleb128(p, end);
527 const char* importedName = (char*)p;
528 if ( importedName[0] == '\0' )
529 importedName = symbol;
530 if ( (ordinal > 0) && (ordinal <= libraryCount()) ) {
531 const ImageLoader* reexportedFrom = libImage((unsigned int)ordinal-1);
532 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
533 const char* reExportLibPath = libPath((unsigned int)ordinal-1);
534 return reexportedFrom->findExportedSymbol(importedName, true, reExportLibPath, foundIn);
535 }
536 else {
537 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
538 // ordinal, libraryCount(), symbol, this->getPath());
539 }
540 }
541 else {
542 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
543 if ( foundIn != NULL )
544 *foundIn = (ImageLoader*)this;
545 // return pointer to terminal part of node
546 return (Symbol*)foundNodeStart;
547 }
548 }
549 return NULL;
550 }
551
552
553 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr) const
554 {
555 const uint8_t* start = &fLinkEditBase[fDyldInfo->export_off];
556 const uint8_t* end = &start[fDyldInfo->export_size];
557 return ( (start <= addr) && (addr < end) );
558 }
559
560
561 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext& context, const Symbol* symbol, const ImageLoader* requestor, bool runResolver) const
562 {
563 const uint8_t* exportNode = (uint8_t*)symbol;
564 const uint8_t* exportTrieStart = fLinkEditBase + fDyldInfo->export_off;
565 const uint8_t* exportTrieEnd = exportTrieStart + fDyldInfo->export_size;
566 if ( (exportNode < exportTrieStart) || (exportNode > exportTrieEnd) )
567 throw "symbol is not in trie";
568 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
569 uintptr_t flags = read_uleb128(exportNode, exportTrieEnd);
570 switch ( flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) {
571 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR:
572 if ( runResolver && (flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) ) {
573 // this node has a stub and resolver, run the resolver to get target address
574 uintptr_t stub = read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData; // skip over stub
575 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
576 uintptr_t interposedStub = interposedAddress(context, stub, requestor);
577 if ( interposedStub != stub )
578 return interposedStub;
579 // stub was not interposed, so run resolver
580 typedef uintptr_t (*ResolverProc)(void);
581 ResolverProc resolver = (ResolverProc)(read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData);
582 uintptr_t result = (*resolver)();
583 if ( context.verboseBind )
584 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver, result);
585 return result;
586 }
587 return read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData;
588 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL:
589 if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER )
590 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
591 return read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData;
592 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE:
593 if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER )
594 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
595 return read_uleb128(exportNode, exportTrieEnd);
596 default:
597 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
598 }
599 }
600
601 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol* symbol) const
602 {
603 const uint8_t* exportNode = (uint8_t*)symbol;
604 const uint8_t* exportTrieStart = fLinkEditBase + fDyldInfo->export_off;
605 const uint8_t* exportTrieEnd = exportTrieStart + fDyldInfo->export_size;
606 if ( (exportNode < exportTrieStart) || (exportNode > exportTrieEnd) )
607 throw "symbol is not in trie";
608 uintptr_t flags = read_uleb128(exportNode, exportTrieEnd);
609 return ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION );
610 }
611
612
613 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol* symbol) const
614 {
615 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
616 }
617
618 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
619 {
620 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
621 }
622
623 const ImageLoader::Symbol* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index) const
624 {
625 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
626 }
627
628 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
629 {
630 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
631 }
632
633 const ImageLoader::Symbol* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index) const
634 {
635 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
636 }
637
638 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol* symbol) const
639 {
640 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
641 }
642
643
644
645 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext& context, const char* symbolName, bool weak_import,
646 bool runResolver, const ImageLoader** foundIn)
647 {
648 const Symbol* sym;
649 if ( context.flatExportFinder(symbolName, &sym, foundIn) ) {
650 if ( *foundIn != this )
651 context.addDynamicReference(this, const_cast<ImageLoader*>(*foundIn));
652 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
653 }
654 // if a bundle is loaded privately the above will not find its exports
655 if ( this->isBundle() && this->hasHiddenExports() ) {
656 // look in self for needed symbol
657 sym = this->findShallowExportedSymbol(symbolName, foundIn);
658 if ( sym != NULL )
659 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
660 }
661 if ( weak_import ) {
662 // definition can't be found anywhere, ok because it is weak, just return 0
663 return 0;
664 }
665 throwSymbolNotFound(context, symbolName, this->getPath(), "", "flat namespace");
666 }
667
668
669 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext& context, const char* symbolName, const ImageLoader* definedInImage,
670 const ImageLoader* requestorImage, unsigned requestorOrdinalOfDef, bool weak_import, bool runResolver,
671 const ImageLoader** foundIn)
672 {
673 // two level lookup
674 uintptr_t address;
675 if ( definedInImage->findExportedSymbolAddress(context, symbolName, requestorImage, requestorOrdinalOfDef, runResolver, foundIn, &address) )
676 return address;
677
678 if ( weak_import ) {
679 // definition can't be found anywhere, ok because it is weak, just return 0
680 return 0;
681 }
682
683 // nowhere to be found, check if maybe this image is too new for this OS
684 char versMismatch[256];
685 versMismatch[0] = '\0';
686 uint32_t imageMinOS = this->minOSVersion();
687 // dyld is always built for the current OS, so we can get the current OS version
688 // from the load command in dyld itself.
689 extern const mach_header __dso_handle;
690 uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion(&__dso_handle);
691 if ( imageMinOS > dyldMinOS ) {
692 #if __MAC_OS_X_VERSION_MIN_REQUIRED
693 const char* msg = dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS >> 16, (imageMinOS >> 8) & 0xFF);
694 #else
695 const char* msg = dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS >> 16, (imageMinOS >> 8) & 0xFF);
696 #endif
697 strcpy(versMismatch, msg);
698 ::free((void*)msg);
699 }
700 throwSymbolNotFound(context, symbolName, this->getPath(), versMismatch, definedInImage->getPath());
701 }
702
703
704 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext& context, const char* symbolName,
705 uint8_t symboFlags, long libraryOrdinal, const ImageLoader** targetImage,
706 LastLookup* last, bool runResolver)
707 {
708 *targetImage = NULL;
709
710 // only clients that benefit from caching last lookup pass in a LastLookup struct
711 if ( last != NULL ) {
712 if ( (last->ordinal == libraryOrdinal)
713 && (last->flags == symboFlags)
714 && (last->name == symbolName) ) {
715 *targetImage = last->foundIn;
716 return last->result;
717 }
718 }
719
720 bool weak_import = (symboFlags & BIND_SYMBOL_FLAGS_WEAK_IMPORT);
721 uintptr_t symbolAddress;
722 if ( context.bindFlat || (libraryOrdinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP) ) {
723 symbolAddress = this->resolveFlat(context, symbolName, weak_import, runResolver, targetImage);
724 }
725 else {
726 if ( libraryOrdinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE ) {
727 *targetImage = context.mainExecutable;
728 }
729 else if ( libraryOrdinal == BIND_SPECIAL_DYLIB_SELF ) {
730 *targetImage = this;
731 }
732 else if ( libraryOrdinal <= 0 ) {
733 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
734 libraryOrdinal, symbolName, this->getPath());
735 }
736 else if ( (unsigned)libraryOrdinal <= libraryCount() ) {
737 *targetImage = libImage((unsigned int)libraryOrdinal-1);
738 }
739 else {
740 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
741 libraryOrdinal, libraryCount(), symbolName, this->getPath());
742 }
743 if ( *targetImage == NULL ) {
744 if ( weak_import ) {
745 // if target library not loaded and reference is weak or library is weak return 0
746 symbolAddress = 0;
747 }
748 else {
749 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
750 symbolName, this->getPath(), libraryOrdinal);
751 }
752 }
753 else {
754 symbolAddress = resolveTwolevel(context, symbolName, *targetImage, this, (unsigned)libraryOrdinal, weak_import, runResolver, targetImage);
755 }
756 }
757
758 // save off lookup results if client wants
759 if ( last != NULL ) {
760 last->ordinal = libraryOrdinal;
761 last->flags = symboFlags;
762 last->name = symbolName;
763 last->foundIn = *targetImage;
764 last->result = symbolAddress;
765 }
766
767 return symbolAddress;
768 }
769
770 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext& context, uintptr_t addr, uint8_t type, const char* symbolName,
771 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal, const char* msg,
772 LastLookup* last, bool runResolver)
773 {
774 const ImageLoader* targetImage;
775 uintptr_t symbolAddress;
776
777 // resolve symbol
778 symbolAddress = this->resolve(context, symbolName, symbolFlags, libraryOrdinal, &targetImage, last, runResolver);
779
780 // do actual update
781 return this->bindLocation(context, addr, symbolAddress, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, msg);
782 }
783
784
785 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address, uintptr_t segmentEndAddress, int segmentIndex,
786 const uint8_t* startOpcodes, const uint8_t* endOpcodes, const uint8_t* pos)
787 {
788 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
789 (intptr_t)(pos-startOpcodes), (intptr_t)(endOpcodes-startOpcodes), address, segName(segmentIndex),
790 segActualLoadAddress(segmentIndex), segmentEndAddress);
791 }
792
793
794 void ImageLoaderMachOCompressed::doBind(const LinkContext& context, bool forceLazysBound)
795 {
796 CRSetCrashLogMessage2(this->getPath());
797
798 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
799 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
800 if ( this->usablePrebinding(context) ) {
801 // don't need to bind
802 }
803 else {
804 uint64_t t0 = mach_absolute_time();
805
806 #if TEXT_RELOC_SUPPORT
807 // if there are __TEXT fixups, temporarily make __TEXT writable
808 if ( fTextSegmentBinds )
809 this->makeTextSegmentWritable(context, true);
810 #endif
811
812 // run through all binding opcodes
813 eachBind(context, &ImageLoaderMachOCompressed::bindAt);
814
815 #if TEXT_RELOC_SUPPORT
816 // if there were __TEXT fixups, restore write protection
817 if ( fTextSegmentBinds )
818 this->makeTextSegmentWritable(context, false);
819 #endif
820
821 // if this image is in the shared cache, but depends on something no longer in the shared cache,
822 // there is no way to reset the lazy pointers, so force bind them now
823 if ( forceLazysBound || fInSharedCache )
824 this->doBindJustLazies(context);
825
826 // this image is in cache, but something below it is not. If
827 // this image has lazy pointer to a resolver function, then
828 // the stub may have been altered to point to a shared lazy pointer.
829 if ( fInSharedCache )
830 this->updateOptimizedLazyPointers(context);
831
832 // tell kernel we are done with chunks of LINKEDIT
833 if ( !context.preFetchDisabled )
834 this->markFreeLINKEDIT(context);
835
836 uint64_t t1 = mach_absolute_time();
837 ImageLoader::fgTotalRebindCacheTime += (t1-t0);
838 }
839
840 // set up dyld entry points in image
841 // do last so flat main executables will have __dyld or __program_vars set up
842 this->setupLazyPointerHandler(context);
843 CRSetCrashLogMessage2(NULL);
844 }
845
846
847 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext& context)
848 {
849 eachLazyBind(context, &ImageLoaderMachOCompressed::bindAt);
850 }
851
852 #if __arm__ || __arm64__
853 int ImageLoaderMachOCompressed::vmAccountingSetSuspended(bool suspend, const LinkContext& context)
854 {
855 if ( context.verboseBind )
856 dyld::log("vm.footprint_suspend=%d\n", suspend);
857 int newValue = suspend ? 1 : 0;
858 int oldValue = 0;
859 size_t newlen = sizeof(newValue);
860 size_t oldlen = sizeof(oldValue);
861 return sysctlbyname("vm.footprint_suspend", &oldValue, &oldlen, &newValue, newlen);
862 }
863 #endif
864
865 void ImageLoaderMachOCompressed::eachBind(const LinkContext& context, bind_handler handler)
866 {
867 #if __arm__ || __arm64__
868 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
869 if ( !sVmAccountingDisabled ) {
870 if ( fInSharedCache ) {
871 if ( !sVmAccountingSuspended ) {
872 int ret = vmAccountingSetSuspended(true, context);
873 if ( context.verboseBind && (ret != 0) )
874 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret, errno);
875 if ( ret == 0 )
876 sVmAccountingSuspended = true;
877 else
878 sVmAccountingDisabled = true;
879 }
880 }
881 else if ( sVmAccountingSuspended ) {
882 int ret = vmAccountingSetSuspended(false, context);
883 if ( ret == 0 )
884 sVmAccountingSuspended = false;
885 else if ( errno == ENOENT )
886 sVmAccountingDisabled = true;
887 }
888 }
889 #endif
890
891 try {
892 uint8_t type = 0;
893 int segmentIndex = -1;
894 uintptr_t address = segActualLoadAddress(0);
895 uintptr_t segmentStartAddress = segActualLoadAddress(0);
896 uintptr_t segmentEndAddress = segActualEndAddress(0);
897 const char* symbolName = NULL;
898 uint8_t symboFlags = 0;
899 bool libraryOrdinalSet = false;
900 long libraryOrdinal = 0;
901 intptr_t addend = 0;
902 uintptr_t count;
903 uintptr_t skip;
904 uintptr_t segOffset;
905 LastLookup last = { 0, 0, NULL, 0, NULL };
906 const uint8_t* const start = fLinkEditBase + fDyldInfo->bind_off;
907 const uint8_t* const end = &start[fDyldInfo->bind_size];
908 const uint8_t* p = start;
909 bool done = false;
910 while ( !done && (p < end) ) {
911 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
912 uint8_t opcode = *p & BIND_OPCODE_MASK;
913 ++p;
914 switch (opcode) {
915 case BIND_OPCODE_DONE:
916 done = true;
917 break;
918 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
919 libraryOrdinal = immediate;
920 libraryOrdinalSet = true;
921 break;
922 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
923 libraryOrdinal = read_uleb128(p, end);
924 libraryOrdinalSet = true;
925 break;
926 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
927 // the special ordinals are negative numbers
928 if ( immediate == 0 )
929 libraryOrdinal = 0;
930 else {
931 int8_t signExtended = BIND_OPCODE_MASK | immediate;
932 libraryOrdinal = signExtended;
933 }
934 libraryOrdinalSet = true;
935 break;
936 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
937 symbolName = (char*)p;
938 symboFlags = immediate;
939 while (*p != '\0')
940 ++p;
941 ++p;
942 break;
943 case BIND_OPCODE_SET_TYPE_IMM:
944 type = immediate;
945 break;
946 case BIND_OPCODE_SET_ADDEND_SLEB:
947 addend = read_sleb128(p, end);
948 break;
949 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
950 segmentIndex = immediate;
951 if ( (segmentIndex >= fSegmentsCount) || (segmentIndex < 0) )
952 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
953 segmentIndex, fSegmentsCount-1);
954 #if TEXT_RELOC_SUPPORT
955 if ( !segWriteable(segmentIndex) && !segHasRebaseFixUps(segmentIndex) && !segHasBindFixUps(segmentIndex) )
956 #else
957 if ( !segWriteable(segmentIndex) )
958 #endif
959 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex);
960 segOffset = read_uleb128(p, end);
961 if ( segOffset > segSize(segmentIndex) )
962 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segmentIndex));
963 segmentStartAddress = segActualLoadAddress(segmentIndex);
964 address = segmentStartAddress + segOffset;
965 segmentEndAddress = segActualEndAddress(segmentIndex);
966 break;
967 case BIND_OPCODE_ADD_ADDR_ULEB:
968 address += read_uleb128(p, end);
969 break;
970 case BIND_OPCODE_DO_BIND:
971 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
972 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
973 if ( symbolName == NULL )
974 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
975 if ( segmentIndex == -1 )
976 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
977 if ( !libraryOrdinalSet )
978 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
979 (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last, false);
980 address += sizeof(intptr_t);
981 break;
982 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
983 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
984 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
985 if ( symbolName == NULL )
986 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
987 if ( segmentIndex == -1 )
988 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
989 if ( !libraryOrdinalSet )
990 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
991 (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last, false);
992 address += read_uleb128(p, end) + sizeof(intptr_t);
993 break;
994 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
995 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
996 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
997 if ( symbolName == NULL )
998 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
999 if ( segmentIndex == -1 )
1000 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1001 if ( !libraryOrdinalSet )
1002 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1003 (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last, false);
1004 address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1005 break;
1006 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1007 if ( symbolName == NULL )
1008 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1009 if ( segmentIndex == -1 )
1010 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1011 count = read_uleb128(p, end);
1012 if ( !libraryOrdinalSet )
1013 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1014 skip = read_uleb128(p, end);
1015 for (uint32_t i=0; i < count; ++i) {
1016 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1017 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1018 (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last, false);
1019 address += skip + sizeof(intptr_t);
1020 }
1021 break;
1022 default:
1023 dyld::throwf("bad bind opcode %d in bind info", *p);
1024 }
1025 }
1026 }
1027 catch (const char* msg) {
1028 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
1029 free((void*)msg);
1030 throw newMsg;
1031 }
1032 }
1033
1034 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext& context, bind_handler handler)
1035 {
1036 try {
1037 uint8_t type = BIND_TYPE_POINTER;
1038 int segmentIndex = -1;
1039 uintptr_t address = segActualLoadAddress(0);
1040 uintptr_t segmentStartAddress = segActualLoadAddress(0);
1041 uintptr_t segmentEndAddress = segActualEndAddress(0);
1042 uintptr_t segOffset;
1043 const char* symbolName = NULL;
1044 uint8_t symboFlags = 0;
1045 long libraryOrdinal = 0;
1046 intptr_t addend = 0;
1047 const uint8_t* const start = fLinkEditBase + fDyldInfo->lazy_bind_off;
1048 const uint8_t* const end = &start[fDyldInfo->lazy_bind_size];
1049 const uint8_t* p = start;
1050 bool done = false;
1051 while ( !done && (p < end) ) {
1052 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1053 uint8_t opcode = *p & BIND_OPCODE_MASK;
1054 ++p;
1055 switch (opcode) {
1056 case BIND_OPCODE_DONE:
1057 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1058 break;
1059 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
1060 libraryOrdinal = immediate;
1061 break;
1062 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
1063 libraryOrdinal = read_uleb128(p, end);
1064 break;
1065 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
1066 // the special ordinals are negative numbers
1067 if ( immediate == 0 )
1068 libraryOrdinal = 0;
1069 else {
1070 int8_t signExtended = BIND_OPCODE_MASK | immediate;
1071 libraryOrdinal = signExtended;
1072 }
1073 break;
1074 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1075 symbolName = (char*)p;
1076 symboFlags = immediate;
1077 while (*p != '\0')
1078 ++p;
1079 ++p;
1080 break;
1081 case BIND_OPCODE_SET_TYPE_IMM:
1082 type = immediate;
1083 break;
1084 case BIND_OPCODE_SET_ADDEND_SLEB:
1085 addend = read_sleb128(p, end);
1086 break;
1087 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1088 segmentIndex = immediate;
1089 if ( (segmentIndex >= fSegmentsCount) || (segmentIndex < 0) )
1090 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1091 segmentIndex, fSegmentsCount-1);
1092 if ( !segWriteable(segmentIndex) )
1093 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex);
1094 segOffset = read_uleb128(p, end);
1095 if ( segOffset > segSize(segmentIndex) )
1096 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segmentIndex));
1097 segmentStartAddress = segActualLoadAddress(segmentIndex);
1098 segmentEndAddress = segActualEndAddress(segmentIndex);
1099 address = segmentStartAddress + segOffset;
1100 break;
1101 case BIND_OPCODE_ADD_ADDR_ULEB:
1102 address += read_uleb128(p, end);
1103 break;
1104 case BIND_OPCODE_DO_BIND:
1105 if ( segmentIndex == -1 )
1106 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1107 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1108 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1109 if ( symbolName == NULL )
1110 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1111 (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "forced lazy ", NULL, false);
1112 address += sizeof(intptr_t);
1113 break;
1114 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1115 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1116 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1117 default:
1118 dyld::throwf("bad lazy bind opcode %d", *p);
1119 }
1120 }
1121 }
1122
1123 catch (const char* msg) {
1124 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
1125 free((void*)msg);
1126 throw newMsg;
1127 }
1128 }
1129
1130 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1131 // the classic lazy loader is used even when running on 10.6
1132 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer, const LinkContext& context)
1133 {
1134 // only works with compressed LINKEDIT if classic symbol table is also present
1135 const macho_nlist* symbolTable = NULL;
1136 const char* symbolTableStrings = NULL;
1137 const dysymtab_command* dynSymbolTable = NULL;
1138 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1139 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1140 const struct load_command* cmd = cmds;
1141 for (uint32_t i = 0; i < cmd_count; ++i) {
1142 switch (cmd->cmd) {
1143 case LC_SYMTAB:
1144 {
1145 const struct symtab_command* symtab = (struct symtab_command*)cmd;
1146 symbolTableStrings = (const char*)&fLinkEditBase[symtab->stroff];
1147 symbolTable = (macho_nlist*)(&fLinkEditBase[symtab->symoff]);
1148 }
1149 break;
1150 case LC_DYSYMTAB:
1151 dynSymbolTable = (struct dysymtab_command*)cmd;
1152 break;
1153 }
1154 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1155 }
1156 // no symbol table => no lookup by address
1157 if ( (symbolTable == NULL) || (dynSymbolTable == NULL) )
1158 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer, this->getPath());
1159
1160 // scan for all lazy-pointer sections
1161 const bool twoLevel = this->usesTwoLevelNameSpace();
1162 const uint32_t* const indirectTable = (uint32_t*)&fLinkEditBase[dynSymbolTable->indirectsymoff];
1163 cmd = cmds;
1164 for (uint32_t i = 0; i < cmd_count; ++i) {
1165 switch (cmd->cmd) {
1166 case LC_SEGMENT_COMMAND:
1167 {
1168 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1169 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1170 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1171 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1172 const uint8_t type = sect->flags & SECTION_TYPE;
1173 uint32_t symbolIndex = INDIRECT_SYMBOL_LOCAL;
1174 if ( type == S_LAZY_SYMBOL_POINTERS ) {
1175 const size_t pointerCount = sect->size / sizeof(uintptr_t);
1176 uintptr_t* const symbolPointers = (uintptr_t*)(sect->addr + fSlide);
1177 if ( (lazyPointer >= symbolPointers) && (lazyPointer < &symbolPointers[pointerCount]) ) {
1178 const uint32_t indirectTableOffset = sect->reserved1;
1179 const size_t lazyIndex = lazyPointer - symbolPointers;
1180 symbolIndex = indirectTable[indirectTableOffset + lazyIndex];
1181 }
1182 }
1183 if ( (symbolIndex != INDIRECT_SYMBOL_ABS) && (symbolIndex != INDIRECT_SYMBOL_LOCAL) ) {
1184 const macho_nlist* symbol = &symbolTable[symbolIndex];
1185 const char* symbolName = &symbolTableStrings[symbol->n_un.n_strx];
1186 int libraryOrdinal = GET_LIBRARY_ORDINAL(symbol->n_desc);
1187 if ( !twoLevel || context.bindFlat )
1188 libraryOrdinal = BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
1189 uintptr_t ptrToBind = (uintptr_t)lazyPointer;
1190 uintptr_t symbolAddr = bindAt(context, ptrToBind, BIND_TYPE_POINTER, symbolName, 0, 0, libraryOrdinal, "lazy ", NULL);
1191 ++fgTotalLazyBindFixups;
1192 return symbolAddr;
1193 }
1194 }
1195 }
1196 break;
1197 }
1198 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1199 }
1200 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer, this->getPath());
1201 }
1202
1203
1204
1205 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset, const LinkContext& context,
1206 void (*lock)(), void (*unlock)())
1207 {
1208 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1209 if ( this->usesTwoLevelNameSpace() ) {
1210 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1211 }
1212 else {
1213 // acquire dyld global lock
1214 if ( lock != NULL )
1215 lock();
1216 }
1217
1218 const uint8_t* const start = fLinkEditBase + fDyldInfo->lazy_bind_off;
1219 const uint8_t* const end = &start[fDyldInfo->lazy_bind_size];
1220 uint8_t segIndex;
1221 uintptr_t segOffset;
1222 int libraryOrdinal;
1223 const char* symbolName;
1224 bool doneAfterBind;
1225 uintptr_t result;
1226 do {
1227 if ( ! getLazyBindingInfo(lazyBindingInfoOffset, start, end, &segIndex, &segOffset, &libraryOrdinal, &symbolName, &doneAfterBind) )
1228 dyld::throwf("bad lazy bind info");
1229
1230 if ( segIndex >= fSegmentsCount )
1231 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1232 segIndex, fSegmentsCount-1);
1233 if ( segOffset > segSize(segIndex) )
1234 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segIndex));
1235 uintptr_t address = segActualLoadAddress(segIndex) + segOffset;
1236 result = this->bindAt(context, address, BIND_TYPE_POINTER, symbolName, 0, 0, libraryOrdinal, "lazy ", NULL, true);
1237 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1238 } while (!doneAfterBind && !context.strictMachORequired);
1239
1240 if ( !this->usesTwoLevelNameSpace() ) {
1241 // release dyld global lock
1242 if ( unlock != NULL )
1243 unlock();
1244 }
1245 return result;
1246 }
1247
1248 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator& it, unsigned int loadOrder, unsigned)
1249 {
1250 it.image = this;
1251 it.symbolName = " ";
1252 it.loadOrder = loadOrder;
1253 it.weakSymbol = false;
1254 it.symbolMatches = false;
1255 it.done = false;
1256 it.curIndex = 0;
1257 it.endIndex = this->fDyldInfo->weak_bind_size;
1258 it.address = 0;
1259 it.type = 0;
1260 it.addend = 0;
1261 }
1262
1263
1264 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator& it)
1265 {
1266 if ( it.done )
1267 return false;
1268
1269 if ( this->fDyldInfo->weak_bind_size == 0 ) {
1270 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1271 it.done = true;
1272 it.symbolName = "~~~";
1273 return true;
1274 }
1275 const uint8_t* start = fLinkEditBase + fDyldInfo->weak_bind_off;
1276 const uint8_t* p = start + it.curIndex;
1277 const uint8_t* end = fLinkEditBase + fDyldInfo->weak_bind_off + this->fDyldInfo->weak_bind_size;
1278 uintptr_t count;
1279 uintptr_t skip;
1280 uintptr_t segOffset;
1281 while ( p < end ) {
1282 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1283 uint8_t opcode = *p & BIND_OPCODE_MASK;
1284 ++p;
1285 switch (opcode) {
1286 case BIND_OPCODE_DONE:
1287 it.done = true;
1288 it.curIndex = p - start;
1289 it.symbolName = "~~~"; // sorts to end
1290 return true;
1291 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1292 it.symbolName = (char*)p;
1293 it.weakSymbol = ((immediate & BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) == 0);
1294 it.symbolMatches = false;
1295 while (*p != '\0')
1296 ++p;
1297 ++p;
1298 it.curIndex = p - start;
1299 return false;
1300 case BIND_OPCODE_SET_TYPE_IMM:
1301 it.type = immediate;
1302 break;
1303 case BIND_OPCODE_SET_ADDEND_SLEB:
1304 it.addend = read_sleb128(p, end);
1305 break;
1306 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1307 if ( immediate >= fSegmentsCount )
1308 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1309 immediate, fSegmentsCount-1);
1310 #if __arm__
1311 // <rdar://problem/23138428> iOS app compatibility
1312 if ( !segWriteable(immediate) && it.image->isPositionIndependentExecutable() )
1313 #elif TEXT_RELOC_SUPPORT
1314 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1315 if ( !segWriteable(immediate) && !segHasRebaseFixUps(immediate) && !segHasBindFixUps(immediate)
1316 && (!it.image->isExecutable() || it.image->isPositionIndependentExecutable()) )
1317 #else
1318 if ( !segWriteable(immediate) )
1319 #endif
1320 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate));
1321 segOffset = read_uleb128(p, end);
1322 if ( segOffset > segSize(immediate) )
1323 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(immediate));
1324 it.address = segActualLoadAddress(immediate) + segOffset;
1325 break;
1326 case BIND_OPCODE_ADD_ADDR_ULEB:
1327 it.address += read_uleb128(p, end);
1328 break;
1329 case BIND_OPCODE_DO_BIND:
1330 it.address += sizeof(intptr_t);
1331 break;
1332 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1333 it.address += read_uleb128(p, end) + sizeof(intptr_t);
1334 break;
1335 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1336 it.address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1337 break;
1338 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1339 count = read_uleb128(p, end);
1340 skip = read_uleb128(p, end);
1341 for (uint32_t i=0; i < count; ++i) {
1342 it.address += skip + sizeof(intptr_t);
1343 }
1344 break;
1345 default:
1346 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p, (int)(p-start), this->getPath());
1347 }
1348 }
1349 /// hmmm, BIND_OPCODE_DONE is missing...
1350 it.done = true;
1351 it.symbolName = "~~~";
1352 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1353 return true;
1354 }
1355
1356 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator& it, const LinkContext& context)
1357 {
1358 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1359 const ImageLoader* foundIn = NULL;
1360 const ImageLoader::Symbol* sym = this->findShallowExportedSymbol(it.symbolName, &foundIn);
1361 if ( sym != NULL ) {
1362 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1363 return foundIn->getExportedSymbolAddress(sym, context, this);
1364 }
1365 return 0;
1366 }
1367
1368
1369 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator& it, uintptr_t value, ImageLoader* targetImage, unsigned targetIndex, const LinkContext& context)
1370 {
1371 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1372 if ( this->getState() < dyld_image_state_bound )
1373 return;
1374
1375 const uint8_t* start = fLinkEditBase + fDyldInfo->weak_bind_off;
1376 const uint8_t* p = start + it.curIndex;
1377 const uint8_t* end = fLinkEditBase + fDyldInfo->weak_bind_off + this->fDyldInfo->weak_bind_size;
1378
1379 uint8_t type = it.type;
1380 uintptr_t address = it.address;
1381 const char* symbolName = it.symbolName;
1382 intptr_t addend = it.addend;
1383 uintptr_t count;
1384 uintptr_t skip;
1385 uintptr_t segOffset;
1386 bool done = false;
1387 bool boundSomething = false;
1388 while ( !done && (p < end) ) {
1389 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1390 uint8_t opcode = *p & BIND_OPCODE_MASK;
1391 ++p;
1392 switch (opcode) {
1393 case BIND_OPCODE_DONE:
1394 done = true;
1395 break;
1396 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1397 done = true;
1398 break;
1399 case BIND_OPCODE_SET_TYPE_IMM:
1400 type = immediate;
1401 break;
1402 case BIND_OPCODE_SET_ADDEND_SLEB:
1403 addend = read_sleb128(p, end);
1404 break;
1405 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1406 if ( immediate >= fSegmentsCount )
1407 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1408 immediate, fSegmentsCount-1);
1409 #if __arm__
1410 // <rdar://problem/23138428> iOS app compatibility
1411 if ( !segWriteable(immediate) && it.image->isPositionIndependentExecutable() )
1412 #elif TEXT_RELOC_SUPPORT
1413 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1414 if ( !segWriteable(immediate) && !segHasRebaseFixUps(immediate) && !segHasBindFixUps(immediate)
1415 && (!it.image->isExecutable() || it.image->isPositionIndependentExecutable()) )
1416 #else
1417 if ( !segWriteable(immediate) )
1418 #endif
1419 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate));
1420 segOffset = read_uleb128(p, end);
1421 if ( segOffset > segSize(immediate) )
1422 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(immediate));
1423 address = segActualLoadAddress(immediate) + segOffset;
1424 break;
1425 case BIND_OPCODE_ADD_ADDR_ULEB:
1426 address += read_uleb128(p, end);
1427 break;
1428 case BIND_OPCODE_DO_BIND:
1429 bindLocation(context, address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ");
1430 boundSomething = true;
1431 address += sizeof(intptr_t);
1432 break;
1433 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1434 bindLocation(context, address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ");
1435 boundSomething = true;
1436 address += read_uleb128(p, end) + sizeof(intptr_t);
1437 break;
1438 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1439 bindLocation(context, address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ");
1440 boundSomething = true;
1441 address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1442 break;
1443 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1444 count = read_uleb128(p, end);
1445 skip = read_uleb128(p, end);
1446 for (uint32_t i=0; i < count; ++i) {
1447 bindLocation(context, address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ");
1448 boundSomething = true;
1449 address += skip + sizeof(intptr_t);
1450 }
1451 break;
1452 default:
1453 dyld::throwf("bad bind opcode %d in weak binding info", *p);
1454 }
1455 }
1456 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1457 if ( boundSomething && (targetImage != this) )
1458 context.addDynamicReference(this, targetImage);
1459 }
1460
1461 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext& context, uintptr_t addr, uint8_t type, const char*,
1462 uint8_t, intptr_t, long, const char*, LastLookup*, bool runResolver)
1463 {
1464 if ( type == BIND_TYPE_POINTER ) {
1465 uintptr_t* fixupLocation = (uintptr_t*)addr;
1466 uintptr_t curValue = *fixupLocation;
1467 uintptr_t newValue = interposedAddress(context, curValue, this);
1468 if ( newValue != curValue) {
1469 *fixupLocation = newValue;
1470 }
1471 }
1472 return 0;
1473 }
1474
1475 void ImageLoaderMachOCompressed::doInterpose(const LinkContext& context)
1476 {
1477 if ( context.verboseInterposing )
1478 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples.size(), this->getPath());
1479
1480 // update prebound symbols
1481 eachBind(context, &ImageLoaderMachOCompressed::interposeAt);
1482 eachLazyBind(context, &ImageLoaderMachOCompressed::interposeAt);
1483 }
1484
1485
1486 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext& context, uintptr_t addr, uint8_t type, const char* symbolName,
1487 uint8_t, intptr_t, long, const char*, LastLookup*, bool runResolver)
1488 {
1489 if ( type == BIND_TYPE_POINTER ) {
1490 uintptr_t* fixupLocation = (uintptr_t*)addr;
1491 uintptr_t value = *fixupLocation;
1492 // don't apply interposing to table entries.
1493 if ( (context.dynamicInterposeArray <= (void*)addr) && ((void*)addr < &context.dynamicInterposeArray[context.dynamicInterposeCount]) )
1494 return 0;
1495 for(size_t i=0; i < context.dynamicInterposeCount; ++i) {
1496 if ( value == (uintptr_t)context.dynamicInterposeArray[i].replacee ) {
1497 if ( context.verboseInterposing ) {
1498 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1499 fixupLocation, context.dynamicInterposeArray[i].replacee, context.dynamicInterposeArray[i].replacement, this->getPath());
1500 }
1501 *fixupLocation = (uintptr_t)context.dynamicInterposeArray[i].replacement;
1502 }
1503 }
1504 }
1505 return 0;
1506 }
1507
1508 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext& context)
1509 {
1510 if ( context.verboseInterposing )
1511 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context.dynamicInterposeCount, this->getPath());
1512
1513 // update already bound references to symbols
1514 eachBind(context, &ImageLoaderMachOCompressed::dynamicInterposeAt);
1515 eachLazyBind(context, &ImageLoaderMachOCompressed::dynamicInterposeAt);
1516 }
1517
1518 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr, const void** closestAddr) const
1519 {
1520 return ImageLoaderMachO::findClosestSymbol((mach_header*)fMachOData, addr, closestAddr);
1521 }
1522
1523
1524 #if PREBOUND_IMAGE_SUPPORT
1525 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext& context)
1526 {
1527 // no way to back off a prebound compress image
1528 }
1529 #endif
1530
1531
1532 #if __arm__ || __x86_64__
1533 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub, void** originalLazyPointerAddr, const LinkContext& context)
1534 {
1535 #if __arm__
1536 uint32_t* instructions = (uint32_t*)stub;
1537 // sanity check this is a stub we understand
1538 if ( (instructions[0] != 0xe59fc004) || (instructions[1] != 0xe08fc00c) || (instructions[2] != 0xe59cf000) )
1539 return;
1540
1541 void** lazyPointerAddr = (void**)(instructions[3] + (stub + 12));
1542 #endif
1543 #if __x86_64__
1544 // sanity check this is a stub we understand
1545 if ( (stub[0] != 0xFF) || (stub[1] != 0x25) )
1546 return;
1547 int32_t ripOffset = *((int32_t*)(&stub[2]));
1548 void** lazyPointerAddr = (void**)(ripOffset + stub + 6);
1549 #endif
1550
1551 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1552 if ( lazyPointerAddr != originalLazyPointerAddr ) {
1553 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1554 const ImageLoader* lazyPointerImage = context.findImageContainingAddress(lazyPointerAddr);
1555 if ( lazyPointerImage != NULL )
1556 return;
1557
1558 // copy newly re-bound lazy pointer value to shared lazy pointer
1559 *lazyPointerAddr = *originalLazyPointerAddr;
1560
1561 if ( context.verboseBind )
1562 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1563 this->getShortName(), (long)lazyPointerAddr, (long)*originalLazyPointerAddr);
1564 }
1565 }
1566 #endif
1567
1568
1569 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1570 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext& context)
1571 {
1572 #if __arm__ || __x86_64__
1573 // find stubs and indirect symbol table
1574 const struct macho_section* stubsSection = NULL;
1575 const dysymtab_command* dynSymbolTable = NULL;
1576 const macho_header* mh = (macho_header*)fMachOData;
1577 const uint32_t cmd_count = mh->ncmds;
1578 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1579 const struct load_command* cmd = cmds;
1580 for (uint32_t i = 0; i < cmd_count; ++i) {
1581 if (cmd->cmd == LC_SEGMENT_COMMAND) {
1582 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1583 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1584 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1585 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1586 const uint8_t type = sect->flags & SECTION_TYPE;
1587 if ( type == S_SYMBOL_STUBS )
1588 stubsSection = sect;
1589 }
1590 }
1591 else if ( cmd->cmd == LC_DYSYMTAB ) {
1592 dynSymbolTable = (struct dysymtab_command*)cmd;
1593 }
1594 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1595 }
1596 if ( dynSymbolTable == NULL )
1597 return;
1598 const uint32_t* const indirectTable = (uint32_t*)&fLinkEditBase[dynSymbolTable->indirectsymoff];
1599 if ( stubsSection == NULL )
1600 return;
1601 const uint32_t stubsSize = stubsSection->reserved2;
1602 const uint32_t stubsCount = (uint32_t)(stubsSection->size / stubsSize);
1603 const uint32_t stubsIndirectTableOffset = stubsSection->reserved1;
1604 if ( (stubsIndirectTableOffset+stubsCount) > dynSymbolTable->nindirectsyms )
1605 return;
1606 uint8_t* const stubsAddr = (uint8_t*)(stubsSection->addr + this->fSlide);
1607
1608 // for each lazy pointer section
1609 cmd = cmds;
1610 for (uint32_t i = 0; i < cmd_count; ++i) {
1611 if (cmd->cmd == LC_SEGMENT_COMMAND) {
1612 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1613 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1614 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1615 for (const struct macho_section* lazyPointerSection=sectionsStart; lazyPointerSection < sectionsEnd; ++lazyPointerSection) {
1616 const uint8_t type = lazyPointerSection->flags & SECTION_TYPE;
1617 if ( type != S_LAZY_SYMBOL_POINTERS )
1618 continue;
1619 const uint32_t lazyPointersCount = (uint32_t)(lazyPointerSection->size / sizeof(void*));
1620 const uint32_t lazyPointersIndirectTableOffset = lazyPointerSection->reserved1;
1621 if ( (lazyPointersIndirectTableOffset+lazyPointersCount) > dynSymbolTable->nindirectsyms )
1622 continue;
1623 void** const lazyPointersAddr = (void**)(lazyPointerSection->addr + this->fSlide);
1624 // for each lazy pointer
1625 for(uint32_t lpIndex=0; lpIndex < lazyPointersCount; ++lpIndex) {
1626 const uint32_t lpSymbolIndex = indirectTable[lazyPointersIndirectTableOffset+lpIndex];
1627 // find matching stub and validate it uses this lazy pointer
1628 for(uint32_t stubIndex=0; stubIndex < stubsCount; ++stubIndex) {
1629 if ( indirectTable[stubsIndirectTableOffset+stubIndex] == lpSymbolIndex ) {
1630 this->updateAlternateLazyPointer(stubsAddr+stubIndex*stubsSize, &lazyPointersAddr[lpIndex], context);
1631 break;
1632 }
1633 }
1634 }
1635
1636 }
1637 }
1638 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1639 }
1640
1641 #endif
1642 }
1643
1644
1645 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command* encryptCmd, const LinkContext& context)
1646 {
1647 #if __arm__ || __arm64__
1648 if ( encryptCmd == NULL )
1649 return;
1650 const mach_header* mh = NULL;
1651 for(unsigned int i=0; i < fSegmentsCount; ++i) {
1652 if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
1653 mh = (mach_header*)segActualLoadAddress(i);
1654 break;
1655 }
1656 }
1657 void* start = ((uint8_t*)mh) + encryptCmd->cryptoff;
1658 size_t len = encryptCmd->cryptsize;
1659 uint32_t cputype = mh->cputype;
1660 uint32_t cpusubtype = mh->cpusubtype;
1661 uint32_t cryptid = encryptCmd->cryptid;
1662 if (context.verboseMapping) {
1663 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start, (long)start+len);
1664 }
1665 int result = mremap_encrypted(start, len, cryptid, cputype, cpusubtype);
1666 if ( result != 0 ) {
1667 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result, errno, this->getPath());
1668 }
1669 #endif
1670 }
1671
1672
1673