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