dyld-655.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 <mach/mach.h>
39 #include <mach/thread_status.h>
40 #include <mach-o/loader.h>
41 #include "ImageLoaderMachOCompressed.h"
42 #include "mach-o/dyld_images.h"
43 #include "Closure.h"
44 #include "Array.h"
45
46 #ifndef EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
47 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
48 #endif
49
50
51 #ifndef BIND_OPCODE_THREADED
52 #define BIND_OPCODE_THREADED 0xD0
53 #endif
54
55 #ifndef BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB
56 #define BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB 0x00
57 #endif
58
59 #ifndef BIND_SUBOPCODE_THREADED_APPLY
60 #define BIND_SUBOPCODE_THREADED_APPLY 0x01
61 #endif
62
63
64 #ifndef BIND_SPECIAL_DYLIB_WEAK_LOOKUP
65 #define BIND_SPECIAL_DYLIB_WEAK_LOOKUP -3
66 #endif
67
68 #ifndef CPU_SUBTYPE_ARM64_E
69 #define CPU_SUBTYPE_ARM64_E 2
70 #endif
71
72 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
73 #if __LP64__
74 #define RELOC_SIZE 3
75 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
76 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
77 struct macho_segment_command : public segment_command_64 {};
78 struct macho_section : public section_64 {};
79 struct macho_routines_command : public routines_command_64 {};
80 #else
81 #define RELOC_SIZE 2
82 #define LC_SEGMENT_COMMAND LC_SEGMENT
83 #define LC_ROUTINES_COMMAND LC_ROUTINES
84 struct macho_segment_command : public segment_command {};
85 struct macho_section : public section {};
86 struct macho_routines_command : public routines_command {};
87 #endif
88
89
90
91 // create image for main executable
92 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header* mh, uintptr_t slide, const char* path,
93 unsigned int segCount, unsigned int libCount, const LinkContext& context)
94 {
95 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, path, segCount, libCount);
96
97 // set slide for PIE programs
98 image->setSlide(slide);
99
100 // for PIE record end of program, to know where to start loading dylibs
101 if ( slide != 0 )
102 fgNextPIEDylibAddress = (uintptr_t)image->getEnd();
103
104 image->disableCoverageCheck();
105 image->instantiateFinish(context);
106 image->setMapped(context);
107
108 if ( context.verboseMapping ) {
109 dyld::log("dyld: Main executable mapped %s\n", path);
110 for(unsigned int i=0, e=image->segmentCount(); i < e; ++i) {
111 const char* name = image->segName(i);
112 if ( (strcmp(name, "__PAGEZERO") == 0) || (strcmp(name, "__UNIXSTACK") == 0) )
113 dyld::log("%18s at 0x%08lX->0x%08lX\n", name, image->segPreferredLoadAddress(i), image->segPreferredLoadAddress(i)+image->segSize(i));
114 else
115 dyld::log("%18s at 0x%08lX->0x%08lX\n", name, image->segActualLoadAddress(i), image->segActualEndAddress(i));
116 }
117 }
118
119 return image;
120 }
121
122 // create image by mapping in a mach-o file
123 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromFile(const char* path, int fd, const uint8_t* fileData, size_t lenFileData,
124 uint64_t offsetInFat, uint64_t lenInFat, const struct stat& info,
125 unsigned int segCount, unsigned int libCount,
126 const struct linkedit_data_command* codeSigCmd,
127 const struct encryption_info_command* encryptCmd,
128 const LinkContext& context)
129 {
130 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart((macho_header*)fileData, path, segCount, libCount);
131
132 try {
133 // record info about file
134 image->setFileInfo(info.st_dev, info.st_ino, info.st_mtime);
135
136 // if this image is code signed, let kernel validate signature before mapping any pages from image
137 image->loadCodeSignature(codeSigCmd, fd, offsetInFat, context);
138
139 // Validate that first data we read with pread actually matches with code signature
140 image->validateFirstPages(codeSigCmd, fd, fileData, lenFileData, offsetInFat, context);
141
142 // mmap segments
143 image->mapSegments(fd, offsetInFat, lenInFat, info.st_size, context);
144
145 // if framework is FairPlay encrypted, register with kernel
146 image->registerEncryption(encryptCmd, context);
147
148 // probe to see if code signed correctly
149 image->crashIfInvalidCodeSignature();
150
151 // finish construction
152 image->instantiateFinish(context);
153
154 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
155 const char* installName = image->getInstallPath();
156 if ( (installName != NULL) && (strcmp(installName, path) == 0) && (path[0] == '/') )
157 image->setPathUnowned(installName);
158 #if __MAC_OS_X_VERSION_MIN_REQUIRED
159 // <rdar://problem/6563887> app crashes when libSystem cannot be found
160 else if ( (installName != NULL) && (strcmp(path, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName, "/usr/lib/libSystem.B.dylib") == 0) )
161 image->setPathUnowned("/usr/lib/libSystem.B.dylib");
162 #endif
163 else if ( (path[0] != '/') || (strstr(path, "../") != NULL) ) {
164 // rdar://problem/10733082 Fix up @rpath based paths during introspection
165 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
166 char realPath[MAXPATHLEN];
167 if ( fcntl(fd, F_GETPATH, realPath) == 0 )
168 image->setPaths(path, realPath);
169 else
170 image->setPath(path);
171 }
172 else
173 image->setPath(path);
174
175 // make sure path is stable before recording in dyld_all_image_infos
176 image->setMapped(context);
177
178 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
179 // don't do this on prebound images or if prefetching is disabled
180 if ( !context.preFetchDisabled && !image->isPrebindable()) {
181 image->preFetchDATA(fd, offsetInFat, context);
182 image->markSequentialLINKEDIT(context);
183 }
184 }
185 catch (...) {
186 // ImageLoader::setMapped() can throw an exception to block loading of image
187 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
188 delete image;
189 throw;
190 }
191
192 return image;
193 }
194
195 // create image by using cached mach-o file
196 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header* mh, const char* path, long slide,
197 const struct stat& info, unsigned int segCount,
198 unsigned int libCount, const LinkContext& context)
199 {
200 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, path, segCount, libCount);
201 try {
202 // record info about file
203 image->setFileInfo(info.st_dev, info.st_ino, info.st_mtime);
204
205 // remember this is from shared cache and cannot be unloaded
206 image->fInSharedCache = true;
207 image->setNeverUnload();
208 image->setSlide(slide);
209 image->disableCoverageCheck();
210
211 // segments already mapped in cache
212 if ( context.verboseMapping ) {
213 dyld::log("dyld: Using shared cached for %s\n", path);
214 for(unsigned int i=0; i < image->fSegmentsCount; ++i) {
215 dyld::log("%18s at 0x%08lX->0x%08lX\n", image->segName(i), image->segActualLoadAddress(i), image->segActualEndAddress(i));
216 }
217 }
218
219 image->instantiateFinish(context);
220 image->setMapped(context);
221 }
222 catch (...) {
223 // ImageLoader::setMapped() can throw an exception to block loading of image
224 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
225 delete image;
226 throw;
227 }
228
229 return image;
230 }
231
232 // create image by copying an in-memory mach-o file
233 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName, const macho_header* mh, uint64_t len,
234 unsigned int segCount, unsigned int libCount, const LinkContext& context)
235 {
236 ImageLoaderMachOCompressed* image = ImageLoaderMachOCompressed::instantiateStart(mh, moduleName, segCount, libCount);
237 try {
238 // map segments
239 if ( mh->filetype == MH_EXECUTE )
240 throw "can't load another MH_EXECUTE";
241
242 // vmcopy segments
243 image->mapSegments((const void*)mh, len, context);
244
245 // for compatibility, never unload dylibs loaded from memory
246 image->setNeverUnload();
247
248 image->disableCoverageCheck();
249
250 // bundle loads need path copied
251 if ( moduleName != NULL )
252 image->setPath(moduleName);
253
254 image->instantiateFinish(context);
255 image->setMapped(context);
256 }
257 catch (...) {
258 // ImageLoader::setMapped() can throw an exception to block loading of image
259 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
260 delete image;
261 throw;
262 }
263
264 return image;
265 }
266
267
268 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header* mh, const char* path, unsigned int segCount,
269 uint32_t segOffsets[], unsigned int libCount)
270 : ImageLoaderMachO(mh, path, segCount, segOffsets, libCount), fDyldInfo(NULL)
271 {
272 }
273
274 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
275 {
276 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
277 destroy();
278 }
279
280
281
282 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
283 ImageLoaderMachOCompressed* ImageLoaderMachOCompressed::instantiateStart(const macho_header* mh, const char* path,
284 unsigned int segCount, unsigned int libCount)
285 {
286 size_t size = sizeof(ImageLoaderMachOCompressed) + segCount * sizeof(uint32_t) + libCount * sizeof(ImageLoader*);
287 ImageLoaderMachOCompressed* allocatedSpace = static_cast<ImageLoaderMachOCompressed*>(malloc(size));
288 if ( allocatedSpace == NULL )
289 throw "malloc failed";
290 uint32_t* segOffsets = ((uint32_t*)(((uint8_t*)allocatedSpace) + sizeof(ImageLoaderMachOCompressed)));
291 bzero(&segOffsets[segCount], libCount*sizeof(void*)); // zero out lib array
292 return new (allocatedSpace) ImageLoaderMachOCompressed(mh, path, segCount, segOffsets, libCount);
293 }
294
295
296 // common code to finish initializing object
297 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext& context)
298 {
299 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
300 this->parseLoadCmds(context);
301 }
302
303 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
304 {
305 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed)));
306 }
307
308
309 ImageLoader* ImageLoaderMachOCompressed::libImage(unsigned int libIndex) const
310 {
311 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
312 // mask off low bits
313 return (ImageLoader*)(images[libIndex] & (-4));
314 }
315
316 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex) const
317 {
318 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
319 // re-export flag is low bit
320 return ((images[libIndex] & 1) != 0);
321 }
322
323 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex) const
324 {
325 const uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
326 // re-export flag is second bit
327 return ((images[libIndex] & 2) != 0);
328 }
329
330
331 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex, ImageLoader* image, bool reExported, bool upward)
332 {
333 uintptr_t* images = ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed) + fSegmentsCount*sizeof(uint32_t)));
334 uintptr_t value = (uintptr_t)image;
335 if ( reExported )
336 value |= 1;
337 if ( upward )
338 value |= 2;
339 images[libIndex] = value;
340 }
341
342
343 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext& context)
344 {
345 // mark that we are done with rebase and bind info
346 markLINKEDIT(context, MADV_FREE);
347 }
348
349 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext& context)
350 {
351 // mark the rebase and bind info and using sequential access
352 markLINKEDIT(context, MADV_SEQUENTIAL);
353 }
354
355 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext& context, int advise)
356 {
357 // if not loaded at preferred address, mark rebase info
358 uintptr_t start = 0;
359 if ( (fSlide != 0) && (fDyldInfo->rebase_size != 0) )
360 start = (uintptr_t)fLinkEditBase + fDyldInfo->rebase_off;
361 else if ( fDyldInfo->bind_off != 0 )
362 start = (uintptr_t)fLinkEditBase + fDyldInfo->bind_off;
363 else
364 return; // no binding info to prefetch
365
366 // end is at end of bind info
367 uintptr_t end = 0;
368 if ( fDyldInfo->bind_off != 0 )
369 end = (uintptr_t)fLinkEditBase + fDyldInfo->bind_off + fDyldInfo->bind_size;
370 else if ( fDyldInfo->rebase_off != 0 )
371 end = (uintptr_t)fLinkEditBase + fDyldInfo->rebase_off + fDyldInfo->rebase_size;
372 else
373 return;
374
375
376 // round to whole pages
377 start = dyld_page_trunc(start);
378 end = dyld_page_round(end);
379
380 // do nothing if only one page of rebase/bind info
381 if ( (end-start) <= dyld_page_size )
382 return;
383
384 // tell kernel about our access to these pages
385 madvise((void*)start, end-start, advise);
386 if ( context.verboseMapping ) {
387 const char* adstr = "sequential";
388 if ( advise == MADV_FREE )
389 adstr = "free";
390 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr, start, end-1, this->getPath());
391 }
392 }
393
394
395
396 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext& context, uintptr_t addr, uintptr_t slide, uint8_t type)
397 {
398 if ( context.verboseRebase ) {
399 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr, slide);
400 }
401 //dyld::log("0x%08lX type=%d\n", addr, type);
402 uintptr_t* locationToFix = (uintptr_t*)addr;
403 switch (type) {
404 case REBASE_TYPE_POINTER:
405 *locationToFix += slide;
406 break;
407 case REBASE_TYPE_TEXT_ABSOLUTE32:
408 *locationToFix += slide;
409 break;
410 default:
411 dyld::throwf("bad rebase type %d", type);
412 }
413 }
414
415 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address, uintptr_t segmentEndAddress, int segmentIndex,
416 const uint8_t* startOpcodes, const uint8_t* endOpcodes, const uint8_t* pos)
417 {
418 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
419 (intptr_t)(pos-startOpcodes), (intptr_t)(endOpcodes-startOpcodes), address, segName(segmentIndex),
420 segActualLoadAddress(segmentIndex), segmentEndAddress);
421 }
422
423 void ImageLoaderMachOCompressed::rebase(const LinkContext& context, uintptr_t slide)
424 {
425 CRSetCrashLogMessage2(this->getPath());
426 const uint8_t* const start = fLinkEditBase + fDyldInfo->rebase_off;
427 const uint8_t* const end = &start[fDyldInfo->rebase_size];
428 const uint8_t* p = start;
429
430 try {
431 uint8_t type = 0;
432 int segmentIndex = 0;
433 uintptr_t address = segActualLoadAddress(0);
434 uintptr_t segmentStartAddress = segActualLoadAddress(0);
435 uintptr_t segmentEndAddress = segActualEndAddress(0);
436 uintptr_t count;
437 uintptr_t skip;
438 bool done = false;
439 while ( !done && (p < end) ) {
440 uint8_t immediate = *p & REBASE_IMMEDIATE_MASK;
441 uint8_t opcode = *p & REBASE_OPCODE_MASK;
442 ++p;
443 switch (opcode) {
444 case REBASE_OPCODE_DONE:
445 done = true;
446 break;
447 case REBASE_OPCODE_SET_TYPE_IMM:
448 type = immediate;
449 break;
450 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
451 segmentIndex = immediate;
452 if ( segmentIndex >= fSegmentsCount )
453 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
454 segmentIndex, fSegmentsCount-1);
455 #if TEXT_RELOC_SUPPORT
456 if ( !segWriteable(segmentIndex) && !segHasRebaseFixUps(segmentIndex) && !segHasBindFixUps(segmentIndex) )
457 #else
458 if ( !segWriteable(segmentIndex) )
459 #endif
460 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
461 segmentIndex, segName(segmentIndex));
462 segmentStartAddress = segActualLoadAddress(segmentIndex);
463 segmentEndAddress = segActualEndAddress(segmentIndex);
464 address = segmentStartAddress + read_uleb128(p, end);
465 break;
466 case REBASE_OPCODE_ADD_ADDR_ULEB:
467 address += read_uleb128(p, end);
468 break;
469 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
470 address += immediate*sizeof(uintptr_t);
471 break;
472 case REBASE_OPCODE_DO_REBASE_IMM_TIMES:
473 for (int i=0; i < immediate; ++i) {
474 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
475 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
476 rebaseAt(context, address, slide, type);
477 address += sizeof(uintptr_t);
478 }
479 fgTotalRebaseFixups += immediate;
480 break;
481 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
482 count = 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 += sizeof(uintptr_t);
488 }
489 fgTotalRebaseFixups += count;
490 break;
491 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
492 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
493 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
494 rebaseAt(context, address, slide, type);
495 address += read_uleb128(p, end) + sizeof(uintptr_t);
496 ++fgTotalRebaseFixups;
497 break;
498 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
499 count = read_uleb128(p, end);
500 skip = read_uleb128(p, end);
501 for (uint32_t i=0; i < count; ++i) {
502 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
503 throwBadRebaseAddress(address, segmentEndAddress, segmentIndex, start, end, p);
504 rebaseAt(context, address, slide, type);
505 address += skip + sizeof(uintptr_t);
506 }
507 fgTotalRebaseFixups += count;
508 break;
509 default:
510 dyld::throwf("bad rebase opcode %d", *(p-1));
511 }
512 }
513 }
514 catch (const char* msg) {
515 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
516 free((void*)msg);
517 throw newMsg;
518 }
519 CRSetCrashLogMessage2(NULL);
520 }
521
522 const ImageLoader::Symbol* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol, const ImageLoader** foundIn) const
523 {
524 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
525 if ( fDyldInfo->export_size == 0 )
526 return NULL;
527 #if LOG_BINDINGS
528 dyld::logBindings("%s: %s\n", this->getShortName(), symbol);
529 #endif
530 ++ImageLoaderMachO::fgSymbolTrieSearchs;
531 const uint8_t* start = &fLinkEditBase[fDyldInfo->export_off];
532 const uint8_t* end = &start[fDyldInfo->export_size];
533 const uint8_t* foundNodeStart = this->trieWalk(start, end, symbol);
534 if ( foundNodeStart != NULL ) {
535 const uint8_t* p = foundNodeStart;
536 const uintptr_t flags = read_uleb128(p, end);
537 // found match, return pointer to terminal part of node
538 if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) {
539 // re-export from another dylib, lookup there
540 const uintptr_t ordinal = read_uleb128(p, end);
541 const char* importedName = (char*)p;
542 if ( importedName[0] == '\0' )
543 importedName = symbol;
544 if ( (ordinal > 0) && (ordinal <= libraryCount()) ) {
545 const ImageLoader* reexportedFrom = libImage((unsigned int)ordinal-1);
546 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
547 const char* reExportLibPath = libPath((unsigned int)ordinal-1);
548 return reexportedFrom->findExportedSymbol(importedName, true, reExportLibPath, foundIn);
549 }
550 else {
551 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
552 // ordinal, libraryCount(), symbol, this->getPath());
553 }
554 }
555 else {
556 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
557 if ( foundIn != NULL )
558 *foundIn = (ImageLoader*)this;
559 // return pointer to terminal part of node
560 return (Symbol*)foundNodeStart;
561 }
562 }
563 return NULL;
564 }
565
566
567 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr) const
568 {
569 const uint8_t* start = &fLinkEditBase[fDyldInfo->export_off];
570 const uint8_t* end = &start[fDyldInfo->export_size];
571 return ( (start <= addr) && (addr < end) );
572 }
573
574
575 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext& context, const Symbol* symbol, const ImageLoader* requestor, bool runResolver) const
576 {
577 const uint8_t* exportNode = (uint8_t*)symbol;
578 const uint8_t* exportTrieStart = fLinkEditBase + fDyldInfo->export_off;
579 const uint8_t* exportTrieEnd = exportTrieStart + fDyldInfo->export_size;
580 if ( (exportNode < exportTrieStart) || (exportNode > exportTrieEnd) )
581 throw "symbol is not in trie";
582 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
583 uintptr_t flags = read_uleb128(exportNode, exportTrieEnd);
584 switch ( flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) {
585 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR:
586 if ( runResolver && (flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) ) {
587 // this node has a stub and resolver, run the resolver to get target address
588 uintptr_t stub = read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData; // skip over stub
589 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
590 uintptr_t interposedStub = interposedAddress(context, stub, requestor);
591 if ( interposedStub != stub )
592 return interposedStub;
593 // stub was not interposed, so run resolver
594 typedef uintptr_t (*ResolverProc)(void);
595 ResolverProc resolver = (ResolverProc)(read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData);
596 uintptr_t result = (*resolver)();
597 if ( context.verboseBind )
598 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver, result);
599 return result;
600 }
601 return read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData;
602 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL:
603 if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER )
604 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
605 return read_uleb128(exportNode, exportTrieEnd) + (uintptr_t)fMachOData;
606 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE:
607 if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER )
608 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
609 return read_uleb128(exportNode, exportTrieEnd);
610 default:
611 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags, symbol);
612 }
613 }
614
615 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol* symbol) const
616 {
617 const uint8_t* exportNode = (uint8_t*)symbol;
618 const uint8_t* exportTrieStart = fLinkEditBase + fDyldInfo->export_off;
619 const uint8_t* exportTrieEnd = exportTrieStart + fDyldInfo->export_size;
620 if ( (exportNode < exportTrieStart) || (exportNode > exportTrieEnd) )
621 throw "symbol is not in trie";
622 uintptr_t flags = read_uleb128(exportNode, exportTrieEnd);
623 return ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION );
624 }
625
626
627 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol* symbol) const
628 {
629 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
630 }
631
632 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
633 {
634 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
635 }
636
637 const ImageLoader::Symbol* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index) const
638 {
639 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
640 }
641
642 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
643 {
644 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
645 }
646
647 const ImageLoader::Symbol* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index) const
648 {
649 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
650 }
651
652 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol* symbol) const
653 {
654 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
655 }
656
657
658
659 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext& context, const char* symbolName, bool weak_import,
660 bool runResolver, const ImageLoader** foundIn)
661 {
662 const Symbol* sym;
663 if ( context.flatExportFinder(symbolName, &sym, foundIn) ) {
664 if ( *foundIn != this )
665 context.addDynamicReference(this, const_cast<ImageLoader*>(*foundIn));
666 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
667 }
668 // if a bundle is loaded privately the above will not find its exports
669 if ( this->isBundle() && this->hasHiddenExports() ) {
670 // look in self for needed symbol
671 sym = this->findShallowExportedSymbol(symbolName, foundIn);
672 if ( sym != NULL )
673 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
674 }
675 if ( weak_import ) {
676 // definition can't be found anywhere, ok because it is weak, just return 0
677 return 0;
678 }
679 throwSymbolNotFound(context, symbolName, this->getPath(), "", "flat namespace");
680 }
681
682
683 #if USES_CHAINED_BINDS
684 static void patchCacheUsesOf(const ImageLoader::LinkContext& context, const dyld3::closure::Image* overriddenImage,
685 uint32_t cacheOffsetOfImpl, const char* symbolName, uintptr_t newImpl)
686 {
687 uintptr_t cacheStart = (uintptr_t)context.dyldCache;
688 overriddenImage->forEachPatchableUseOfExport(cacheOffsetOfImpl, ^(dyld3::closure::Image::PatchableExport::PatchLocation patchLocation) {
689 uintptr_t* loc = (uintptr_t*)(cacheStart+patchLocation.cacheOffset);
690 #if __has_feature(ptrauth_calls)
691 if ( patchLocation.authenticated ) {
692 dyld3::MachOLoaded::ChainedFixupPointerOnDisk fixupInfo;
693 fixupInfo.authRebase.auth = true;
694 fixupInfo.authRebase.addrDiv = patchLocation.usesAddressDiversity;
695 fixupInfo.authRebase.diversity = patchLocation.discriminator;
696 fixupInfo.authRebase.key = patchLocation.key;
697 uintptr_t newValue = fixupInfo.signPointer(loc, newImpl + patchLocation.getAddend());
698 if ( *loc != newValue ) {
699 *loc = newValue;
700 if ( context.verboseBind )
701 dyld::log("dyld: cache fixup: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s) to %s\n",
702 loc, (void*)newValue, patchLocation.discriminator, patchLocation.usesAddressDiversity, patchLocation.keyName(), symbolName);
703 }
704 return;
705 }
706 #endif
707 uintptr_t newValue =newImpl + patchLocation.getAddend();
708 if ( *loc != newValue ) {
709 *loc = newValue;
710 if ( context.verboseBind )
711 dyld::log("dyld: cache fixup: *%p = %p to %s\n", loc, (void*)newValue, symbolName);
712 }
713 });
714 }
715 #endif
716
717
718 uintptr_t ImageLoaderMachOCompressed::resolveWeak(const LinkContext& context, const char* symbolName, bool weak_import,
719 bool runResolver, const ImageLoader** foundIn)
720 {
721 const Symbol* sym;
722 #if USES_CHAINED_BINDS
723 __block uintptr_t foundOutsideCache = 0;
724 __block uintptr_t lastFoundInCache = 0;
725 CoalesceNotifier notifier = ^(const Symbol* implSym, const ImageLoader* implIn, const mach_header* implMh) {
726 //dyld::log("notifier: found %s in %p %s\n", symbolName, implMh, implIn->getPath());
727 // This block is only called in dyld2 mode when a non-cached image is search for which weak-def implementation to use
728 // As a side effect of that search we notice any implementations outside and inside the cache,
729 // and use that to trigger patching the cache to use the implementation outside the cache.
730 uintptr_t implAddr = implIn->getExportedSymbolAddress(implSym, context, nullptr, false, symbolName);
731 if ( ((dyld3::MachOLoaded*)implMh)->inDyldCache() ) {
732 if ( foundOutsideCache != 0 ) {
733 // have an implementation in cache and and earlier one not in the cache, patch cache to use earlier one
734 lastFoundInCache = implAddr;
735 uint32_t imageIndex;
736 if ( context.dyldCache->findMachHeaderImageIndex(implMh, imageIndex) ) {
737 const dyld3::closure::Image* overriddenImage = context.dyldCache->cachedDylibsImageArray()->imageForNum(imageIndex+1);
738 uint32_t cacheOffsetOfImpl = (uint32_t)((uintptr_t)implAddr - (uintptr_t)context.dyldCache);
739 patchCacheUsesOf(context, overriddenImage, cacheOffsetOfImpl, symbolName, foundOutsideCache);
740 }
741 }
742 }
743 else {
744 // record first non-cache implementation
745 if ( foundOutsideCache == 0 )
746 foundOutsideCache = implAddr;
747 }
748 };
749 #else
750 CoalesceNotifier notifier = nullptr;
751 #endif
752 if ( context.coalescedExportFinder(symbolName, &sym, foundIn, notifier) ) {
753 if ( *foundIn != this )
754 context.addDynamicReference(this, const_cast<ImageLoader*>(*foundIn));
755 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
756 }
757 // if a bundle is loaded privately the above will not find its exports
758 if ( this->isBundle() && this->hasHiddenExports() ) {
759 // look in self for needed symbol
760 sym = this->findShallowExportedSymbol(symbolName, foundIn);
761 if ( sym != NULL )
762 return (*foundIn)->getExportedSymbolAddress(sym, context, this, runResolver);
763 }
764 if ( weak_import ) {
765 // definition can't be found anywhere, ok because it is weak, just return 0
766 return 0;
767 }
768 throwSymbolNotFound(context, symbolName, this->getPath(), "", "weak");
769 }
770
771
772 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext& context, const char* symbolName, const ImageLoader* definedInImage,
773 const ImageLoader* requestorImage, unsigned requestorOrdinalOfDef, bool weak_import, bool runResolver,
774 const ImageLoader** foundIn)
775 {
776 // two level lookup
777 uintptr_t address;
778 if ( definedInImage->findExportedSymbolAddress(context, symbolName, requestorImage, requestorOrdinalOfDef, runResolver, foundIn, &address) )
779 return address;
780
781 if ( weak_import ) {
782 // definition can't be found anywhere, ok because it is weak, just return 0
783 return 0;
784 }
785
786 // nowhere to be found, check if maybe this image is too new for this OS
787 char versMismatch[256];
788 versMismatch[0] = '\0';
789 uint32_t imageMinOS = this->minOSVersion();
790 // dyld is always built for the current OS, so we can get the current OS version
791 // from the load command in dyld itself.
792 extern const mach_header __dso_handle;
793 uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion(&__dso_handle);
794 if ( imageMinOS > dyldMinOS ) {
795 #if __MAC_OS_X_VERSION_MIN_REQUIRED
796 const char* msg = dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS >> 16, (imageMinOS >> 8) & 0xFF);
797 #else
798 const char* msg = dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS >> 16, (imageMinOS >> 8) & 0xFF);
799 #endif
800 strcpy(versMismatch, msg);
801 ::free((void*)msg);
802 }
803 throwSymbolNotFound(context, symbolName, this->getPath(), versMismatch, definedInImage->getPath());
804 }
805
806
807 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext& context, const char* symbolName,
808 uint8_t symboFlags, long libraryOrdinal, const ImageLoader** targetImage,
809 LastLookup* last, bool runResolver)
810 {
811 *targetImage = NULL;
812
813 // only clients that benefit from caching last lookup pass in a LastLookup struct
814 if ( last != NULL ) {
815 if ( (last->ordinal == libraryOrdinal)
816 && (last->flags == symboFlags)
817 && (last->name == symbolName) ) {
818 *targetImage = last->foundIn;
819 return last->result;
820 }
821 }
822
823 bool weak_import = (symboFlags & BIND_SYMBOL_FLAGS_WEAK_IMPORT);
824 uintptr_t symbolAddress;
825 if ( context.bindFlat || (libraryOrdinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP) ) {
826 symbolAddress = this->resolveFlat(context, symbolName, weak_import, runResolver, targetImage);
827 }
828 else if ( libraryOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP ) {
829 symbolAddress = this->resolveWeak(context, symbolName, false, runResolver, targetImage);
830 }
831 else {
832 if ( libraryOrdinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE ) {
833 *targetImage = context.mainExecutable;
834 }
835 else if ( libraryOrdinal == BIND_SPECIAL_DYLIB_SELF ) {
836 *targetImage = this;
837 }
838 else if ( libraryOrdinal <= 0 ) {
839 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
840 libraryOrdinal, symbolName, this->getPath());
841 }
842 else if ( (unsigned)libraryOrdinal <= libraryCount() ) {
843 *targetImage = libImage((unsigned int)libraryOrdinal-1);
844 }
845 else {
846 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
847 libraryOrdinal, libraryCount(), symbolName, this->getPath());
848 }
849 if ( *targetImage == NULL ) {
850 if ( weak_import ) {
851 // if target library not loaded and reference is weak or library is weak return 0
852 symbolAddress = 0;
853 }
854 else {
855 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
856 symbolName, this->getPath(), libraryOrdinal);
857 }
858 }
859 else {
860 symbolAddress = resolveTwolevel(context, symbolName, *targetImage, this, (unsigned)libraryOrdinal, weak_import, runResolver, targetImage);
861 }
862 }
863
864 // save off lookup results if client wants
865 if ( last != NULL ) {
866 last->ordinal = libraryOrdinal;
867 last->flags = symboFlags;
868 last->name = symbolName;
869 last->foundIn = *targetImage;
870 last->result = symbolAddress;
871 }
872
873 return symbolAddress;
874 }
875
876 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext& context, ImageLoaderMachOCompressed* image,
877 uintptr_t addr, uint8_t type, const char* symbolName,
878 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
879 ExtraBindData *extraBindData,
880 const char* msg, LastLookup* last, bool runResolver)
881 {
882 const ImageLoader* targetImage;
883 uintptr_t symbolAddress;
884
885 // resolve symbol
886 if (type == BIND_TYPE_THREADED_REBASE) {
887 symbolAddress = 0;
888 targetImage = nullptr;
889 } else
890 symbolAddress = image->resolve(context, symbolName, symbolFlags, libraryOrdinal, &targetImage, last, runResolver);
891
892 // do actual update
893 return image->bindLocation(context, image->imageBaseAddress(), addr, symbolAddress, type, symbolName, addend, image->getPath(), targetImage ? targetImage->getPath() : NULL, msg, extraBindData, image->fSlide);
894 }
895
896
897 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address, uintptr_t segmentEndAddress, int segmentIndex,
898 const uint8_t* startOpcodes, const uint8_t* endOpcodes, const uint8_t* pos)
899 {
900 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
901 (intptr_t)(pos-startOpcodes), (intptr_t)(endOpcodes-startOpcodes), address, segName(segmentIndex),
902 segActualLoadAddress(segmentIndex), segmentEndAddress);
903 }
904
905
906 void ImageLoaderMachOCompressed::doBind(const LinkContext& context, bool forceLazysBound)
907 {
908 CRSetCrashLogMessage2(this->getPath());
909
910 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
911 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
912 if ( this->usablePrebinding(context) ) {
913 // don't need to bind
914 // except weak which may now be inline with the regular binds
915 if (this->participatesInCoalescing()) {
916 // run through all binding opcodes
917 eachBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
918 uintptr_t addr, uint8_t type, const char* symbolName,
919 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
920 ExtraBindData *extraBindData,
921 const char* msg, LastLookup* last, bool runResolver) {
922 if ( libraryOrdinal != BIND_SPECIAL_DYLIB_WEAK_LOOKUP )
923 return (uintptr_t)0;
924 return ImageLoaderMachOCompressed::bindAt(ctx, image, addr, type, symbolName, symbolFlags,
925 addend, libraryOrdinal, extraBindData,
926 msg, last, runResolver);
927 });
928 }
929 }
930 else {
931 uint64_t t0 = mach_absolute_time();
932
933 #if TEXT_RELOC_SUPPORT
934 // if there are __TEXT fixups, temporarily make __TEXT writable
935 if ( fTextSegmentBinds )
936 this->makeTextSegmentWritable(context, true);
937 #endif
938
939 uint32_t ignore;
940 bool bindingBecauseOfRoot = ( this->overridesCachedDylib(ignore) || this->inSharedCache() );
941 vmAccountingSetSuspended(context, bindingBecauseOfRoot);
942
943 // run through all binding opcodes
944 eachBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
945 uintptr_t addr, uint8_t type, const char* symbolName,
946 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
947 ExtraBindData *extraBindData,
948 const char* msg, LastLookup* last, bool runResolver) {
949 return ImageLoaderMachOCompressed::bindAt(ctx, image, addr, type, symbolName, symbolFlags,
950 addend, libraryOrdinal, extraBindData,
951 msg, last, runResolver);
952 });
953
954 #if TEXT_RELOC_SUPPORT
955 // if there were __TEXT fixups, restore write protection
956 if ( fTextSegmentBinds )
957 this->makeTextSegmentWritable(context, false);
958 #endif
959
960 // if this image is in the shared cache, but depends on something no longer in the shared cache,
961 // there is no way to reset the lazy pointers, so force bind them now
962 if ( forceLazysBound || fInSharedCache )
963 this->doBindJustLazies(context);
964
965 // this image is in cache, but something below it is not. If
966 // this image has lazy pointer to a resolver function, then
967 // the stub may have been altered to point to a shared lazy pointer.
968 if ( fInSharedCache )
969 this->updateOptimizedLazyPointers(context);
970
971 // tell kernel we are done with chunks of LINKEDIT
972 if ( !context.preFetchDisabled )
973 this->markFreeLINKEDIT(context);
974
975 uint64_t t1 = mach_absolute_time();
976 ImageLoader::fgTotalRebindCacheTime += (t1-t0);
977 }
978
979 #if USES_CHAINED_BINDS
980 // See if this dylib overrides something in the dyld cache
981 uint32_t dyldCacheOverrideImageNum;
982 if ( context.dyldCache && overridesCachedDylib(dyldCacheOverrideImageNum) ) {
983 // need to patch all other places in cache that point to the overridden dylib, to point to this dylib instead
984 const dyld3::closure::Image* overriddenImage = context.dyldCache->cachedDylibsImageArray()->imageForNum(dyldCacheOverrideImageNum);
985 overriddenImage->forEachPatchableExport(^(uint32_t cacheOffsetOfImpl, const char* exportName) {
986 uintptr_t newImpl = 0;
987 const ImageLoader* foundIn;
988 if ( const ImageLoader::Symbol* sym = this->findShallowExportedSymbol(exportName, &foundIn) ) {
989 newImpl = foundIn->getExportedSymbolAddress(sym, context, this);
990 }
991 patchCacheUsesOf(context, overriddenImage, cacheOffsetOfImpl, exportName, newImpl);
992 });
993 }
994 #endif
995
996 // set up dyld entry points in image
997 // do last so flat main executables will have __dyld or __program_vars set up
998 this->setupLazyPointerHandler(context);
999 CRSetCrashLogMessage2(NULL);
1000 }
1001
1002
1003 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext& context)
1004 {
1005 eachLazyBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
1006 uintptr_t addr, uint8_t type, const char* symbolName,
1007 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1008 ExtraBindData *extraBindData,
1009 const char* msg, LastLookup* last, bool runResolver) {
1010 return ImageLoaderMachOCompressed::bindAt(ctx, image, addr, type, symbolName, symbolFlags,
1011 addend, libraryOrdinal, extraBindData,
1012 msg, last, runResolver);
1013 });
1014 }
1015
1016 void ImageLoaderMachOCompressed::registerInterposing(const LinkContext& context)
1017 {
1018 // mach-o files advertise interposing by having a __DATA __interpose section
1019 struct InterposeData { uintptr_t replacement; uintptr_t replacee; };
1020 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1021 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1022 const struct load_command* cmd = cmds;
1023 for (uint32_t i = 0; i < cmd_count; ++i) {
1024 switch (cmd->cmd) {
1025 case LC_SEGMENT_COMMAND:
1026 {
1027 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1028 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1029 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1030 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1031 if ( ((sect->flags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(sect->sectname, "__interpose") == 0) && (strcmp(seg->segname, "__DATA") == 0)) ) {
1032 // <rdar://problem/23929217> Ensure section is within segment
1033 if ( (sect->addr < seg->vmaddr) || (sect->addr+sect->size > seg->vmaddr+seg->vmsize) || (sect->addr+sect->size < sect->addr) )
1034 dyld::throwf("interpose section has malformed address range for %s\n", this->getPath());
1035 __block uintptr_t sectionStart = sect->addr + fSlide;
1036 __block uintptr_t sectionEnd = sectionStart + sect->size;
1037 const size_t count = sect->size / sizeof(InterposeData);
1038 InterposeData interposeArray[count];
1039 // Note, we memcpy here as rebases may have already been applied.
1040 memcpy(&interposeArray[0], (void*)sectionStart, sect->size);
1041 __block InterposeData *interposeArrayStart = &interposeArray[0];
1042 eachBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image, uintptr_t addr, uint8_t type,
1043 const char* symbolName, uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1044 ExtraBindData *extraBindData,
1045 const char* msg, LastLookup* last, bool runResolver) {
1046 if (addr >= sectionStart && addr < sectionEnd) {
1047 if ( context.verboseInterposing ) {
1048 dyld::log("dyld: interposing %s at 0x%lx in range 0x%lx..0x%lx\n",
1049 symbolName, addr, sectionStart, sectionEnd);
1050 }
1051 const ImageLoader* targetImage;
1052 uintptr_t symbolAddress;
1053
1054 // resolve symbol
1055 if (type == BIND_TYPE_THREADED_REBASE) {
1056 symbolAddress = 0;
1057 targetImage = nullptr;
1058 } else
1059 symbolAddress = image->resolve(ctx, symbolName, symbolFlags, libraryOrdinal, &targetImage, last, runResolver);
1060
1061 uintptr_t newValue = symbolAddress+addend;
1062 uintptr_t index = (addr - sectionStart) / sizeof(uintptr_t);
1063 switch (type) {
1064 case BIND_TYPE_POINTER:
1065 ((uintptr_t*)interposeArrayStart)[index] = newValue;
1066 break;
1067 case BIND_TYPE_TEXT_ABSOLUTE32:
1068 // unreachable!
1069 abort();
1070 case BIND_TYPE_TEXT_PCREL32:
1071 // unreachable!
1072 abort();
1073 case BIND_TYPE_THREADED_BIND:
1074 ((uintptr_t*)interposeArrayStart)[index] = newValue;
1075 break;
1076 case BIND_TYPE_THREADED_REBASE: {
1077 // Regular pointer which needs to fit in 51-bits of value.
1078 // C++ RTTI uses the top bit, so we'll allow the whole top-byte
1079 // and the signed-extended bottom 43-bits to be fit in to 51-bits.
1080 uint64_t top8Bits = (*(uint64_t*)addr) & 0x0007F80000000000ULL;
1081 uint64_t bottom43Bits = (*(uint64_t*)addr) & 0x000007FFFFFFFFFFULL;
1082 uint64_t targetValue = ( top8Bits << 13 ) | (((intptr_t)(bottom43Bits << 21) >> 21) & 0x00FFFFFFFFFFFFFF);
1083 newValue = (uintptr_t)(targetValue + fSlide);
1084 ((uintptr_t*)interposeArrayStart)[index] = newValue;
1085 break;
1086 }
1087 default:
1088 dyld::throwf("bad bind type %d", type);
1089 }
1090 }
1091 return (uintptr_t)0;
1092 });
1093 for (size_t j=0; j < count; ++j) {
1094 ImageLoader::InterposeTuple tuple;
1095 tuple.replacement = interposeArray[j].replacement;
1096 tuple.neverImage = this;
1097 tuple.onlyImage = NULL;
1098 tuple.replacee = interposeArray[j].replacee;
1099 if ( context.verboseInterposing ) {
1100 dyld::log("dyld: interposing index %d 0x%lx with 0x%lx\n",
1101 (unsigned)j, interposeArray[j].replacee, interposeArray[j].replacement);
1102 }
1103 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1104 if ( tuple.replacee == 0 )
1105 continue;
1106 // <rdar://problem/7937695> verify that replacement is in this image
1107 if ( this->containsAddress((void*)tuple.replacement) ) {
1108 // chain to any existing interpositions
1109 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
1110 if ( it->replacee == tuple.replacee ) {
1111 tuple.replacee = it->replacement;
1112 }
1113 }
1114 ImageLoader::fgInterposingTuples.push_back(tuple);
1115 }
1116 }
1117 }
1118 }
1119 }
1120 break;
1121 }
1122 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1123 }
1124 }
1125
1126 bool ImageLoaderMachOCompressed::usesChainedFixups() const
1127 {
1128 #if __arm64e__
1129 return ( machHeader()->cpusubtype == CPU_SUBTYPE_ARM64_E );
1130 #else
1131 return false;
1132 #endif
1133 }
1134
1135 struct ThreadedBindData {
1136 ThreadedBindData(const char* symbolName, int64_t addend, long libraryOrdinal, uint8_t symbolFlags, uint8_t type)
1137 : symbolName(symbolName), addend(addend), libraryOrdinal(libraryOrdinal), symbolFlags(symbolFlags), type(type) { }
1138
1139 std::tuple<const char*, int64_t, long, bool, uint8_t> pack() const {
1140 return std::make_tuple(symbolName, addend, libraryOrdinal, symbolFlags, type);
1141 }
1142
1143 const char* symbolName = nullptr;
1144 int64_t addend = 0;
1145 long libraryOrdinal = 0;
1146 uint8_t symbolFlags = 0;
1147 uint8_t type = 0;
1148 };
1149
1150 void ImageLoaderMachOCompressed::eachBind(const LinkContext& context, bind_handler handler)
1151 {
1152 try {
1153 const dysymtab_command* dynSymbolTable = NULL;
1154 const macho_nlist* symbolTable = NULL;
1155 const char* symbolTableStrings = NULL;
1156 uint32_t maxStringOffset = 0;
1157
1158 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1159 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1160 const struct load_command* cmd = cmds;
1161 for (uint32_t i = 0; i < cmd_count; ++i) {
1162 switch (cmd->cmd) {
1163 case LC_SYMTAB:
1164 {
1165 const struct symtab_command* symtab = (struct symtab_command*)cmd;
1166 symbolTableStrings = (const char*)&fLinkEditBase[symtab->stroff];
1167 maxStringOffset = symtab->strsize;
1168 symbolTable = (macho_nlist*)(&fLinkEditBase[symtab->symoff]);
1169 }
1170 break;
1171 case LC_DYSYMTAB:
1172 dynSymbolTable = (struct dysymtab_command*)cmd;
1173 break;
1174 }
1175 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1176 }
1177
1178 uint8_t type = 0;
1179 int segmentIndex = -1;
1180 uintptr_t address = segActualLoadAddress(0);
1181 uintptr_t segmentStartAddress = segActualLoadAddress(0);
1182 uintptr_t segmentEndAddress = segActualEndAddress(0);
1183 const char* symbolName = NULL;
1184 uint8_t symboFlags = 0;
1185 bool libraryOrdinalSet = false;
1186 long libraryOrdinal = 0;
1187 intptr_t addend = 0;
1188 uintptr_t count;
1189 uintptr_t skip;
1190 uintptr_t segOffset = 0;
1191
1192 dyld3::OverflowSafeArray<ThreadedBindData> ordinalTable;
1193 bool useThreadedRebaseBind = false;
1194 ExtraBindData extraBindData;
1195 LastLookup last = { 0, 0, NULL, 0, NULL };
1196 const uint8_t* const start = fLinkEditBase + fDyldInfo->bind_off;
1197 const uint8_t* const end = &start[fDyldInfo->bind_size];
1198 const uint8_t* p = start;
1199 bool done = false;
1200 while ( !done && (p < end) ) {
1201 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1202 uint8_t opcode = *p & BIND_OPCODE_MASK;
1203 ++p;
1204 switch (opcode) {
1205 case BIND_OPCODE_DONE:
1206 done = true;
1207 break;
1208 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
1209 libraryOrdinal = immediate;
1210 libraryOrdinalSet = true;
1211 break;
1212 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
1213 libraryOrdinal = read_uleb128(p, end);
1214 libraryOrdinalSet = true;
1215 break;
1216 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
1217 // the special ordinals are negative numbers
1218 if ( immediate == 0 )
1219 libraryOrdinal = 0;
1220 else {
1221 int8_t signExtended = BIND_OPCODE_MASK | immediate;
1222 libraryOrdinal = signExtended;
1223 }
1224 libraryOrdinalSet = true;
1225 break;
1226 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1227 symbolName = (char*)p;
1228 symboFlags = immediate;
1229 while (*p != '\0')
1230 ++p;
1231 ++p;
1232 break;
1233 case BIND_OPCODE_SET_TYPE_IMM:
1234 type = immediate;
1235 break;
1236 case BIND_OPCODE_SET_ADDEND_SLEB:
1237 addend = read_sleb128(p, end);
1238 break;
1239 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1240 segmentIndex = immediate;
1241 if ( (segmentIndex >= fSegmentsCount) || (segmentIndex < 0) )
1242 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1243 segmentIndex, fSegmentsCount-1);
1244 #if TEXT_RELOC_SUPPORT
1245 if ( !segWriteable(segmentIndex) && !segHasRebaseFixUps(segmentIndex) && !segHasBindFixUps(segmentIndex) )
1246 #else
1247 if ( !segWriteable(segmentIndex) )
1248 #endif
1249 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex);
1250 segOffset = read_uleb128(p, end);
1251 if ( segOffset > segSize(segmentIndex) )
1252 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segmentIndex));
1253 segmentStartAddress = segActualLoadAddress(segmentIndex);
1254 address = segmentStartAddress + segOffset;
1255 segmentEndAddress = segActualEndAddress(segmentIndex);
1256 break;
1257 case BIND_OPCODE_ADD_ADDR_ULEB:
1258 address += read_uleb128(p, end);
1259 break;
1260 case BIND_OPCODE_DO_BIND:
1261 if (!useThreadedRebaseBind) {
1262 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1263 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1264 if ( symbolName == NULL )
1265 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1266 if ( segmentIndex == -1 )
1267 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1268 if ( !libraryOrdinalSet )
1269 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1270 handler(context, this, address, type, symbolName, symboFlags, addend, libraryOrdinal,
1271 &extraBindData, "", &last, false);
1272 address += sizeof(intptr_t);
1273 } else {
1274 ordinalTable.push_back(ThreadedBindData(symbolName, addend, libraryOrdinal, symboFlags, type));
1275 }
1276 break;
1277 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1278 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1279 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1280 if ( symbolName == NULL )
1281 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1282 if ( segmentIndex == -1 )
1283 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1284 if ( !libraryOrdinalSet )
1285 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1286 handler(context, this, address, type, symbolName, symboFlags, addend, libraryOrdinal,
1287 &extraBindData, "", &last, false);
1288 address += read_uleb128(p, end) + sizeof(intptr_t);
1289 break;
1290 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1291 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1292 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1293 if ( symbolName == NULL )
1294 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1295 if ( segmentIndex == -1 )
1296 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1297 if ( !libraryOrdinalSet )
1298 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1299 handler(context, this, address, type, symbolName, symboFlags, addend, libraryOrdinal,
1300 &extraBindData, "", &last, false);
1301 address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1302 break;
1303 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1304 if ( symbolName == NULL )
1305 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1306 if ( segmentIndex == -1 )
1307 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1308 count = read_uleb128(p, end);
1309 if ( !libraryOrdinalSet )
1310 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1311 skip = read_uleb128(p, end);
1312 for (uint32_t i=0; i < count; ++i) {
1313 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1314 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1315 handler(context, this, address, type, symbolName, symboFlags, addend, libraryOrdinal,
1316 &extraBindData, "", &last, false);
1317 address += skip + sizeof(intptr_t);
1318 }
1319 break;
1320 case BIND_OPCODE_THREADED:
1321 if (sizeof(intptr_t) != 8) {
1322 dyld::throwf("BIND_OPCODE_THREADED require 64-bit");
1323 return;
1324 }
1325 // Note the immediate is a sub opcode
1326 switch (immediate) {
1327 case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB:
1328 count = read_uleb128(p, end);
1329 ordinalTable.clear();
1330 // FIXME: ld64 wrote the wrong value here and we need to offset by 1 for now.
1331 ordinalTable.reserve(count + 1);
1332 useThreadedRebaseBind = true;
1333 break;
1334 case BIND_SUBOPCODE_THREADED_APPLY: {
1335 uint64_t delta = 0;
1336 do {
1337 address = segmentStartAddress + segOffset;
1338 uint64_t value = *(uint64_t*)address;
1339
1340
1341 bool isRebase = (value & (1ULL << 62)) == 0;
1342 if (isRebase) {
1343 {
1344 // Call the bind handler which knows about our bind type being set to rebase
1345 handler(context, this, address, BIND_TYPE_THREADED_REBASE, nullptr, 0, 0, 0,
1346 nullptr, "", &last, false);
1347 }
1348 } else {
1349 // the ordinal is bits [0..15]
1350 uint16_t ordinal = value & 0xFFFF;
1351 if (ordinal >= ordinalTable.count()) {
1352 dyld::throwf("bind ordinal is out of range\n");
1353 return;
1354 }
1355 std::tie(symbolName, addend, libraryOrdinal, symboFlags, type) = ordinalTable[ordinal].pack();
1356 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1357 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1358 {
1359 handler(context, this, address, BIND_TYPE_THREADED_BIND,
1360 symbolName, symboFlags, addend, libraryOrdinal,
1361 nullptr, "", &last, false);
1362 }
1363 }
1364
1365 // The delta is bits [51..61]
1366 // And bit 62 is to tell us if we are a rebase (0) or bind (1)
1367 value &= ~(1ULL << 62);
1368 delta = ( value & 0x3FF8000000000000 ) >> 51;
1369 segOffset += delta * sizeof(intptr_t);
1370 } while ( delta != 0 );
1371 break;
1372 }
1373
1374 default:
1375 dyld::throwf("bad threaded bind subopcode 0x%02X", *p);
1376 }
1377 break;
1378 default:
1379 dyld::throwf("bad bind opcode %d in bind info", *p);
1380 }
1381 }
1382 }
1383 catch (const char* msg) {
1384 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
1385 free((void*)msg);
1386 throw newMsg;
1387 }
1388 }
1389
1390 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext& context, bind_handler handler)
1391 {
1392 try {
1393 uint8_t type = BIND_TYPE_POINTER;
1394 int segmentIndex = -1;
1395 uintptr_t address = segActualLoadAddress(0);
1396 uintptr_t segmentStartAddress = segActualLoadAddress(0);
1397 uintptr_t segmentEndAddress = segActualEndAddress(0);
1398 uintptr_t segOffset;
1399 const char* symbolName = NULL;
1400 uint8_t symboFlags = 0;
1401 long libraryOrdinal = 0;
1402 intptr_t addend = 0;
1403 const uint8_t* const start = fLinkEditBase + fDyldInfo->lazy_bind_off;
1404 const uint8_t* const end = &start[fDyldInfo->lazy_bind_size];
1405 const uint8_t* p = start;
1406 bool done = false;
1407 while ( !done && (p < end) ) {
1408 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1409 uint8_t opcode = *p & BIND_OPCODE_MASK;
1410 ++p;
1411 switch (opcode) {
1412 case BIND_OPCODE_DONE:
1413 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1414 break;
1415 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
1416 libraryOrdinal = immediate;
1417 break;
1418 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
1419 libraryOrdinal = read_uleb128(p, end);
1420 break;
1421 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
1422 // the special ordinals are negative numbers
1423 if ( immediate == 0 )
1424 libraryOrdinal = 0;
1425 else {
1426 int8_t signExtended = BIND_OPCODE_MASK | immediate;
1427 libraryOrdinal = signExtended;
1428 }
1429 break;
1430 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1431 symbolName = (char*)p;
1432 symboFlags = immediate;
1433 while (*p != '\0')
1434 ++p;
1435 ++p;
1436 break;
1437 case BIND_OPCODE_SET_TYPE_IMM:
1438 type = immediate;
1439 break;
1440 case BIND_OPCODE_SET_ADDEND_SLEB:
1441 addend = read_sleb128(p, end);
1442 break;
1443 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1444 segmentIndex = immediate;
1445 if ( (segmentIndex >= fSegmentsCount) || (segmentIndex < 0) )
1446 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1447 segmentIndex, fSegmentsCount-1);
1448 if ( !segWriteable(segmentIndex) )
1449 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex);
1450 segOffset = read_uleb128(p, end);
1451 if ( segOffset > segSize(segmentIndex) )
1452 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segmentIndex));
1453 segmentStartAddress = segActualLoadAddress(segmentIndex);
1454 segmentEndAddress = segActualEndAddress(segmentIndex);
1455 address = segmentStartAddress + segOffset;
1456 break;
1457 case BIND_OPCODE_ADD_ADDR_ULEB:
1458 address += read_uleb128(p, end);
1459 break;
1460 case BIND_OPCODE_DO_BIND:
1461 if ( segmentIndex == -1 )
1462 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1463 if ( (address < segmentStartAddress) || (address >= segmentEndAddress) )
1464 throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
1465 if ( symbolName == NULL )
1466 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1467 handler(context, this, address, type, symbolName, symboFlags, addend, libraryOrdinal,
1468 NULL, "forced lazy ", NULL, false);
1469 address += sizeof(intptr_t);
1470 break;
1471 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1472 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1473 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1474 default:
1475 dyld::throwf("bad lazy bind opcode %d", *p);
1476 }
1477 }
1478 }
1479
1480 catch (const char* msg) {
1481 const char* newMsg = dyld::mkstringf("%s in %s", msg, this->getPath());
1482 free((void*)msg);
1483 throw newMsg;
1484 }
1485 }
1486
1487 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1488 // the classic lazy loader is used even when running on 10.6
1489 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer, const LinkContext& context)
1490 {
1491 // only works with compressed LINKEDIT if classic symbol table is also present
1492 const macho_nlist* symbolTable = NULL;
1493 const char* symbolTableStrings = NULL;
1494 const dysymtab_command* dynSymbolTable = NULL;
1495 const uint32_t cmd_count = ((macho_header*)fMachOData)->ncmds;
1496 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1497 const struct load_command* cmd = cmds;
1498 for (uint32_t i = 0; i < cmd_count; ++i) {
1499 switch (cmd->cmd) {
1500 case LC_SYMTAB:
1501 {
1502 const struct symtab_command* symtab = (struct symtab_command*)cmd;
1503 symbolTableStrings = (const char*)&fLinkEditBase[symtab->stroff];
1504 symbolTable = (macho_nlist*)(&fLinkEditBase[symtab->symoff]);
1505 }
1506 break;
1507 case LC_DYSYMTAB:
1508 dynSymbolTable = (struct dysymtab_command*)cmd;
1509 break;
1510 }
1511 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1512 }
1513 // no symbol table => no lookup by address
1514 if ( (symbolTable == NULL) || (dynSymbolTable == NULL) )
1515 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer, this->getPath());
1516
1517 // scan for all lazy-pointer sections
1518 const bool twoLevel = this->usesTwoLevelNameSpace();
1519 const uint32_t* const indirectTable = (uint32_t*)&fLinkEditBase[dynSymbolTable->indirectsymoff];
1520 cmd = cmds;
1521 for (uint32_t i = 0; i < cmd_count; ++i) {
1522 switch (cmd->cmd) {
1523 case LC_SEGMENT_COMMAND:
1524 {
1525 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1526 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1527 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1528 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1529 const uint8_t type = sect->flags & SECTION_TYPE;
1530 uint32_t symbolIndex = INDIRECT_SYMBOL_LOCAL;
1531 if ( type == S_LAZY_SYMBOL_POINTERS ) {
1532 const size_t pointerCount = sect->size / sizeof(uintptr_t);
1533 uintptr_t* const symbolPointers = (uintptr_t*)(sect->addr + fSlide);
1534 if ( (lazyPointer >= symbolPointers) && (lazyPointer < &symbolPointers[pointerCount]) ) {
1535 const uint32_t indirectTableOffset = sect->reserved1;
1536 const size_t lazyIndex = lazyPointer - symbolPointers;
1537 symbolIndex = indirectTable[indirectTableOffset + lazyIndex];
1538 }
1539 }
1540 if ( (symbolIndex != INDIRECT_SYMBOL_ABS) && (symbolIndex != INDIRECT_SYMBOL_LOCAL) ) {
1541 const macho_nlist* symbol = &symbolTable[symbolIndex];
1542 const char* symbolName = &symbolTableStrings[symbol->n_un.n_strx];
1543 int libraryOrdinal = GET_LIBRARY_ORDINAL(symbol->n_desc);
1544 if ( !twoLevel || context.bindFlat )
1545 libraryOrdinal = BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
1546 uintptr_t ptrToBind = (uintptr_t)lazyPointer;
1547 uintptr_t symbolAddr = bindAt(context, this, ptrToBind, BIND_TYPE_POINTER, symbolName, 0, 0, libraryOrdinal,
1548 NULL, "lazy ", NULL);
1549 ++fgTotalLazyBindFixups;
1550 return symbolAddr;
1551 }
1552 }
1553 }
1554 break;
1555 }
1556 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1557 }
1558 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer, this->getPath());
1559 }
1560
1561
1562
1563 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset, const LinkContext& context,
1564 void (*lock)(), void (*unlock)())
1565 {
1566 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1567 if ( this->usesTwoLevelNameSpace() ) {
1568 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1569 }
1570 else {
1571 // acquire dyld global lock
1572 if ( lock != NULL )
1573 lock();
1574 }
1575
1576 const uint8_t* const start = fLinkEditBase + fDyldInfo->lazy_bind_off;
1577 const uint8_t* const end = &start[fDyldInfo->lazy_bind_size];
1578 uint8_t segIndex;
1579 uintptr_t segOffset;
1580 int libraryOrdinal;
1581 const char* symbolName;
1582 bool doneAfterBind;
1583 uintptr_t result;
1584 do {
1585 if ( ! getLazyBindingInfo(lazyBindingInfoOffset, start, end, &segIndex, &segOffset, &libraryOrdinal, &symbolName, &doneAfterBind) )
1586 dyld::throwf("bad lazy bind info");
1587
1588 if ( segIndex >= fSegmentsCount )
1589 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1590 segIndex, fSegmentsCount-1);
1591 if ( segOffset > segSize(segIndex) )
1592 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(segIndex));
1593 uintptr_t address = segActualLoadAddress(segIndex) + segOffset;
1594 result = bindAt(context, this, address, BIND_TYPE_POINTER, symbolName, 0, 0, libraryOrdinal,
1595 NULL, "lazy ", NULL, true);
1596 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1597 } while (!doneAfterBind && !context.strictMachORequired);
1598
1599 if ( !this->usesTwoLevelNameSpace() ) {
1600 // release dyld global lock
1601 if ( unlock != NULL )
1602 unlock();
1603 }
1604 return result;
1605 }
1606
1607 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator& it, unsigned int loadOrder, unsigned)
1608 {
1609 it.image = this;
1610 it.symbolName = " ";
1611 it.loadOrder = loadOrder;
1612 it.weakSymbol = false;
1613 it.symbolMatches = false;
1614 it.done = false;
1615 it.curIndex = 0;
1616 it.endIndex = this->fDyldInfo->weak_bind_size;
1617 it.address = 0;
1618 it.type = 0;
1619 it.addend = 0;
1620 }
1621
1622
1623 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator& it)
1624 {
1625 if ( it.done )
1626 return false;
1627
1628 if ( this->fDyldInfo->weak_bind_size == 0 ) {
1629 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1630 it.done = true;
1631 it.symbolName = "~~~";
1632 return true;
1633 }
1634 const uint8_t* start = fLinkEditBase + fDyldInfo->weak_bind_off;
1635 const uint8_t* p = start + it.curIndex;
1636 const uint8_t* end = fLinkEditBase + fDyldInfo->weak_bind_off + this->fDyldInfo->weak_bind_size;
1637 uintptr_t count;
1638 uintptr_t skip;
1639 uintptr_t segOffset;
1640 while ( p < end ) {
1641 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1642 uint8_t opcode = *p & BIND_OPCODE_MASK;
1643 ++p;
1644 switch (opcode) {
1645 case BIND_OPCODE_DONE:
1646 it.done = true;
1647 it.curIndex = p - start;
1648 it.symbolName = "~~~"; // sorts to end
1649 return true;
1650 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1651 it.symbolName = (char*)p;
1652 it.weakSymbol = ((immediate & BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) == 0);
1653 it.symbolMatches = false;
1654 while (*p != '\0')
1655 ++p;
1656 ++p;
1657 it.curIndex = p - start;
1658 return false;
1659 case BIND_OPCODE_SET_TYPE_IMM:
1660 it.type = immediate;
1661 break;
1662 case BIND_OPCODE_SET_ADDEND_SLEB:
1663 it.addend = read_sleb128(p, end);
1664 break;
1665 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1666 if ( immediate >= fSegmentsCount )
1667 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1668 immediate, fSegmentsCount-1);
1669 #if __arm__
1670 // <rdar://problem/23138428> iOS app compatibility
1671 if ( !segWriteable(immediate) && it.image->isPositionIndependentExecutable() )
1672 #elif TEXT_RELOC_SUPPORT
1673 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1674 if ( !segWriteable(immediate) && !segHasRebaseFixUps(immediate) && !segHasBindFixUps(immediate)
1675 && (!it.image->isExecutable() || it.image->isPositionIndependentExecutable()) )
1676 #else
1677 if ( !segWriteable(immediate) )
1678 #endif
1679 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate));
1680 segOffset = read_uleb128(p, end);
1681 if ( segOffset > segSize(immediate) )
1682 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(immediate));
1683 it.address = segActualLoadAddress(immediate) + segOffset;
1684 break;
1685 case BIND_OPCODE_ADD_ADDR_ULEB:
1686 it.address += read_uleb128(p, end);
1687 break;
1688 case BIND_OPCODE_DO_BIND:
1689 it.address += sizeof(intptr_t);
1690 break;
1691 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1692 it.address += read_uleb128(p, end) + sizeof(intptr_t);
1693 break;
1694 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1695 it.address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1696 break;
1697 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1698 count = read_uleb128(p, end);
1699 skip = read_uleb128(p, end);
1700 for (uint32_t i=0; i < count; ++i) {
1701 it.address += skip + sizeof(intptr_t);
1702 }
1703 break;
1704 default:
1705 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p, (int)(p-start), this->getPath());
1706 }
1707 }
1708 /// hmmm, BIND_OPCODE_DONE is missing...
1709 it.done = true;
1710 it.symbolName = "~~~";
1711 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1712 return true;
1713 }
1714
1715 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator& it, const LinkContext& context)
1716 {
1717 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1718 const ImageLoader* foundIn = NULL;
1719 const ImageLoader::Symbol* sym = this->findShallowExportedSymbol(it.symbolName, &foundIn);
1720 if ( sym != NULL ) {
1721 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1722 return foundIn->getExportedSymbolAddress(sym, context, this);
1723 }
1724 return 0;
1725 }
1726
1727
1728 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator& it, uintptr_t value, ImageLoader* targetImage, unsigned targetIndex, const LinkContext& context)
1729 {
1730 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1731 if ( this->getState() < dyld_image_state_bound )
1732 return;
1733
1734 const uint8_t* start = fLinkEditBase + fDyldInfo->weak_bind_off;
1735 const uint8_t* p = start + it.curIndex;
1736 const uint8_t* end = fLinkEditBase + fDyldInfo->weak_bind_off + this->fDyldInfo->weak_bind_size;
1737
1738 uint8_t type = it.type;
1739 uintptr_t address = it.address;
1740 const char* symbolName = it.symbolName;
1741 intptr_t addend = it.addend;
1742 uintptr_t count;
1743 uintptr_t skip;
1744 uintptr_t segOffset;
1745 bool done = false;
1746 bool boundSomething = false;
1747 while ( !done && (p < end) ) {
1748 uint8_t immediate = *p & BIND_IMMEDIATE_MASK;
1749 uint8_t opcode = *p & BIND_OPCODE_MASK;
1750 ++p;
1751 switch (opcode) {
1752 case BIND_OPCODE_DONE:
1753 done = true;
1754 break;
1755 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1756 done = true;
1757 break;
1758 case BIND_OPCODE_SET_TYPE_IMM:
1759 type = immediate;
1760 break;
1761 case BIND_OPCODE_SET_ADDEND_SLEB:
1762 addend = read_sleb128(p, end);
1763 break;
1764 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1765 if ( immediate >= fSegmentsCount )
1766 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1767 immediate, fSegmentsCount-1);
1768 #if __arm__
1769 // <rdar://problem/23138428> iOS app compatibility
1770 if ( !segWriteable(immediate) && it.image->isPositionIndependentExecutable() )
1771 #elif TEXT_RELOC_SUPPORT
1772 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1773 if ( !segWriteable(immediate) && !segHasRebaseFixUps(immediate) && !segHasBindFixUps(immediate)
1774 && (!it.image->isExecutable() || it.image->isPositionIndependentExecutable()) )
1775 #else
1776 if ( !segWriteable(immediate) )
1777 #endif
1778 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate));
1779 segOffset = read_uleb128(p, end);
1780 if ( segOffset > segSize(immediate) )
1781 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset, segSize(immediate));
1782 address = segActualLoadAddress(immediate) + segOffset;
1783 break;
1784 case BIND_OPCODE_ADD_ADDR_ULEB:
1785 address += read_uleb128(p, end);
1786 break;
1787 case BIND_OPCODE_DO_BIND:
1788 bindLocation(context, this->imageBaseAddress(), address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ", NULL, fSlide);
1789 boundSomething = true;
1790 address += sizeof(intptr_t);
1791 break;
1792 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1793 bindLocation(context, this->imageBaseAddress(), address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ", NULL, fSlide);
1794 boundSomething = true;
1795 address += read_uleb128(p, end) + sizeof(intptr_t);
1796 break;
1797 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1798 bindLocation(context, this->imageBaseAddress(), address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ", NULL, fSlide);
1799 boundSomething = true;
1800 address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
1801 break;
1802 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1803 count = read_uleb128(p, end);
1804 skip = read_uleb128(p, end);
1805 for (uint32_t i=0; i < count; ++i) {
1806 bindLocation(context, this->imageBaseAddress(), address, value, type, symbolName, addend, this->getPath(), targetImage ? targetImage->getPath() : NULL, "weak ", NULL, fSlide);
1807 boundSomething = true;
1808 address += skip + sizeof(intptr_t);
1809 }
1810 break;
1811 default:
1812 dyld::throwf("bad bind opcode %d in weak binding info", *p);
1813 }
1814 }
1815 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1816 if ( boundSomething && (targetImage != this) )
1817 context.addDynamicReference(this, targetImage);
1818 }
1819
1820 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext& context, ImageLoaderMachOCompressed* image,
1821 uintptr_t addr, uint8_t type, const char*,
1822 uint8_t, intptr_t, long,
1823 ExtraBindData *extraBindData,
1824 const char*, LastLookup*, bool runResolver)
1825 {
1826 if ( type == BIND_TYPE_POINTER ) {
1827 uintptr_t* fixupLocation = (uintptr_t*)addr;
1828 uintptr_t curValue = *fixupLocation;
1829 uintptr_t newValue = interposedAddress(context, curValue, image);
1830 if ( newValue != curValue) {
1831 *fixupLocation = newValue;
1832 }
1833 }
1834 return 0;
1835 }
1836
1837 void ImageLoaderMachOCompressed::doInterpose(const LinkContext& context)
1838 {
1839 if ( context.verboseInterposing )
1840 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples.size(), this->getPath());
1841
1842 // update prebound symbols
1843 eachBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
1844 uintptr_t addr, uint8_t type, const char* symbolName,
1845 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1846 ExtraBindData *extraBindData,
1847 const char* msg, LastLookup* last, bool runResolver) {
1848 return ImageLoaderMachOCompressed::interposeAt(ctx, image, addr, type, symbolName, symbolFlags,
1849 addend, libraryOrdinal, extraBindData,
1850 msg, last, runResolver);
1851 });
1852 eachLazyBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
1853 uintptr_t addr, uint8_t type, const char* symbolName,
1854 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1855 ExtraBindData *extraBindData,
1856 const char* msg, LastLookup* last, bool runResolver) {
1857 return ImageLoaderMachOCompressed::interposeAt(ctx, image, addr, type, symbolName, symbolFlags,
1858 addend, libraryOrdinal, extraBindData,
1859 msg, last, runResolver);
1860 });
1861 }
1862
1863
1864 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext& context, ImageLoaderMachOCompressed* image,
1865 uintptr_t addr, uint8_t type, const char* symbolName,
1866 uint8_t, intptr_t, long,
1867 ExtraBindData *extraBindData,
1868 const char*, LastLookup*, bool runResolver)
1869 {
1870 if ( type == BIND_TYPE_POINTER ) {
1871 uintptr_t* fixupLocation = (uintptr_t*)addr;
1872 uintptr_t value = *fixupLocation;
1873 // don't apply interposing to table entries.
1874 if ( (context.dynamicInterposeArray <= (void*)addr) && ((void*)addr < &context.dynamicInterposeArray[context.dynamicInterposeCount]) )
1875 return 0;
1876 for(size_t i=0; i < context.dynamicInterposeCount; ++i) {
1877 if ( value == (uintptr_t)context.dynamicInterposeArray[i].replacee ) {
1878 if ( context.verboseInterposing ) {
1879 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1880 fixupLocation, context.dynamicInterposeArray[i].replacee, context.dynamicInterposeArray[i].replacement, image->getPath());
1881 }
1882 *fixupLocation = (uintptr_t)context.dynamicInterposeArray[i].replacement;
1883 }
1884 }
1885 }
1886 return 0;
1887 }
1888
1889 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext& context)
1890 {
1891 if ( context.verboseInterposing )
1892 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context.dynamicInterposeCount, this->getPath());
1893
1894 // update already bound references to symbols
1895 eachBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
1896 uintptr_t addr, uint8_t type, const char* symbolName,
1897 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1898 ExtraBindData *extraBindData,
1899 const char* msg, LastLookup* last, bool runResolver) {
1900 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx, image, addr, type, symbolName, symbolFlags,
1901 addend, libraryOrdinal, extraBindData,
1902 msg, last, runResolver);
1903 });
1904 eachLazyBind(context, ^(const LinkContext& ctx, ImageLoaderMachOCompressed* image,
1905 uintptr_t addr, uint8_t type, const char* symbolName,
1906 uint8_t symbolFlags, intptr_t addend, long libraryOrdinal,
1907 ExtraBindData *extraBindData,
1908 const char* msg, LastLookup* last, bool runResolver) {
1909 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx, image, addr, type, symbolName, symbolFlags,
1910 addend, libraryOrdinal, extraBindData,
1911 msg, last, runResolver);
1912 });
1913 }
1914
1915 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr, const void** closestAddr) const
1916 {
1917 return ImageLoaderMachO::findClosestSymbol((mach_header*)fMachOData, addr, closestAddr);
1918 }
1919
1920
1921 #if PREBOUND_IMAGE_SUPPORT
1922 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext& context)
1923 {
1924 // no way to back off a prebound compress image
1925 }
1926 #endif
1927
1928
1929 #if __arm__ || __x86_64__
1930 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub, void** originalLazyPointerAddr, const LinkContext& context)
1931 {
1932 #if __arm__
1933 uint32_t* instructions = (uint32_t*)stub;
1934 // sanity check this is a stub we understand
1935 if ( (instructions[0] != 0xe59fc004) || (instructions[1] != 0xe08fc00c) || (instructions[2] != 0xe59cf000) )
1936 return;
1937
1938 void** lazyPointerAddr = (void**)(instructions[3] + (stub + 12));
1939 #endif
1940 #if __x86_64__
1941 // sanity check this is a stub we understand
1942 if ( (stub[0] != 0xFF) || (stub[1] != 0x25) )
1943 return;
1944 int32_t ripOffset = *((int32_t*)(&stub[2]));
1945 void** lazyPointerAddr = (void**)(ripOffset + stub + 6);
1946 #endif
1947
1948 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1949 if ( lazyPointerAddr != originalLazyPointerAddr ) {
1950 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1951 const ImageLoader* lazyPointerImage = context.findImageContainingAddress(lazyPointerAddr);
1952 if ( lazyPointerImage != NULL )
1953 return;
1954
1955 // copy newly re-bound lazy pointer value to shared lazy pointer
1956 *lazyPointerAddr = *originalLazyPointerAddr;
1957
1958 if ( context.verboseBind )
1959 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1960 this->getShortName(), (long)lazyPointerAddr, (long)*originalLazyPointerAddr);
1961 }
1962 }
1963 #endif
1964
1965
1966 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1967 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext& context)
1968 {
1969 #if __arm__ || __x86_64__
1970 // find stubs and indirect symbol table
1971 const struct macho_section* stubsSection = NULL;
1972 const dysymtab_command* dynSymbolTable = NULL;
1973 const macho_header* mh = (macho_header*)fMachOData;
1974 const uint32_t cmd_count = mh->ncmds;
1975 const struct load_command* const cmds = (struct load_command*)&fMachOData[sizeof(macho_header)];
1976 const struct load_command* cmd = cmds;
1977 for (uint32_t i = 0; i < cmd_count; ++i) {
1978 if (cmd->cmd == LC_SEGMENT_COMMAND) {
1979 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
1980 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
1981 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
1982 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
1983 const uint8_t type = sect->flags & SECTION_TYPE;
1984 if ( type == S_SYMBOL_STUBS )
1985 stubsSection = sect;
1986 }
1987 }
1988 else if ( cmd->cmd == LC_DYSYMTAB ) {
1989 dynSymbolTable = (struct dysymtab_command*)cmd;
1990 }
1991 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
1992 }
1993 if ( dynSymbolTable == NULL )
1994 return;
1995 const uint32_t* const indirectTable = (uint32_t*)&fLinkEditBase[dynSymbolTable->indirectsymoff];
1996 if ( stubsSection == NULL )
1997 return;
1998 const uint32_t stubsSize = stubsSection->reserved2;
1999 const uint32_t stubsCount = (uint32_t)(stubsSection->size / stubsSize);
2000 const uint32_t stubsIndirectTableOffset = stubsSection->reserved1;
2001 if ( (stubsIndirectTableOffset+stubsCount) > dynSymbolTable->nindirectsyms )
2002 return;
2003 uint8_t* const stubsAddr = (uint8_t*)(stubsSection->addr + this->fSlide);
2004
2005 // for each lazy pointer section
2006 cmd = cmds;
2007 for (uint32_t i = 0; i < cmd_count; ++i) {
2008 if (cmd->cmd == LC_SEGMENT_COMMAND) {
2009 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2010 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2011 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2012 for (const struct macho_section* lazyPointerSection=sectionsStart; lazyPointerSection < sectionsEnd; ++lazyPointerSection) {
2013 const uint8_t type = lazyPointerSection->flags & SECTION_TYPE;
2014 if ( type != S_LAZY_SYMBOL_POINTERS )
2015 continue;
2016 const uint32_t lazyPointersCount = (uint32_t)(lazyPointerSection->size / sizeof(void*));
2017 const uint32_t lazyPointersIndirectTableOffset = lazyPointerSection->reserved1;
2018 if ( (lazyPointersIndirectTableOffset+lazyPointersCount) > dynSymbolTable->nindirectsyms )
2019 continue;
2020 void** const lazyPointersAddr = (void**)(lazyPointerSection->addr + this->fSlide);
2021 // for each lazy pointer
2022 for(uint32_t lpIndex=0; lpIndex < lazyPointersCount; ++lpIndex) {
2023 const uint32_t lpSymbolIndex = indirectTable[lazyPointersIndirectTableOffset+lpIndex];
2024 // find matching stub and validate it uses this lazy pointer
2025 for(uint32_t stubIndex=0; stubIndex < stubsCount; ++stubIndex) {
2026 if ( indirectTable[stubsIndirectTableOffset+stubIndex] == lpSymbolIndex ) {
2027 this->updateAlternateLazyPointer(stubsAddr+stubIndex*stubsSize, &lazyPointersAddr[lpIndex], context);
2028 break;
2029 }
2030 }
2031 }
2032
2033 }
2034 }
2035 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2036 }
2037
2038 #endif
2039 }
2040
2041
2042 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command* encryptCmd, const LinkContext& context)
2043 {
2044 #if __arm__ || __arm64__
2045 if ( encryptCmd == NULL )
2046 return;
2047 const mach_header* mh = NULL;
2048 for(unsigned int i=0; i < fSegmentsCount; ++i) {
2049 if ( (segFileOffset(i) == 0) && (segFileSize(i) != 0) ) {
2050 mh = (mach_header*)segActualLoadAddress(i);
2051 break;
2052 }
2053 }
2054 void* start = ((uint8_t*)mh) + encryptCmd->cryptoff;
2055 size_t len = encryptCmd->cryptsize;
2056 uint32_t cputype = mh->cputype;
2057 uint32_t cpusubtype = mh->cpusubtype;
2058 uint32_t cryptid = encryptCmd->cryptid;
2059 if (context.verboseMapping) {
2060 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start, (long)start+len);
2061 }
2062 int result = mremap_encrypted(start, len, cryptid, cputype, cpusubtype);
2063 if ( result != 0 ) {
2064 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result, errno, this->getPath());
2065 }
2066 #endif
2067 }
2068
2069
2070