1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2008 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
26 #if __arm__ || __arm64__
27 #include <System/sys/mman.h>
34 #include <sys/types.h>
35 #include <sys/fcntl.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 <mach-o/dyld_images.h>
44 #include "ImageLoaderMachOCompressed.h"
48 #ifndef BIND_SUBOPCODE_THREADED_SET_JOP
49 #define BIND_SUBOPCODE_THREADED_SET_JOP 0x0F
52 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
55 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
56 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
57 struct macho_segment_command
: public segment_command_64
{};
58 struct macho_section
: public section_64
{};
59 struct macho_routines_command
: public routines_command_64
{};
62 #define LC_SEGMENT_COMMAND LC_SEGMENT
63 #define LC_ROUTINES_COMMAND LC_ROUTINES
64 struct macho_segment_command
: public segment_command
{};
65 struct macho_section
: public section
{};
66 struct macho_routines_command
: public routines_command
{};
71 // create image for main executable
72 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
,
73 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
75 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
77 // set slide for PIE programs
78 image
->setSlide(slide
);
80 // for PIE record end of program, to know where to start loading dylibs
82 fgNextPIEDylibAddress
= (uintptr_t)image
->getEnd();
84 image
->disableCoverageCheck();
85 image
->instantiateFinish(context
);
86 image
->setMapped(context
);
88 if ( context
.verboseMapping
) {
89 dyld::log("dyld: Main executable mapped %s\n", path
);
90 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
91 const char* name
= image
->segName(i
);
92 if ( (strcmp(name
, "__PAGEZERO") == 0) || (strcmp(name
, "__UNIXSTACK") == 0) )
93 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segPreferredLoadAddress(i
), image
->segPreferredLoadAddress(i
)+image
->segSize(i
));
95 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
102 // create image by mapping in a mach-o file
103 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromFile(const char* path
, int fd
, const uint8_t* fileData
, size_t lenFileData
,
104 uint64_t offsetInFat
, uint64_t lenInFat
, const struct stat
& info
,
105 unsigned int segCount
, unsigned int libCount
,
106 const struct linkedit_data_command
* codeSigCmd
,
107 const struct encryption_info_command
* encryptCmd
,
108 const LinkContext
& context
)
110 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart((macho_header
*)fileData
, path
, segCount
, libCount
);
113 // record info about file
114 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
116 // if this image is code signed, let kernel validate signature before mapping any pages from image
117 image
->loadCodeSignature(codeSigCmd
, fd
, offsetInFat
, context
);
119 // Validate that first data we read with pread actually matches with code signature
120 image
->validateFirstPages(codeSigCmd
, fd
, fileData
, lenFileData
, offsetInFat
, context
);
123 image
->mapSegments(fd
, offsetInFat
, lenInFat
, info
.st_size
, context
);
125 // if framework is FairPlay encrypted, register with kernel
126 image
->registerEncryption(encryptCmd
, context
);
128 // probe to see if code signed correctly
129 image
->crashIfInvalidCodeSignature();
131 // finish construction
132 image
->instantiateFinish(context
);
134 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
135 const char* installName
= image
->getInstallPath();
136 if ( (installName
!= NULL
) && (strcmp(installName
, path
) == 0) && (path
[0] == '/') )
137 image
->setPathUnowned(installName
);
138 #if __MAC_OS_X_VERSION_MIN_REQUIRED
139 // <rdar://problem/6563887> app crashes when libSystem cannot be found
140 else if ( (installName
!= NULL
) && (strcmp(path
, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName
, "/usr/lib/libSystem.B.dylib") == 0) )
141 image
->setPathUnowned("/usr/lib/libSystem.B.dylib");
143 else if ( (path
[0] != '/') || (strstr(path
, "../") != NULL
) ) {
144 // rdar://problem/10733082 Fix up @rpath based paths during introspection
145 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
146 char realPath
[MAXPATHLEN
];
147 if ( fcntl(fd
, F_GETPATH
, realPath
) == 0 )
148 image
->setPaths(path
, realPath
);
150 image
->setPath(path
);
153 // <rdar://problem/46682306> always try to realpath dylibs since they may have been dlopen()ed using a symlink path
154 if ( installName
!= NULL
) {
155 char realPath
[MAXPATHLEN
];
156 if ( (fcntl(fd
, F_GETPATH
, realPath
) == 0) && (strcmp(path
, realPath
) != 0) )
157 image
->setPaths(path
, realPath
);
159 image
->setPath(path
);
162 image
->setPath(path
);
166 // make sure path is stable before recording in dyld_all_image_infos
167 image
->setMapped(context
);
171 // ImageLoader::setMapped() can throw an exception to block loading of image
172 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
180 // create image by using cached mach-o file
181 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
,
182 const struct stat
& info
, unsigned int segCount
,
183 unsigned int libCount
, const LinkContext
& context
)
185 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
187 // record info about file
188 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
190 // remember this is from shared cache and cannot be unloaded
191 image
->fInSharedCache
= true;
192 image
->setNeverUnload();
193 image
->setSlide(slide
);
194 image
->disableCoverageCheck();
196 // segments already mapped in cache
197 if ( context
.verboseMapping
) {
198 dyld::log("dyld: Using shared cached for %s\n", path
);
199 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
200 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
204 image
->instantiateFinish(context
);
206 #if TARGET_OS_SIMULATOR
207 char realPath
[MAXPATHLEN
] = { 0 };
208 if ( dyld::gLinkContext
.rootPaths
== NULL
)
209 throw "root path is not set";
210 strlcpy(realPath
, dyld::gLinkContext
.rootPaths
[0], MAXPATHLEN
);
211 strlcat(realPath
, path
, MAXPATHLEN
);
212 image
->setPaths(path
, realPath
);
214 image
->setMapped(context
);
217 // ImageLoader::setMapped() can throw an exception to block loading of image
218 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
226 // create image by copying an in-memory mach-o file
227 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
228 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
230 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, moduleName
, segCount
, libCount
);
233 if ( mh
->filetype
== MH_EXECUTE
)
234 throw "can't load another MH_EXECUTE";
237 image
->mapSegments((const void*)mh
, len
, context
);
239 // for compatibility, never unload dylibs loaded from memory
240 image
->setNeverUnload();
242 image
->disableCoverageCheck();
244 // bundle loads need path copied
245 if ( moduleName
!= NULL
)
246 image
->setPath(moduleName
);
248 image
->instantiateFinish(context
);
249 image
->setMapped(context
);
252 // ImageLoader::setMapped() can throw an exception to block loading of image
253 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
262 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header
* mh
, const char* path
, unsigned int segCount
,
263 uint32_t segOffsets
[], unsigned int libCount
)
264 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fDyldInfo(NULL
), fChainedFixups(NULL
), fExportsTrie(NULL
)
268 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
270 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
276 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
277 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateStart(const macho_header
* mh
, const char* path
,
278 unsigned int segCount
, unsigned int libCount
)
280 size_t size
= sizeof(ImageLoaderMachOCompressed
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
281 ImageLoaderMachOCompressed
* allocatedSpace
= static_cast<ImageLoaderMachOCompressed
*>(malloc(size
));
282 if ( allocatedSpace
== NULL
)
283 throw "malloc failed";
284 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOCompressed
)));
285 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
286 return new (allocatedSpace
) ImageLoaderMachOCompressed(mh
, path
, segCount
, segOffsets
, libCount
);
290 // common code to finish initializing object
291 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext
& context
)
293 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
294 this->parseLoadCmds(context
);
297 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
299 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
)));
303 ImageLoader
* ImageLoaderMachOCompressed::libImage(unsigned int libIndex
) const
305 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
307 return (ImageLoader
*)(images
[libIndex
] & (-4));
310 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex
) const
312 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
313 // re-export flag is low bit
314 return ((images
[libIndex
] & 1) != 0);
317 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex
) const
319 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
320 // re-export flag is second bit
321 return ((images
[libIndex
] & 2) != 0);
325 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
, bool upward
)
327 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
328 uintptr_t value
= (uintptr_t)image
;
333 images
[libIndex
] = value
;
337 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext
& context
, uintptr_t addr
, uintptr_t slide
, uint8_t type
)
339 if ( context
.verboseRebase
) {
340 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr
, slide
);
342 //dyld::log("0x%08lX type=%d\n", addr, type);
343 uintptr_t* locationToFix
= (uintptr_t*)addr
;
345 case REBASE_TYPE_POINTER
:
346 *locationToFix
+= slide
;
348 case REBASE_TYPE_TEXT_ABSOLUTE32
:
349 *locationToFix
+= slide
;
352 dyld::throwf("bad rebase type %d", type
);
356 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
357 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
359 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
360 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
361 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
364 void ImageLoaderMachOCompressed::rebase(const LinkContext
& context
, uintptr_t slide
)
366 // binary uses chained fixups where are applied during binding
367 if ( fDyldInfo
== NULL
)
370 CRSetCrashLogMessage2(this->getPath());
371 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->rebase_off
;
372 const uint8_t* const end
= &start
[fDyldInfo
->rebase_size
];
373 const uint8_t* p
= start
;
379 bool bindingBecauseOfRoot
= this->overridesCachedDylib(ignore
);
380 vmAccountingSetSuspended(context
, bindingBecauseOfRoot
);
384 int segmentIndex
= 0;
385 uintptr_t address
= segActualLoadAddress(0);
386 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
387 uintptr_t segmentEndAddress
= segActualEndAddress(0);
391 while ( !done
&& (p
< end
) ) {
392 uint8_t immediate
= *p
& REBASE_IMMEDIATE_MASK
;
393 uint8_t opcode
= *p
& REBASE_OPCODE_MASK
;
396 case REBASE_OPCODE_DONE
:
399 case REBASE_OPCODE_SET_TYPE_IMM
:
402 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
403 segmentIndex
= immediate
;
404 if ( segmentIndex
>= fSegmentsCount
)
405 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
406 segmentIndex
, fSegmentsCount
-1);
407 #if TEXT_RELOC_SUPPORT
408 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
410 if ( !segWriteable(segmentIndex
) )
412 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
413 segmentIndex
, segName(segmentIndex
));
414 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
415 segmentEndAddress
= segActualEndAddress(segmentIndex
);
416 address
= segmentStartAddress
+ read_uleb128(p
, end
);
418 case REBASE_OPCODE_ADD_ADDR_ULEB
:
419 address
+= read_uleb128(p
, end
);
421 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED
:
422 address
+= immediate
*sizeof(uintptr_t);
424 case REBASE_OPCODE_DO_REBASE_IMM_TIMES
:
425 for (int i
=0; i
< immediate
; ++i
) {
426 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
427 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
428 rebaseAt(context
, address
, slide
, type
);
429 address
+= sizeof(uintptr_t);
431 fgTotalRebaseFixups
+= immediate
;
433 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES
:
434 count
= read_uleb128(p
, end
);
435 for (uint32_t i
=0; i
< count
; ++i
) {
436 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
437 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
438 rebaseAt(context
, address
, slide
, type
);
439 address
+= sizeof(uintptr_t);
441 fgTotalRebaseFixups
+= count
;
443 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB
:
444 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
445 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
446 rebaseAt(context
, address
, slide
, type
);
447 address
+= read_uleb128(p
, end
) + sizeof(uintptr_t);
448 ++fgTotalRebaseFixups
;
450 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
:
451 count
= read_uleb128(p
, end
);
452 skip
= read_uleb128(p
, end
);
453 for (uint32_t i
=0; i
< count
; ++i
) {
454 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
455 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
456 rebaseAt(context
, address
, slide
, type
);
457 address
+= skip
+ sizeof(uintptr_t);
459 fgTotalRebaseFixups
+= count
;
462 dyld::throwf("bad rebase opcode %d", *(p
-1));
466 catch (const char* msg
) {
467 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
471 CRSetCrashLogMessage2(NULL
);
474 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol
, const ImageLoader
** foundIn
) const
476 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
477 uint32_t trieFileOffset
= fDyldInfo
? fDyldInfo
->export_off
: fExportsTrie
->dataoff
;
478 uint32_t trieFileSize
= fDyldInfo
? fDyldInfo
->export_size
: fExportsTrie
->datasize
;
479 if ( trieFileSize
== 0 )
482 dyld::logBindings("%s: %s\n", this->getShortName(), symbol
);
484 ++ImageLoaderMachO::fgSymbolTrieSearchs
;
485 const uint8_t* start
= &fLinkEditBase
[trieFileOffset
];
486 const uint8_t* end
= &start
[trieFileSize
];
487 const uint8_t* foundNodeStart
= this->trieWalk(start
, end
, symbol
);
488 if ( foundNodeStart
!= NULL
) {
489 const uint8_t* p
= foundNodeStart
;
490 const uintptr_t flags
= read_uleb128(p
, end
);
491 // found match, return pointer to terminal part of node
492 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
493 // re-export from another dylib, lookup there
494 const uintptr_t ordinal
= read_uleb128(p
, end
);
495 const char* importedName
= (char*)p
;
496 if ( importedName
[0] == '\0' )
497 importedName
= symbol
;
498 if ( (ordinal
> 0) && (ordinal
<= libraryCount()) ) {
499 const ImageLoader
* reexportedFrom
= libImage((unsigned int)ordinal
-1);
500 // Missing weak-dylib
501 if ( reexportedFrom
== NULL
)
503 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
504 const char* reExportLibPath
= libPath((unsigned int)ordinal
-1);
505 return reexportedFrom
->findExportedSymbol(importedName
, true, reExportLibPath
, foundIn
);
508 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
509 // ordinal, libraryCount(), symbol, this->getPath());
513 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
514 if ( foundIn
!= NULL
)
515 *foundIn
= (ImageLoader
*)this;
516 // return pointer to terminal part of node
517 return (Symbol
*)foundNodeStart
;
524 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr
) const
526 uint32_t trieFileOffset
= fDyldInfo
? fDyldInfo
->export_off
: fExportsTrie
->dataoff
;
527 uint32_t trieFileSize
= fDyldInfo
? fDyldInfo
->export_size
: fExportsTrie
->datasize
;
528 const uint8_t* start
= &fLinkEditBase
[trieFileOffset
];
529 const uint8_t* end
= &start
[trieFileSize
];
530 return ( (start
<= addr
) && (addr
< end
) );
534 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext
& context
, const Symbol
* symbol
, const ImageLoader
* requestor
, bool runResolver
) const
536 uint32_t trieFileOffset
= fDyldInfo
? fDyldInfo
->export_off
: fExportsTrie
->dataoff
;
537 uint32_t trieFileSize
= fDyldInfo
? fDyldInfo
->export_size
: fExportsTrie
->datasize
;
538 const uint8_t* exportNode
= (uint8_t*)symbol
;
539 const uint8_t* exportTrieStart
= fLinkEditBase
+ trieFileOffset
;
540 const uint8_t* exportTrieEnd
= exportTrieStart
+ trieFileSize
;
541 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
542 throw "symbol is not in trie";
543 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
544 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
545 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
546 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
547 if ( runResolver
&& (flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) ) {
548 // this node has a stub and resolver, run the resolver to get target address
549 uintptr_t stub
= read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
; // skip over stub
550 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
551 uintptr_t interposedStub
= interposedAddress(context
, stub
, requestor
);
552 if ( interposedStub
!= stub
)
553 return interposedStub
;
554 // stub was not interposed, so run resolver
555 typedef uintptr_t (*ResolverProc
)(void);
556 ResolverProc resolver
= (ResolverProc
)(read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
);
557 #if __has_feature(ptrauth_calls)
558 resolver
= (ResolverProc
)__builtin_ptrauth_sign_unauthenticated(resolver
, ptrauth_key_asia
, 0);
560 uintptr_t result
= (*resolver
)();
561 if ( context
.verboseBind
)
562 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver
, result
);
563 #if __has_feature(ptrauth_calls)
564 result
= (uintptr_t)__builtin_ptrauth_strip((void*)result
, ptrauth_key_asia
);
568 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
569 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
570 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
571 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
572 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
573 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
574 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
575 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
576 return read_uleb128(exportNode
, exportTrieEnd
);
578 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
582 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
584 uint32_t trieFileOffset
= fDyldInfo
? fDyldInfo
->export_off
: fExportsTrie
->dataoff
;
585 uint32_t trieFileSize
= fDyldInfo
? fDyldInfo
->export_size
: fExportsTrie
->datasize
;
586 const uint8_t* exportNode
= (uint8_t*)symbol
;
587 const uint8_t* exportTrieStart
= fLinkEditBase
+ trieFileOffset
;
588 const uint8_t* exportTrieEnd
= exportTrieStart
+ trieFileSize
;
589 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
590 throw "symbol is not in trie";
591 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
592 return ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
);
596 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol
* symbol
) const
598 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
601 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
603 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
606 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index
) const
608 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
611 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
613 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
616 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index
) const
618 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
621 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol
* symbol
) const
623 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
628 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
629 bool runResolver
, const ImageLoader
** foundIn
)
632 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
633 if ( *foundIn
!= this )
634 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
635 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
637 // if a bundle is loaded privately the above will not find its exports
638 if ( this->isBundle() && this->hasHiddenExports() ) {
639 // look in self for needed symbol
640 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
642 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
645 // definition can't be found anywhere, ok because it is weak, just return 0
648 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "flat namespace");
652 static void patchCacheUsesOf(const ImageLoader::LinkContext
& context
, const dyld3::closure::Image
* overriddenImage
,
653 uint32_t cacheOffsetOfImpl
, const char* symbolName
, uintptr_t newImpl
)
655 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
656 uint32_t imageIndex
= overriddenImage
->imageNum() - (uint32_t)context
.dyldCache
->cachedDylibsImageArray()->startImageNum();
657 context
.dyldCache
->forEachPatchableUseOfExport(imageIndex
, cacheOffsetOfImpl
, ^(dyld_cache_patchable_location patchLocation
) {
658 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
659 #if __has_feature(ptrauth_calls)
660 if ( patchLocation
.authenticated
) {
661 dyld3::MachOLoaded::ChainedFixupPointerOnDisk fixupInfo
;
662 fixupInfo
.arm64e
.authRebase
.auth
= true;
663 fixupInfo
.arm64e
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
664 fixupInfo
.arm64e
.authRebase
.diversity
= patchLocation
.discriminator
;
665 fixupInfo
.arm64e
.authRebase
.key
= patchLocation
.key
;
666 uintptr_t newValue
= fixupInfo
.arm64e
.signPointer(loc
, newImpl
+ DyldSharedCache::getAddend(patchLocation
));
667 if ( *loc
!= newValue
) {
669 if ( context
.verboseBind
)
670 dyld::log("dyld: cache fixup: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s) to %s\n",
671 loc
, (void*)newValue
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, DyldSharedCache::keyName(patchLocation
), symbolName
);
676 uintptr_t newValue
= newImpl
+ (uintptr_t)DyldSharedCache::getAddend(patchLocation
);
677 if ( *loc
!= newValue
) {
679 if ( context
.verboseBind
)
680 dyld::log("dyld: cache fixup: *%p = %p to %s\n", loc
, (void*)newValue
, symbolName
);
687 uintptr_t ImageLoaderMachOCompressed::resolveWeak(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
688 bool runResolver
, const ImageLoader
** foundIn
)
691 CoalesceNotifier notifier
= nullptr;
692 __block
uintptr_t foundOutsideCache
= 0;
693 __block
const char* foundOutsideCachePath
= nullptr;
694 __block
uintptr_t lastFoundInCache
= 0;
695 if ( this->usesChainedFixups() ) {
696 notifier
= ^(const Symbol
* implSym
, const ImageLoader
* implIn
, const mach_header
* implMh
) {
697 // This block is only called in dyld2 mode when a non-cached image is search for which weak-def implementation to use
698 // As a side effect of that search we notice any implementations outside and inside the cache,
699 // and use that to trigger patching the cache to use the implementation outside the cache.
700 uintptr_t implAddr
= implIn
->getExportedSymbolAddress(implSym
, context
, nullptr, false, symbolName
);
701 if ( ((dyld3::MachOLoaded
*)implMh
)->inDyldCache() ) {
702 if ( foundOutsideCache
!= 0 ) {
703 // have an implementation in cache and and earlier one not in the cache, patch cache to use earlier one
704 lastFoundInCache
= implAddr
;
706 if ( context
.dyldCache
->findMachHeaderImageIndex(implMh
, imageIndex
) ) {
707 const dyld3::closure::Image
* overriddenImage
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageIndex
+1);
708 uint32_t cacheOffsetOfImpl
= (uint32_t)((uintptr_t)implAddr
- (uintptr_t)context
.dyldCache
);
709 if ( context
.verboseWeakBind
)
710 dyld::log("dyld: weak bind, patching dyld cache uses of %s to use 0x%lX in %s\n", symbolName
, foundOutsideCache
, foundOutsideCachePath
);
711 patchCacheUsesOf(context
, overriddenImage
, cacheOffsetOfImpl
, symbolName
, foundOutsideCache
);
716 // record first non-cache implementation
717 if ( foundOutsideCache
== 0 ) {
718 foundOutsideCache
= implAddr
;
719 foundOutsideCachePath
= implIn
->getPath();
725 if ( context
.coalescedExportFinder(symbolName
, &sym
, foundIn
, notifier
) ) {
726 if ( *foundIn
!= this )
727 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
728 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
730 // if a bundle is loaded privately the above will not find its exports
731 if ( this->isBundle() && this->hasHiddenExports() ) {
732 // look in self for needed symbol
733 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
735 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
738 // definition can't be found anywhere, ok because it is weak, just return 0
741 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "weak");
745 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext
& context
, const char* symbolName
, const ImageLoader
* definedInImage
,
746 const ImageLoader
* requestorImage
, unsigned requestorOrdinalOfDef
, bool weak_import
, bool runResolver
,
747 const ImageLoader
** foundIn
)
751 if ( definedInImage
->findExportedSymbolAddress(context
, symbolName
, requestorImage
, requestorOrdinalOfDef
, runResolver
, foundIn
, &address
) )
755 // definition can't be found anywhere, ok because it is weak, just return 0
759 // nowhere to be found, check if maybe this image is too new for this OS
760 char versMismatch
[256];
761 versMismatch
[0] = '\0';
762 uint32_t imageMinOS
= this->minOSVersion();
763 // dyld is always built for the current OS, so we can get the current OS version
764 // from the load command in dyld itself.
765 extern const mach_header __dso_handle
;
766 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion(&__dso_handle
);
767 if ( imageMinOS
> dyldMinOS
) {
768 #if __MAC_OS_X_VERSION_MIN_REQUIRED
769 const char* msg
= dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
771 const char* msg
= dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
773 strcpy(versMismatch
, msg
);
776 throwSymbolNotFound(context
, symbolName
, this->getPath(), versMismatch
, definedInImage
->getPath());
780 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext
& context
, const char* symbolName
,
781 uint8_t symboFlags
, long libraryOrdinal
, const ImageLoader
** targetImage
,
782 LastLookup
* last
, bool runResolver
)
786 // only clients that benefit from caching last lookup pass in a LastLookup struct
787 if ( last
!= NULL
) {
788 if ( (last
->ordinal
== libraryOrdinal
)
789 && (last
->flags
== symboFlags
)
790 && (last
->name
== symbolName
) ) {
791 *targetImage
= last
->foundIn
;
796 bool weak_import
= (symboFlags
& BIND_SYMBOL_FLAGS_WEAK_IMPORT
);
797 uintptr_t symbolAddress
;
798 if ( context
.bindFlat
|| (libraryOrdinal
== BIND_SPECIAL_DYLIB_FLAT_LOOKUP
) ) {
799 symbolAddress
= this->resolveFlat(context
, symbolName
, weak_import
, runResolver
, targetImage
);
801 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_WEAK_LOOKUP
) {
802 symbolAddress
= this->resolveWeak(context
, symbolName
, false, runResolver
, targetImage
);
805 if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
) {
806 *targetImage
= context
.mainExecutable
;
808 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_SELF
) {
811 else if ( libraryOrdinal
<= 0 ) {
812 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
813 libraryOrdinal
, symbolName
, this->getPath());
815 else if ( (unsigned)libraryOrdinal
<= libraryCount() ) {
816 *targetImage
= libImage((unsigned int)libraryOrdinal
-1);
819 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
820 libraryOrdinal
, libraryCount(), symbolName
, this->getPath());
822 if ( *targetImage
== NULL
) {
824 // if target library not loaded and reference is weak or library is weak return 0
828 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
829 symbolName
, this->getPath(), libraryOrdinal
);
833 symbolAddress
= resolveTwolevel(context
, symbolName
, *targetImage
, this, (unsigned)libraryOrdinal
, weak_import
, runResolver
, targetImage
);
837 // save off lookup results if client wants
838 if ( last
!= NULL
) {
839 last
->ordinal
= libraryOrdinal
;
840 last
->flags
= symboFlags
;
841 last
->name
= symbolName
;
842 last
->foundIn
= *targetImage
;
843 last
->result
= symbolAddress
;
846 return symbolAddress
;
849 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
850 uintptr_t addr
, uint8_t type
, const char* symbolName
,
851 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
852 ExtraBindData
*extraBindData
,
853 const char* msg
, LastLookup
* last
, bool runResolver
)
855 const ImageLoader
* targetImage
;
856 uintptr_t symbolAddress
;
859 if (type
== BIND_TYPE_THREADED_REBASE
) {
861 targetImage
= nullptr;
863 symbolAddress
= image
->resolve(context
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
866 return image
->bindLocation(context
, image
->imageBaseAddress(), addr
, symbolAddress
, type
, symbolName
, addend
, image
->getPath(), targetImage
? targetImage
->getPath() : NULL
, msg
, extraBindData
, image
->fSlide
);
870 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
871 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
873 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
874 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
875 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
879 void ImageLoaderMachOCompressed::doBind(const LinkContext
& context
, bool forceLazysBound
)
881 CRSetCrashLogMessage2(this->getPath());
883 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
884 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
885 if ( this->usablePrebinding(context
) ) {
886 // don't need to bind
887 // except weak which may now be inline with the regular binds
888 if ( this->participatesInCoalescing() && (fDyldInfo
!= nullptr) ) {
889 // run through all binding opcodes
890 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
891 uintptr_t addr
, uint8_t type
, const char* symbolName
,
892 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
893 ExtraBindData
*extraBindData
,
894 const char* msg
, LastLookup
* last
, bool runResolver
) {
895 if ( libraryOrdinal
!= BIND_SPECIAL_DYLIB_WEAK_LOOKUP
)
897 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
898 addend
, libraryOrdinal
, extraBindData
,
899 msg
, last
, runResolver
);
904 uint64_t t0
= mach_absolute_time();
907 bool bindingBecauseOfRoot
= ( this->overridesCachedDylib(ignore
) || this->inSharedCache() );
908 vmAccountingSetSuspended(context
, bindingBecauseOfRoot
);
910 if ( fChainedFixups
!= NULL
) {
911 const dyld_chained_fixups_header
* fixupsHeader
= (dyld_chained_fixups_header
*)(fLinkEditBase
+ fChainedFixups
->dataoff
);
912 doApplyFixups(context
, fixupsHeader
);
914 else if ( fDyldInfo
!= nullptr ) {
915 #if TEXT_RELOC_SUPPORT
916 // if there are __TEXT fixups, temporarily make __TEXT writable
917 if ( fTextSegmentBinds
)
918 this->makeTextSegmentWritable(context
, true);
921 // run through all binding opcodes
922 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
923 uintptr_t addr
, uint8_t type
, const char* symbolName
,
924 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
925 ExtraBindData
*extraBindData
,
926 const char* msg
, LastLookup
* last
, bool runResolver
) {
927 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
928 addend
, libraryOrdinal
, extraBindData
,
929 msg
, last
, runResolver
);
932 #if TEXT_RELOC_SUPPORT
933 // if there were __TEXT fixups, restore write protection
934 if ( fTextSegmentBinds
)
935 this->makeTextSegmentWritable(context
, false);
938 // if this image is in the shared cache, but depends on something no longer in the shared cache,
939 // there is no way to reset the lazy pointers, so force bind them now
940 if ( forceLazysBound
|| fInSharedCache
)
941 this->doBindJustLazies(context
);
943 // this image is in cache, but something below it is not. If
944 // this image has lazy pointer to a resolver function, then
945 // the stub may have been altered to point to a shared lazy pointer.
946 if ( fInSharedCache
)
947 this->updateOptimizedLazyPointers(context
);
950 uint64_t t1
= mach_absolute_time();
951 ImageLoader::fgTotalRebindCacheTime
+= (t1
-t0
);
954 // See if this dylib overrides something in the dyld cache
955 uint32_t dyldCacheOverrideImageNum
;
956 if ( context
.dyldCache
&& context
.dyldCache
->header
.builtFromChainedFixups
&& overridesCachedDylib(dyldCacheOverrideImageNum
) ) {
957 // need to patch all other places in cache that point to the overridden dylib, to point to this dylib instead
958 const dyld3::closure::Image
* overriddenImage
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(dyldCacheOverrideImageNum
);
959 uint32_t imageIndex
= dyldCacheOverrideImageNum
- (uint32_t)context
.dyldCache
->cachedDylibsImageArray()->startImageNum();
960 context
.dyldCache
->forEachPatchableExport(imageIndex
, ^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
961 uintptr_t newImpl
= 0;
962 const ImageLoader
* foundIn
;
963 this->findExportedSymbolAddress(context
, exportName
, NULL
, 0, false, &foundIn
, &newImpl
);
964 patchCacheUsesOf(context
, overriddenImage
, cacheOffsetOfImpl
, exportName
, newImpl
);
968 // set up dyld entry points in image
969 // do last so flat main executables will have __dyld or __program_vars set up
970 this->setupLazyPointerHandler(context
);
971 CRSetCrashLogMessage2(NULL
);
975 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext
& context
)
977 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
978 uintptr_t addr
, uint8_t type
, const char* symbolName
,
979 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
980 ExtraBindData
*extraBindData
,
981 const char* msg
, LastLookup
* last
, bool runResolver
) {
982 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
983 addend
, libraryOrdinal
, extraBindData
,
984 msg
, last
, runResolver
);
988 void ImageLoaderMachOCompressed::doApplyFixups(const LinkContext
& context
, const dyld_chained_fixups_header
* fixupsHeader
)
990 const dyld3::MachOLoaded
* ml
= (dyld3::MachOLoaded
*)machHeader();
991 const dyld_chained_starts_in_image
* starts
= (dyld_chained_starts_in_image
*)((uint8_t*)fixupsHeader
+ fixupsHeader
->starts_offset
);
993 // build table of resolved targets for each symbol ordinal
994 STACK_ALLOC_OVERFLOW_SAFE_ARRAY(const void*, targetAddrs
, 128);
995 targetAddrs
.reserve(fixupsHeader
->imports_count
);
996 __block Diagnostics diag
;
997 const dyld3::MachOAnalyzer
* ma
= (dyld3::MachOAnalyzer
*)ml
;
998 ma
->forEachChainedFixupTarget(diag
, ^(int libOrdinal
, const char* symbolName
, uint64_t addend
, bool weakImport
, bool& stop
) {
999 const ImageLoader
* targetImage
;
1000 uint8_t symbolFlags
= weakImport
? BIND_SYMBOL_FLAGS_WEAK_IMPORT
: 0;
1002 uintptr_t symbolAddress
= this->resolve(context
, symbolName
, symbolFlags
, libOrdinal
, &targetImage
, NULL
, true);
1003 targetAddrs
.push_back((void*)(symbolAddress
+ addend
));
1005 catch (const char* msg
) {
1007 diag
.error("%s", msg
);
1010 if ( diag
.hasError() )
1011 throw strdup(diag
.errorMessage());
1013 auto logFixups
= ^(void* loc
, void* newValue
) {
1014 dyld::log("dyld: fixup: %s:%p = %p\n", this->getShortName(), loc
, newValue
);
1016 if ( !context
.verboseBind
)
1017 logFixups
= nullptr;
1019 ml
->fixupAllChainedFixups(diag
, starts
, fSlide
, targetAddrs
, logFixups
);
1020 if ( diag
.hasError() )
1021 throw strdup(diag
.errorMessage());
1024 void ImageLoaderMachOCompressed::registerInterposing(const LinkContext
& context
)
1026 // mach-o files advertise interposing by having a __DATA __interpose section
1027 struct InterposeData
{ uintptr_t replacement
; uintptr_t replacee
; };
1029 __block Diagnostics diag
;
1030 const dyld3::MachOAnalyzer
* ma
= (dyld3::MachOAnalyzer
*)fMachOData
;
1031 ma
->forEachInterposingSection(diag
, ^(uint64_t vmOffset
, uint64_t vmSize
, bool& stopSections
) {
1032 if ( ma
->hasChainedFixups() ) {
1033 const uint16_t pointerFormat
= ma
->chainedPointerFormat();
1034 const uint8_t* sectionStart
= fMachOData
+vmOffset
;
1035 const uint8_t* sectionEnd
= fMachOData
+vmOffset
+vmSize
;
1036 ma
->withChainStarts(diag
, ma
->chainStartsOffset(), ^(const dyld_chained_starts_in_image
* startsInfo
) {
1037 __block
uintptr_t lastRebaseTarget
= 0;
1038 ma
->forEachFixupInAllChains(diag
, startsInfo
, false, ^(dyld3::MachOLoaded::ChainedFixupPointerOnDisk
* fixupLoc
, const dyld_chained_starts_in_segment
* segInfo
, bool& stopFixups
) {
1039 if ( ((uint8_t*)fixupLoc
< sectionStart
) || ((uint8_t*)fixupLoc
>= sectionEnd
) )
1041 uint64_t rebaseTargetRuntimeOffset
;
1042 uint32_t bindOrdinal
;
1043 if ( fixupLoc
->isRebase(pointerFormat
, 0, rebaseTargetRuntimeOffset
) ) {
1044 //dyld::log("interpose rebase at fixup at %p to 0x%0llX\n", fixupLoc, rebaseTargetRuntimeOffset);
1045 lastRebaseTarget
= (uintptr_t)(fMachOData
+rebaseTargetRuntimeOffset
);
1047 else if ( fixupLoc
->isBind(pointerFormat
, bindOrdinal
) ) {
1048 //dyld::log("interpose bind fixup at %p to bind ordinal %d\n", fixupLoc, bindOrdinal);
1049 __block
uint32_t targetBindIndex
= 0;
1050 ma
->forEachChainedFixupTarget(diag
, ^(int libraryOrdinal
, const char* symbolName
, uint64_t addend
, bool weakImport
, bool& stop
) {
1051 if ( targetBindIndex
== bindOrdinal
) {
1052 //dyld::log("interpose bind fixup at %p is to %s libOrdinal=%d\n", fixupLoc, symbolName, libraryOrdinal);
1053 LastLookup
* last
= NULL
;
1054 const ImageLoader
* targetImage
;
1055 uintptr_t targetBindAddress
= 0;
1057 targetBindAddress
= this->resolve(context
, symbolName
, 0, libraryOrdinal
, &targetImage
, last
, false);
1059 catch (const char* msg
) {
1062 targetBindAddress
= 0;
1064 //dyld::log("interpose bind fixup at %p is bound to 0x%lX\n", fixupLoc, targetBindAddress);
1065 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1066 if ( targetBindAddress
== 0 )
1068 ImageLoader::InterposeTuple tuple
;
1069 tuple
.replacement
= lastRebaseTarget
;
1070 tuple
.neverImage
= this;
1071 tuple
.onlyImage
= NULL
;
1072 tuple
.replacee
= targetBindAddress
;
1073 // <rdar://problem/7937695> verify that replacement is in this image
1074 if ( this->containsAddress((void*)tuple
.replacement
) ) {
1075 if ( context
.verboseInterposing
)
1076 dyld::log("dyld: interposing 0x%lx with 0x%lx\n", tuple
.replacee
, tuple
.replacement
);
1077 // chain to any existing interpositions
1078 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
1079 if ( it
->replacee
== tuple
.replacee
) {
1080 tuple
.replacee
= it
->replacement
;
1083 ImageLoader::fgInterposingTuples
.push_back(tuple
);
1093 // traditional (non-chained) fixups
1094 const size_t count
= (size_t)(vmSize
/ sizeof(InterposeData
));
1095 const InterposeData
* interposeArray
= (InterposeData
*)(fMachOData
+vmOffset
);
1096 if ( context
.verboseInterposing
)
1097 dyld::log("dyld: found %lu interposing tuples in %s\n", count
, getPath());
1098 for (size_t j
=0; j
< count
; ++j
) {
1099 uint64_t bindOffset
= ((uint8_t*)&(interposeArray
[j
].replacee
)) - fMachOData
;
1100 ma
->forEachBind(diag
, ^(uint64_t runtimeOffset
, int libOrdinal
, const char* symbolName
, bool weakImport
, bool lazyBind
, uint64_t addend
, bool& stopBinds
) {
1101 if ( bindOffset
!= runtimeOffset
)
1104 LastLookup
* last
= NULL
;
1105 const ImageLoader
* targetImage
;
1106 uintptr_t targetBindAddress
= 0;
1108 targetBindAddress
= this->resolve(context
, symbolName
, 0, libOrdinal
, &targetImage
, last
, false);
1110 catch (const char* msg
) {
1113 targetBindAddress
= 0;
1115 ImageLoader::InterposeTuple tuple
;
1116 tuple
.replacement
= interposeArray
[j
].replacement
;
1117 tuple
.neverImage
= this;
1118 tuple
.onlyImage
= NULL
;
1119 tuple
.replacee
= targetBindAddress
;
1120 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1121 if ( tuple
.replacee
== 0 )
1123 // <rdar://problem/7937695> verify that replacement is in this image
1124 if ( this->containsAddress((void*)tuple
.replacement
) ) {
1125 if ( context
.verboseInterposing
)
1126 dyld::log("dyld: interposing 0x%lx with 0x%lx\n", tuple
.replacee
, tuple
.replacement
);
1127 // chain to any existing interpositions
1128 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
1129 if ( it
->replacee
== tuple
.replacee
) {
1130 tuple
.replacee
= it
->replacement
;
1133 ImageLoader::fgInterposingTuples
.push_back(tuple
);
1135 }, ^(const char* symbolName
){ },
1142 bool ImageLoaderMachOCompressed::usesChainedFixups() const
1144 return ((dyld3::MachOLoaded
*)machHeader())->hasChainedFixups();
1147 struct ThreadedBindData
{
1148 ThreadedBindData(const char* symbolName
, int64_t addend
, long libraryOrdinal
, uint8_t symbolFlags
, uint8_t type
)
1149 : symbolName(symbolName
), addend(addend
), libraryOrdinal(libraryOrdinal
), symbolFlags(symbolFlags
), type(type
) { }
1151 std::tuple
<const char*, int64_t, long, bool, uint8_t> pack() const {
1152 return std::make_tuple(symbolName
, addend
, libraryOrdinal
, symbolFlags
, type
);
1155 const char* symbolName
= nullptr;
1157 long libraryOrdinal
= 0;
1158 uint8_t symbolFlags
= 0;
1162 void ImageLoaderMachOCompressed::makeDataReadOnly() const
1164 #if !TEXT_RELOC_SUPPORT
1165 if ( fReadOnlyDataSegment
&& !this->ImageLoader::inSharedCache() ) {
1166 for (unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1167 if ( segIsReadOnlyData(i
) ) {
1168 uintptr_t start
= segActualLoadAddress(i
);
1169 uintptr_t size
= segSize(i
);
1170 ::mprotect((void*)start
, size
, PROT_READ
);
1171 //dyld::log("make read-only 0x%09lX -> 0x%09lX\n", (long)start, (long)(start+size));
1179 void ImageLoaderMachOCompressed::eachBind(const LinkContext
& context
, bind_handler handler
)
1183 int segmentIndex
= -1;
1184 uintptr_t address
= segActualLoadAddress(0);
1185 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1186 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1187 const char* symbolName
= NULL
;
1188 uint8_t symboFlags
= 0;
1189 bool libraryOrdinalSet
= false;
1190 long libraryOrdinal
= 0;
1191 intptr_t addend
= 0;
1194 uintptr_t segOffset
= 0;
1196 dyld3::OverflowSafeArray
<ThreadedBindData
> ordinalTable
;
1197 bool useThreadedRebaseBind
= false;
1198 ExtraBindData extraBindData
;
1199 LastLookup last
= { 0, 0, NULL
, 0, NULL
};
1200 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->bind_off
;
1201 const uint8_t* const end
= &start
[fDyldInfo
->bind_size
];
1202 const uint8_t* p
= start
;
1204 while ( !done
&& (p
< end
) ) {
1205 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1206 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1209 case BIND_OPCODE_DONE
:
1212 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1213 libraryOrdinal
= immediate
;
1214 libraryOrdinalSet
= true;
1216 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1217 libraryOrdinal
= read_uleb128(p
, end
);
1218 libraryOrdinalSet
= true;
1220 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1221 // the special ordinals are negative numbers
1222 if ( immediate
== 0 )
1225 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1226 libraryOrdinal
= signExtended
;
1228 libraryOrdinalSet
= true;
1230 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1231 symbolName
= (char*)p
;
1232 symboFlags
= immediate
;
1237 case BIND_OPCODE_SET_TYPE_IMM
:
1240 case BIND_OPCODE_SET_ADDEND_SLEB
:
1241 addend
= read_sleb128(p
, end
);
1243 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1244 segmentIndex
= immediate
;
1245 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1246 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1247 segmentIndex
, fSegmentsCount
-1);
1248 #if TEXT_RELOC_SUPPORT
1249 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
1251 if ( !segWriteable(segmentIndex
) )
1253 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1254 segOffset
= read_uleb128(p
, end
);
1255 if ( segOffset
> segSize(segmentIndex
) )
1256 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1257 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1258 address
= segmentStartAddress
+ segOffset
;
1259 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1261 case BIND_OPCODE_ADD_ADDR_ULEB
:
1262 address
+= read_uleb128(p
, end
);
1264 case BIND_OPCODE_DO_BIND
:
1265 if (!useThreadedRebaseBind
) {
1266 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1267 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1268 if ( symbolName
== NULL
)
1269 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1270 if ( segmentIndex
== -1 )
1271 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1272 if ( !libraryOrdinalSet
)
1273 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1274 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1275 &extraBindData
, "", &last
, false);
1276 address
+= sizeof(intptr_t);
1278 ordinalTable
.push_back(ThreadedBindData(symbolName
, addend
, libraryOrdinal
, symboFlags
, type
));
1281 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1282 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1283 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1284 if ( symbolName
== NULL
)
1285 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1286 if ( segmentIndex
== -1 )
1287 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1288 if ( !libraryOrdinalSet
)
1289 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1290 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1291 &extraBindData
, "", &last
, false);
1292 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1294 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1295 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1296 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1297 if ( symbolName
== NULL
)
1298 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1299 if ( segmentIndex
== -1 )
1300 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1301 if ( !libraryOrdinalSet
)
1302 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1303 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1304 &extraBindData
, "", &last
, false);
1305 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1307 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1308 if ( symbolName
== NULL
)
1309 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1310 if ( segmentIndex
== -1 )
1311 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1312 count
= read_uleb128(p
, end
);
1313 if ( !libraryOrdinalSet
)
1314 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1315 skip
= read_uleb128(p
, end
);
1316 for (uint32_t i
=0; i
< count
; ++i
) {
1317 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1318 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1319 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1320 &extraBindData
, "", &last
, false);
1321 address
+= skip
+ sizeof(intptr_t);
1324 case BIND_OPCODE_THREADED
:
1325 if (sizeof(intptr_t) != 8) {
1326 dyld::throwf("BIND_OPCODE_THREADED require 64-bit");
1329 // Note the immediate is a sub opcode
1330 switch (immediate
) {
1331 case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB
:
1332 count
= read_uleb128(p
, end
);
1333 ordinalTable
.clear();
1334 // FIXME: ld64 wrote the wrong value here and we need to offset by 1 for now.
1335 ordinalTable
.reserve(count
+ 1);
1336 useThreadedRebaseBind
= true;
1338 case BIND_SUBOPCODE_THREADED_APPLY
: {
1341 address
= segmentStartAddress
+ segOffset
;
1342 uint64_t value
= *(uint64_t*)address
;
1345 bool isRebase
= (value
& (1ULL << 62)) == 0;
1348 // Call the bind handler which knows about our bind type being set to rebase
1349 handler(context
, this, address
, BIND_TYPE_THREADED_REBASE
, nullptr, 0, 0, 0,
1350 nullptr, "", &last
, false);
1353 // the ordinal is bits [0..15]
1354 uint16_t ordinal
= value
& 0xFFFF;
1355 if (ordinal
>= ordinalTable
.count()) {
1356 dyld::throwf("bind ordinal (%d) is out of range (max=%lu) for disk pointer 0x%16llX at segIndex=%d, segOffset=0x%0lX in %s",
1357 ordinal
, ordinalTable
.count(),value
, segmentIndex
, segOffset
, this->getPath());
1360 std::tie(symbolName
, addend
, libraryOrdinal
, symboFlags
, type
) = ordinalTable
[ordinal
].pack();
1361 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1362 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1364 handler(context
, this, address
, BIND_TYPE_THREADED_BIND
,
1365 symbolName
, symboFlags
, addend
, libraryOrdinal
,
1366 nullptr, "", &last
, false);
1370 // The delta is bits [51..61]
1371 // And bit 62 is to tell us if we are a rebase (0) or bind (1)
1372 value
&= ~(1ULL << 62);
1373 delta
= ( value
& 0x3FF8000000000000 ) >> 51;
1374 segOffset
+= delta
* sizeof(intptr_t);
1375 } while ( delta
!= 0 );
1380 dyld::throwf("bad threaded bind subopcode 0x%02X", *p
);
1384 dyld::throwf("bad bind opcode %d in bind info", *p
);
1388 catch (const char* msg
) {
1389 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1395 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext
& context
, bind_handler handler
)
1398 uint8_t type
= BIND_TYPE_POINTER
;
1399 int segmentIndex
= -1;
1400 uintptr_t address
= segActualLoadAddress(0);
1401 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1402 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1403 uintptr_t segOffset
;
1404 const char* symbolName
= NULL
;
1405 uint8_t symboFlags
= 0;
1406 long libraryOrdinal
= 0;
1407 intptr_t addend
= 0;
1408 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1409 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1410 const uint8_t* p
= start
;
1412 while ( !done
&& (p
< end
) ) {
1413 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1414 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1417 case BIND_OPCODE_DONE
:
1418 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1420 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1421 libraryOrdinal
= immediate
;
1423 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1424 libraryOrdinal
= read_uleb128(p
, end
);
1426 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1427 // the special ordinals are negative numbers
1428 if ( immediate
== 0 )
1431 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1432 libraryOrdinal
= signExtended
;
1435 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1436 symbolName
= (char*)p
;
1437 symboFlags
= immediate
;
1442 case BIND_OPCODE_SET_TYPE_IMM
:
1445 case BIND_OPCODE_SET_ADDEND_SLEB
:
1446 addend
= read_sleb128(p
, end
);
1448 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1449 segmentIndex
= immediate
;
1450 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1451 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1452 segmentIndex
, fSegmentsCount
-1);
1453 if ( !segWriteable(segmentIndex
) )
1454 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1455 segOffset
= read_uleb128(p
, end
);
1456 if ( segOffset
> segSize(segmentIndex
) )
1457 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1458 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1459 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1460 address
= segmentStartAddress
+ segOffset
;
1462 case BIND_OPCODE_ADD_ADDR_ULEB
:
1463 address
+= read_uleb128(p
, end
);
1465 case BIND_OPCODE_DO_BIND
:
1466 if ( segmentIndex
== -1 )
1467 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1468 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1469 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1470 if ( symbolName
== NULL
)
1471 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1472 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1473 NULL
, "forced lazy ", NULL
, false);
1474 address
+= sizeof(intptr_t);
1476 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1477 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1478 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1480 dyld::throwf("bad lazy bind opcode %d", *p
);
1485 catch (const char* msg
) {
1486 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1492 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1493 // the classic lazy loader is used even when running on 10.6
1494 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1496 // only works with compressed LINKEDIT if classic symbol table is also present
1497 const macho_nlist
* symbolTable
= NULL
;
1498 const char* symbolTableStrings
= NULL
;
1499 const dysymtab_command
* dynSymbolTable
= NULL
;
1500 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1501 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1502 const struct load_command
* cmd
= cmds
;
1503 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1507 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1508 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1509 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1513 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1516 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1518 // no symbol table => no lookup by address
1519 if ( (symbolTable
== NULL
) || (dynSymbolTable
== NULL
) )
1520 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer
, this->getPath());
1522 // scan for all lazy-pointer sections
1523 const bool twoLevel
= this->usesTwoLevelNameSpace();
1524 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1526 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1528 case LC_SEGMENT_COMMAND
:
1530 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1531 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1532 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1533 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1534 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1535 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1536 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1537 const size_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1538 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1539 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1540 const uint32_t indirectTableOffset
= sect
->reserved1
;
1541 const size_t lazyIndex
= lazyPointer
- symbolPointers
;
1542 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1545 if ( (symbolIndex
!= INDIRECT_SYMBOL_ABS
) && (symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) ) {
1546 const macho_nlist
* symbol
= &symbolTable
[symbolIndex
];
1547 const char* symbolName
= &symbolTableStrings
[symbol
->n_un
.n_strx
];
1548 int libraryOrdinal
= GET_LIBRARY_ORDINAL(symbol
->n_desc
);
1549 if ( !twoLevel
|| context
.bindFlat
)
1550 libraryOrdinal
= BIND_SPECIAL_DYLIB_FLAT_LOOKUP
;
1551 uintptr_t ptrToBind
= (uintptr_t)lazyPointer
;
1552 uintptr_t symbolAddr
= bindAt(context
, this, ptrToBind
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
,
1553 NULL
, "lazy ", NULL
);
1554 ++fgTotalLazyBindFixups
;
1561 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1563 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1568 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
,
1569 void (*lock
)(), void (*unlock
)())
1571 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1572 if ( this->usesTwoLevelNameSpace() ) {
1573 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1576 // acquire dyld global lock
1581 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1582 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1584 uintptr_t segOffset
;
1586 const char* symbolName
;
1590 if ( ! getLazyBindingInfo(lazyBindingInfoOffset
, start
, end
, &segIndex
, &segOffset
, &libraryOrdinal
, &symbolName
, &doneAfterBind
) )
1591 dyld::throwf("bad lazy bind info");
1593 if ( segIndex
>= fSegmentsCount
)
1594 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1595 segIndex
, fSegmentsCount
-1);
1596 if ( segOffset
> segSize(segIndex
) )
1597 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segIndex
));
1598 uintptr_t address
= segActualLoadAddress(segIndex
) + segOffset
;
1599 result
= bindAt(context
, this, address
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
,
1600 NULL
, "lazy ", NULL
, true);
1601 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1602 } while (!doneAfterBind
&& !context
.strictMachORequired
);
1604 if ( !this->usesTwoLevelNameSpace() ) {
1605 // release dyld global lock
1606 if ( unlock
!= NULL
)
1612 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
, unsigned)
1615 it
.symbolName
= " ";
1616 it
.loadOrder
= loadOrder
;
1617 it
.weakSymbol
= false;
1618 it
.symbolMatches
= false;
1621 it
.endIndex
= (this->fDyldInfo
? this->fDyldInfo
->weak_bind_size
: 0);
1628 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator
& it
)
1633 if ( (this->fDyldInfo
== nullptr) || (this->fDyldInfo
->weak_bind_size
== 0) ) {
1634 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1636 it
.symbolName
= "~~~";
1639 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1640 const uint8_t* p
= start
+ it
.curIndex
;
1641 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1644 uintptr_t segOffset
;
1646 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1647 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1650 case BIND_OPCODE_DONE
:
1652 it
.curIndex
= p
- start
;
1653 it
.symbolName
= "~~~"; // sorts to end
1655 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1656 it
.symbolName
= (char*)p
;
1657 it
.weakSymbol
= ((immediate
& BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION
) == 0);
1658 it
.symbolMatches
= false;
1662 it
.curIndex
= p
- start
;
1664 case BIND_OPCODE_SET_TYPE_IMM
:
1665 it
.type
= immediate
;
1667 case BIND_OPCODE_SET_ADDEND_SLEB
:
1668 it
.addend
= read_sleb128(p
, end
);
1670 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1671 if ( immediate
>= fSegmentsCount
)
1672 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1673 immediate
, fSegmentsCount
-1);
1675 // <rdar://problem/23138428> iOS app compatibility
1676 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1677 #elif TEXT_RELOC_SUPPORT
1678 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1679 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1680 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1682 if ( !segWriteable(immediate
) )
1684 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1685 segOffset
= read_uleb128(p
, end
);
1686 if ( segOffset
> segSize(immediate
) )
1687 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1688 it
.address
= segActualLoadAddress(immediate
) + segOffset
;
1690 case BIND_OPCODE_ADD_ADDR_ULEB
:
1691 it
.address
+= read_uleb128(p
, end
);
1693 case BIND_OPCODE_DO_BIND
:
1694 it
.address
+= sizeof(intptr_t);
1696 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1697 it
.address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1699 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1700 it
.address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1702 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1703 count
= read_uleb128(p
, end
);
1704 skip
= read_uleb128(p
, end
);
1705 for (uint32_t i
=0; i
< count
; ++i
) {
1706 it
.address
+= skip
+ sizeof(intptr_t);
1710 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p
, (int)(p
-start
), this->getPath());
1713 /// hmmm, BIND_OPCODE_DONE is missing...
1715 it
.symbolName
= "~~~";
1716 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1720 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1722 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1723 const ImageLoader
* foundIn
= NULL
;
1724 const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(it
.symbolName
, &foundIn
);
1725 if ( sym
!= NULL
) {
1726 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1727 return foundIn
->getExportedSymbolAddress(sym
, context
, this);
1733 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, unsigned targetIndex
, const LinkContext
& context
)
1735 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1736 if ( this->getState() < dyld_image_state_bound
)
1739 if ( fDyldInfo
== nullptr )
1742 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1743 const uint8_t* p
= start
+ it
.curIndex
;
1744 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1746 uint8_t type
= it
.type
;
1747 uintptr_t address
= it
.address
;
1748 const char* symbolName
= it
.symbolName
;
1749 intptr_t addend
= it
.addend
;
1752 uintptr_t segOffset
;
1754 bool boundSomething
= false;
1755 while ( !done
&& (p
< end
) ) {
1756 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1757 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1760 case BIND_OPCODE_DONE
:
1763 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1766 case BIND_OPCODE_SET_TYPE_IMM
:
1769 case BIND_OPCODE_SET_ADDEND_SLEB
:
1770 addend
= read_sleb128(p
, end
);
1772 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1773 if ( immediate
>= fSegmentsCount
)
1774 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1775 immediate
, fSegmentsCount
-1);
1777 // <rdar://problem/23138428> iOS app compatibility
1778 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1779 #elif TEXT_RELOC_SUPPORT
1780 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1781 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1782 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1784 if ( !segWriteable(immediate
) )
1786 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1787 segOffset
= read_uleb128(p
, end
);
1788 if ( segOffset
> segSize(immediate
) )
1789 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1790 address
= segActualLoadAddress(immediate
) + segOffset
;
1792 case BIND_OPCODE_ADD_ADDR_ULEB
:
1793 address
+= read_uleb128(p
, end
);
1795 case BIND_OPCODE_DO_BIND
:
1796 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1797 boundSomething
= true;
1798 address
+= sizeof(intptr_t);
1800 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1801 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1802 boundSomething
= true;
1803 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1805 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1806 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1807 boundSomething
= true;
1808 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1810 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1811 count
= read_uleb128(p
, end
);
1812 skip
= read_uleb128(p
, end
);
1813 for (uint32_t i
=0; i
< count
; ++i
) {
1814 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1815 boundSomething
= true;
1816 address
+= skip
+ sizeof(intptr_t);
1820 dyld::throwf("bad bind opcode %d in weak binding info", *p
);
1823 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1824 if ( boundSomething
&& (targetImage
!= this) )
1825 context
.addDynamicReference(this, targetImage
);
1828 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
1829 uintptr_t addr
, uint8_t type
, const char*,
1830 uint8_t, intptr_t, long,
1831 ExtraBindData
*extraBindData
,
1832 const char*, LastLookup
*, bool runResolver
)
1834 if ( type
== BIND_TYPE_POINTER
) {
1835 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1836 uintptr_t curValue
= *fixupLocation
;
1837 uintptr_t newValue
= interposedAddress(context
, curValue
, image
);
1838 if ( newValue
!= curValue
) {
1839 *fixupLocation
= newValue
;
1845 void ImageLoaderMachOCompressed::doInterpose(const LinkContext
& context
)
1847 if ( context
.verboseInterposing
)
1848 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples
.size(), this->getPath());
1850 const dyld3::MachOAnalyzer
* ma
= (dyld3::MachOAnalyzer
*)fMachOData
;
1851 if ( !ma
->hasChainedFixups() && (fDyldInfo
!= nullptr) ) {
1852 // Note: all binds that happen as part of normal loading and fixups will have interposing applied.
1853 // There is only two cases where we need to parse bind opcodes and apply interposing:
1855 // 1) Lazy pointers are either not bound yet, or in dyld cache they are prebound (to uninterposed target)
1856 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1857 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1858 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1859 ExtraBindData
*extraBindData
,
1860 const char* msg
, LastLookup
* last
, bool runResolver
) {
1861 return ImageLoaderMachOCompressed::interposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1862 addend
, libraryOrdinal
, extraBindData
,
1863 msg
, last
, runResolver
);
1866 // 2) non-lazy pointers in the dyld cache need to be interposed
1867 if ( ma
->inDyldCache() ) {
1868 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1869 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1870 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1871 ExtraBindData
*extraBindData
,
1872 const char* msg
, LastLookup
* last
, bool runResolver
) {
1873 return ImageLoaderMachOCompressed::interposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1874 addend
, libraryOrdinal
, extraBindData
,
1875 msg
, last
, runResolver
);
1883 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
1884 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1885 uint8_t, intptr_t, long,
1886 ExtraBindData
*extraBindData
,
1887 const char*, LastLookup
*, bool runResolver
)
1889 if ( type
== BIND_TYPE_POINTER
) {
1890 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1891 uintptr_t value
= *fixupLocation
;
1892 // don't apply interposing to table entries.
1893 if ( (context
.dynamicInterposeArray
<= (void*)addr
) && ((void*)addr
< &context
.dynamicInterposeArray
[context
.dynamicInterposeCount
]) )
1895 for(size_t i
=0; i
< context
.dynamicInterposeCount
; ++i
) {
1896 if ( value
== (uintptr_t)context
.dynamicInterposeArray
[i
].replacee
) {
1897 if ( context
.verboseInterposing
) {
1898 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1899 fixupLocation
, context
.dynamicInterposeArray
[i
].replacee
, context
.dynamicInterposeArray
[i
].replacement
, image
->getPath());
1901 *fixupLocation
= (uintptr_t)context
.dynamicInterposeArray
[i
].replacement
;
1908 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext
& context
)
1910 if ( context
.verboseInterposing
)
1911 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context
.dynamicInterposeCount
, this->getPath());
1913 // update already bound references to symbols
1914 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1915 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1916 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1917 ExtraBindData
*extraBindData
,
1918 const char* msg
, LastLookup
* last
, bool runResolver
) {
1919 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1920 addend
, libraryOrdinal
, extraBindData
,
1921 msg
, last
, runResolver
);
1923 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1924 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1925 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1926 ExtraBindData
*extraBindData
,
1927 const char* msg
, LastLookup
* last
, bool runResolver
) {
1928 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1929 addend
, libraryOrdinal
, extraBindData
,
1930 msg
, last
, runResolver
);
1934 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1936 return ImageLoaderMachO::findClosestSymbol((mach_header
*)fMachOData
, addr
, closestAddr
);
1940 #if PREBOUND_IMAGE_SUPPORT
1941 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext
& context
)
1943 // no way to back off a prebound compress image
1948 #if __arm__ || __x86_64__
1949 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub
, void** originalLazyPointerAddr
, const LinkContext
& context
)
1952 uint32_t* instructions
= (uint32_t*)stub
;
1953 // sanity check this is a stub we understand
1954 if ( (instructions
[0] != 0xe59fc004) || (instructions
[1] != 0xe08fc00c) || (instructions
[2] != 0xe59cf000) )
1957 void** lazyPointerAddr
= (void**)(instructions
[3] + (stub
+ 12));
1960 // sanity check this is a stub we understand
1961 if ( (stub
[0] != 0xFF) || (stub
[1] != 0x25) )
1963 int32_t ripOffset
= *((int32_t*)(&stub
[2]));
1964 void** lazyPointerAddr
= (void**)(ripOffset
+ stub
+ 6);
1967 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1968 if ( lazyPointerAddr
!= originalLazyPointerAddr
) {
1969 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1970 const ImageLoader
* lazyPointerImage
= context
.findImageContainingAddress(lazyPointerAddr
);
1971 if ( lazyPointerImage
!= NULL
)
1974 // copy newly re-bound lazy pointer value to shared lazy pointer
1975 *lazyPointerAddr
= *originalLazyPointerAddr
;
1977 if ( context
.verboseBind
)
1978 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1979 this->getShortName(), (long)lazyPointerAddr
, (long)*originalLazyPointerAddr
);
1985 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1986 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext
& context
)
1988 #if __arm__ || __x86_64__
1989 // find stubs and indirect symbol table
1990 const struct macho_section
* stubsSection
= NULL
;
1991 const dysymtab_command
* dynSymbolTable
= NULL
;
1992 const macho_header
* mh
= (macho_header
*)fMachOData
;
1993 const uint32_t cmd_count
= mh
->ncmds
;
1994 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1995 const struct load_command
* cmd
= cmds
;
1996 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1997 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1998 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1999 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2000 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2001 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
2002 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
2003 if ( type
== S_SYMBOL_STUBS
)
2004 stubsSection
= sect
;
2007 else if ( cmd
->cmd
== LC_DYSYMTAB
) {
2008 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
2010 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2012 if ( dynSymbolTable
== NULL
)
2014 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
2015 if ( stubsSection
== NULL
)
2017 const uint32_t stubsSize
= stubsSection
->reserved2
;
2018 const uint32_t stubsCount
= (uint32_t)(stubsSection
->size
/ stubsSize
);
2019 const uint32_t stubsIndirectTableOffset
= stubsSection
->reserved1
;
2020 if ( (stubsIndirectTableOffset
+stubsCount
) > dynSymbolTable
->nindirectsyms
)
2022 uint8_t* const stubsAddr
= (uint8_t*)(stubsSection
->addr
+ this->fSlide
);
2024 // for each lazy pointer section
2026 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2027 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2028 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2029 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2030 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2031 for (const struct macho_section
* lazyPointerSection
=sectionsStart
; lazyPointerSection
< sectionsEnd
; ++lazyPointerSection
) {
2032 const uint8_t type
= lazyPointerSection
->flags
& SECTION_TYPE
;
2033 if ( type
!= S_LAZY_SYMBOL_POINTERS
)
2035 const uint32_t lazyPointersCount
= (uint32_t)(lazyPointerSection
->size
/ sizeof(void*));
2036 const uint32_t lazyPointersIndirectTableOffset
= lazyPointerSection
->reserved1
;
2037 if ( (lazyPointersIndirectTableOffset
+lazyPointersCount
) > dynSymbolTable
->nindirectsyms
)
2039 void** const lazyPointersAddr
= (void**)(lazyPointerSection
->addr
+ this->fSlide
);
2040 // for each lazy pointer
2041 for(uint32_t lpIndex
=0; lpIndex
< lazyPointersCount
; ++lpIndex
) {
2042 const uint32_t lpSymbolIndex
= indirectTable
[lazyPointersIndirectTableOffset
+lpIndex
];
2043 // find matching stub and validate it uses this lazy pointer
2044 for(uint32_t stubIndex
=0; stubIndex
< stubsCount
; ++stubIndex
) {
2045 if ( indirectTable
[stubsIndirectTableOffset
+stubIndex
] == lpSymbolIndex
) {
2046 this->updateAlternateLazyPointer(stubsAddr
+stubIndex
*stubsSize
, &lazyPointersAddr
[lpIndex
], context
);
2054 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2061 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command
* encryptCmd
, const LinkContext
& context
)
2063 #if __arm__ || __arm64__
2064 if ( encryptCmd
== NULL
)
2066 // fMachOData not set up yet, need to manually find mach_header
2067 const mach_header
* mh
= NULL
;
2068 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
2069 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
2070 mh
= (mach_header
*)segActualLoadAddress(i
);
2071 void* start
= ((uint8_t*)mh
) + encryptCmd
->cryptoff
;
2072 size_t len
= encryptCmd
->cryptsize
;
2073 uint32_t cputype
= mh
->cputype
;
2074 uint32_t cpusubtype
= mh
->cpusubtype
;
2075 uint32_t cryptid
= encryptCmd
->cryptid
;
2076 if (context
.verboseMapping
) {
2077 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start
, (long)start
+len
);
2079 int result
= mremap_encrypted(start
, len
, cryptid
, cputype
, cpusubtype
);
2080 if ( result
!= 0 ) {
2081 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result
, errno
, this->getPath());