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 <sys/sysctl.h>
39 #include <mach/mach.h>
40 #include <mach/thread_status.h>
41 #include <mach-o/loader.h>
42 #include "ImageLoaderMachOCompressed.h"
43 #include "mach-o/dyld_images.h"
45 #ifndef EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
46 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
49 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
52 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
53 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
54 struct macho_segment_command
: public segment_command_64
{};
55 struct macho_section
: public section_64
{};
56 struct macho_routines_command
: public routines_command_64
{};
59 #define LC_SEGMENT_COMMAND LC_SEGMENT
60 #define LC_ROUTINES_COMMAND LC_ROUTINES
61 struct macho_segment_command
: public segment_command
{};
62 struct macho_section
: public section
{};
63 struct macho_routines_command
: public routines_command
{};
66 #if __arm__ || __arm64__
67 bool ImageLoaderMachOCompressed::sVmAccountingDisabled
= false;
68 bool ImageLoaderMachOCompressed::sVmAccountingSuspended
= false;
73 // create image for main executable
74 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
,
75 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
77 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
79 // set slide for PIE programs
80 image
->setSlide(slide
);
82 // for PIE record end of program, to know where to start loading dylibs
84 fgNextPIEDylibAddress
= (uintptr_t)image
->getEnd();
86 image
->disableCoverageCheck();
87 image
->instantiateFinish(context
);
88 image
->setMapped(context
);
90 if ( context
.verboseMapping
) {
91 dyld::log("dyld: Main executable mapped %s\n", path
);
92 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
93 const char* name
= image
->segName(i
);
94 if ( (strcmp(name
, "__PAGEZERO") == 0) || (strcmp(name
, "__UNIXSTACK") == 0) )
95 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segPreferredLoadAddress(i
), image
->segPreferredLoadAddress(i
)+image
->segSize(i
));
97 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
104 // create image by mapping in a mach-o file
105 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromFile(const char* path
, int fd
, const uint8_t* fileData
, size_t lenFileData
,
106 uint64_t offsetInFat
, uint64_t lenInFat
, const struct stat
& info
,
107 unsigned int segCount
, unsigned int libCount
,
108 const struct linkedit_data_command
* codeSigCmd
,
109 const struct encryption_info_command
* encryptCmd
,
110 const LinkContext
& context
)
112 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart((macho_header
*)fileData
, path
, segCount
, libCount
);
115 // record info about file
116 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
118 // if this image is code signed, let kernel validate signature before mapping any pages from image
119 image
->loadCodeSignature(codeSigCmd
, fd
, offsetInFat
, context
);
121 // Validate that first data we read with pread actually matches with code signature
122 image
->validateFirstPages(codeSigCmd
, fd
, fileData
, lenFileData
, offsetInFat
, context
);
125 image
->mapSegments(fd
, offsetInFat
, lenInFat
, info
.st_size
, context
);
127 // if framework is FairPlay encrypted, register with kernel
128 image
->registerEncryption(encryptCmd
, context
);
130 // probe to see if code signed correctly
131 image
->crashIfInvalidCodeSignature();
133 // finish construction
134 image
->instantiateFinish(context
);
136 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
137 const char* installName
= image
->getInstallPath();
138 if ( (installName
!= NULL
) && (strcmp(installName
, path
) == 0) && (path
[0] == '/') )
139 image
->setPathUnowned(installName
);
140 #if __MAC_OS_X_VERSION_MIN_REQUIRED
141 // <rdar://problem/6563887> app crashes when libSystem cannot be found
142 else if ( (installName
!= NULL
) && (strcmp(path
, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName
, "/usr/lib/libSystem.B.dylib") == 0) )
143 image
->setPathUnowned("/usr/lib/libSystem.B.dylib");
145 else if ( (path
[0] != '/') || (strstr(path
, "../") != NULL
) ) {
146 // rdar://problem/10733082 Fix up @rpath based paths during introspection
147 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
148 char realPath
[MAXPATHLEN
];
149 if ( fcntl(fd
, F_GETPATH
, realPath
) == 0 )
150 image
->setPaths(path
, realPath
);
152 image
->setPath(path
);
155 image
->setPath(path
);
157 // make sure path is stable before recording in dyld_all_image_infos
158 image
->setMapped(context
);
160 // dylibs with thread local variables cannot be unloaded because there is no way to clean up all threads
161 if ( image
->machHeader()->flags
& MH_HAS_TLV_DESCRIPTORS
)
162 image
->setNeverUnload();
164 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
165 // don't do this on prebound images or if prefetching is disabled
166 if ( !context
.preFetchDisabled
&& !image
->isPrebindable()) {
167 image
->preFetchDATA(fd
, offsetInFat
, context
);
168 image
->markSequentialLINKEDIT(context
);
172 // ImageLoader::setMapped() can throw an exception to block loading of image
173 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
181 // create image by using cached mach-o file
182 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
,
183 const struct stat
& info
, unsigned int segCount
,
184 unsigned int libCount
, const LinkContext
& context
)
186 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
188 // record info about file
189 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
191 // remember this is from shared cache and cannot be unloaded
192 image
->fInSharedCache
= true;
193 image
->setNeverUnload();
194 image
->setSlide(slide
);
195 image
->disableCoverageCheck();
197 // segments already mapped in cache
198 if ( context
.verboseMapping
) {
199 dyld::log("dyld: Using shared cached for %s\n", path
);
200 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
201 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
205 image
->instantiateFinish(context
);
206 image
->setMapped(context
);
209 // ImageLoader::setMapped() can throw an exception to block loading of image
210 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
218 // create image by copying an in-memory mach-o file
219 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
220 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
222 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, moduleName
, segCount
, libCount
);
225 if ( mh
->filetype
== MH_EXECUTE
)
226 throw "can't load another MH_EXECUTE";
229 image
->mapSegments((const void*)mh
, len
, context
);
231 // for compatibility, never unload dylibs loaded from memory
232 image
->setNeverUnload();
234 image
->disableCoverageCheck();
236 // bundle loads need path copied
237 if ( moduleName
!= NULL
)
238 image
->setPath(moduleName
);
240 image
->instantiateFinish(context
);
241 image
->setMapped(context
);
244 // ImageLoader::setMapped() can throw an exception to block loading of image
245 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
254 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header
* mh
, const char* path
, unsigned int segCount
,
255 uint32_t segOffsets
[], unsigned int libCount
)
256 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fDyldInfo(NULL
)
260 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
262 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
268 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
269 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateStart(const macho_header
* mh
, const char* path
,
270 unsigned int segCount
, unsigned int libCount
)
272 size_t size
= sizeof(ImageLoaderMachOCompressed
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
273 ImageLoaderMachOCompressed
* allocatedSpace
= static_cast<ImageLoaderMachOCompressed
*>(malloc(size
));
274 if ( allocatedSpace
== NULL
)
275 throw "malloc failed";
276 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOCompressed
)));
277 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
278 return new (allocatedSpace
) ImageLoaderMachOCompressed(mh
, path
, segCount
, segOffsets
, libCount
);
282 // common code to finish initializing object
283 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext
& context
)
285 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
286 this->parseLoadCmds(context
);
289 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
291 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
)));
295 ImageLoader
* ImageLoaderMachOCompressed::libImage(unsigned int libIndex
) const
297 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
299 return (ImageLoader
*)(images
[libIndex
] & (-4));
302 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex
) const
304 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
305 // re-export flag is low bit
306 return ((images
[libIndex
] & 1) != 0);
309 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex
) const
311 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
312 // re-export flag is second bit
313 return ((images
[libIndex
] & 2) != 0);
317 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
, bool upward
)
319 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
320 uintptr_t value
= (uintptr_t)image
;
325 images
[libIndex
] = value
;
329 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext
& context
)
331 // mark that we are done with rebase and bind info
332 markLINKEDIT(context
, MADV_FREE
);
335 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext
& context
)
337 // mark the rebase and bind info and using sequential access
338 markLINKEDIT(context
, MADV_SEQUENTIAL
);
341 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext
& context
, int advise
)
343 // if not loaded at preferred address, mark rebase info
345 if ( (fSlide
!= 0) && (fDyldInfo
->rebase_size
!= 0) )
346 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
;
347 else if ( fDyldInfo
->bind_off
!= 0 )
348 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
;
350 return; // no binding info to prefetch
352 // end is at end of bind info
354 if ( fDyldInfo
->bind_off
!= 0 )
355 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
+ fDyldInfo
->bind_size
;
356 else if ( fDyldInfo
->rebase_off
!= 0 )
357 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
+ fDyldInfo
->rebase_size
;
362 // round to whole pages
363 start
= dyld_page_trunc(start
);
364 end
= dyld_page_round(end
);
366 // do nothing if only one page of rebase/bind info
367 if ( (end
-start
) <= dyld_page_size
)
370 // tell kernel about our access to these pages
371 madvise((void*)start
, end
-start
, advise
);
372 if ( context
.verboseMapping
) {
373 const char* adstr
= "sequential";
374 if ( advise
== MADV_FREE
)
376 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr
, start
, end
-1, this->getPath());
382 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext
& context
, uintptr_t addr
, uintptr_t slide
, uint8_t type
)
384 if ( context
.verboseRebase
) {
385 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr
, slide
);
387 //dyld::log("0x%08lX type=%d\n", addr, type);
388 uintptr_t* locationToFix
= (uintptr_t*)addr
;
390 case REBASE_TYPE_POINTER
:
391 *locationToFix
+= slide
;
393 case REBASE_TYPE_TEXT_ABSOLUTE32
:
394 *locationToFix
+= slide
;
397 dyld::throwf("bad rebase type %d", type
);
401 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
402 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
404 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
405 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
406 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
409 void ImageLoaderMachOCompressed::rebase(const LinkContext
& context
, uintptr_t slide
)
411 CRSetCrashLogMessage2(this->getPath());
412 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->rebase_off
;
413 const uint8_t* const end
= &start
[fDyldInfo
->rebase_size
];
414 const uint8_t* p
= start
;
418 int segmentIndex
= 0;
419 uintptr_t address
= segActualLoadAddress(0);
420 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
421 uintptr_t segmentEndAddress
= segActualEndAddress(0);
425 while ( !done
&& (p
< end
) ) {
426 uint8_t immediate
= *p
& REBASE_IMMEDIATE_MASK
;
427 uint8_t opcode
= *p
& REBASE_OPCODE_MASK
;
430 case REBASE_OPCODE_DONE
:
433 case REBASE_OPCODE_SET_TYPE_IMM
:
436 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
437 segmentIndex
= immediate
;
438 if ( segmentIndex
>= fSegmentsCount
)
439 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
440 segmentIndex
, fSegmentsCount
-1);
441 #if TEXT_RELOC_SUPPORT
442 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
444 if ( !segWriteable(segmentIndex
) )
446 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
447 segmentIndex
, segName(segmentIndex
));
448 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
449 segmentEndAddress
= segActualEndAddress(segmentIndex
);
450 address
= segmentStartAddress
+ read_uleb128(p
, end
);
452 case REBASE_OPCODE_ADD_ADDR_ULEB
:
453 address
+= read_uleb128(p
, end
);
455 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED
:
456 address
+= immediate
*sizeof(uintptr_t);
458 case REBASE_OPCODE_DO_REBASE_IMM_TIMES
:
459 for (int i
=0; i
< immediate
; ++i
) {
460 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
461 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
462 rebaseAt(context
, address
, slide
, type
);
463 address
+= sizeof(uintptr_t);
465 fgTotalRebaseFixups
+= immediate
;
467 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES
:
468 count
= read_uleb128(p
, end
);
469 for (uint32_t i
=0; i
< count
; ++i
) {
470 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
471 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
472 rebaseAt(context
, address
, slide
, type
);
473 address
+= sizeof(uintptr_t);
475 fgTotalRebaseFixups
+= count
;
477 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB
:
478 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
479 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
480 rebaseAt(context
, address
, slide
, type
);
481 address
+= read_uleb128(p
, end
) + sizeof(uintptr_t);
482 ++fgTotalRebaseFixups
;
484 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
:
485 count
= read_uleb128(p
, end
);
486 skip
= read_uleb128(p
, end
);
487 for (uint32_t i
=0; i
< count
; ++i
) {
488 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
489 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
490 rebaseAt(context
, address
, slide
, type
);
491 address
+= skip
+ sizeof(uintptr_t);
493 fgTotalRebaseFixups
+= count
;
496 dyld::throwf("bad rebase opcode %d", *p
);
500 catch (const char* msg
) {
501 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
505 CRSetCrashLogMessage2(NULL
);
508 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol
, const ImageLoader
** foundIn
) const
510 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
511 if ( fDyldInfo
->export_size
== 0 )
514 dyld::logBindings("%s: %s\n", this->getShortName(), symbol
);
516 ++ImageLoaderMachO::fgSymbolTrieSearchs
;
517 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
518 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
519 const uint8_t* foundNodeStart
= this->trieWalk(start
, end
, symbol
);
520 if ( foundNodeStart
!= NULL
) {
521 const uint8_t* p
= foundNodeStart
;
522 const uintptr_t flags
= read_uleb128(p
, end
);
523 // found match, return pointer to terminal part of node
524 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
525 // re-export from another dylib, lookup there
526 const uintptr_t ordinal
= read_uleb128(p
, end
);
527 const char* importedName
= (char*)p
;
528 if ( importedName
[0] == '\0' )
529 importedName
= symbol
;
530 if ( (ordinal
> 0) && (ordinal
<= libraryCount()) ) {
531 const ImageLoader
* reexportedFrom
= libImage((unsigned int)ordinal
-1);
532 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
533 const char* reExportLibPath
= libPath((unsigned int)ordinal
-1);
534 return reexportedFrom
->findExportedSymbol(importedName
, true, reExportLibPath
, foundIn
);
537 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
538 // ordinal, libraryCount(), symbol, this->getPath());
542 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
543 if ( foundIn
!= NULL
)
544 *foundIn
= (ImageLoader
*)this;
545 // return pointer to terminal part of node
546 return (Symbol
*)foundNodeStart
;
553 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr
) const
555 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
556 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
557 return ( (start
<= addr
) && (addr
< end
) );
561 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext
& context
, const Symbol
* symbol
, const ImageLoader
* requestor
, bool runResolver
) const
563 const uint8_t* exportNode
= (uint8_t*)symbol
;
564 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
565 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
566 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
567 throw "symbol is not in trie";
568 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
569 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
570 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
571 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
572 if ( runResolver
&& (flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) ) {
573 // this node has a stub and resolver, run the resolver to get target address
574 uintptr_t stub
= read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
; // skip over stub
575 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
576 uintptr_t interposedStub
= interposedAddress(context
, stub
, requestor
);
577 if ( interposedStub
!= stub
)
578 return interposedStub
;
579 // stub was not interposed, so run resolver
580 typedef uintptr_t (*ResolverProc
)(void);
581 ResolverProc resolver
= (ResolverProc
)(read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
);
582 uintptr_t result
= (*resolver
)();
583 if ( context
.verboseBind
)
584 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver
, result
);
587 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
588 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
589 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
590 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
591 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
592 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
593 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
594 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
595 return read_uleb128(exportNode
, exportTrieEnd
);
597 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
601 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
603 const uint8_t* exportNode
= (uint8_t*)symbol
;
604 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
605 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
606 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
607 throw "symbol is not in trie";
608 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
609 return ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
);
613 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol
* symbol
) const
615 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
618 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
620 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
623 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index
) const
625 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
628 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
630 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
633 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index
) const
635 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
638 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol
* symbol
) const
640 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
645 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
646 bool runResolver
, const ImageLoader
** foundIn
)
649 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
650 if ( *foundIn
!= this )
651 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
652 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
654 // if a bundle is loaded privately the above will not find its exports
655 if ( this->isBundle() && this->hasHiddenExports() ) {
656 // look in self for needed symbol
657 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
659 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
662 // definition can't be found anywhere, ok because it is weak, just return 0
665 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "flat namespace");
669 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext
& context
, const char* symbolName
, const ImageLoader
* definedInImage
,
670 const ImageLoader
* requestorImage
, unsigned requestorOrdinalOfDef
, bool weak_import
, bool runResolver
,
671 const ImageLoader
** foundIn
)
675 if ( definedInImage
->findExportedSymbolAddress(context
, symbolName
, requestorImage
, requestorOrdinalOfDef
, runResolver
, foundIn
, &address
) )
679 // definition can't be found anywhere, ok because it is weak, just return 0
683 // nowhere to be found, check if maybe this image is too new for this OS
684 char versMismatch
[256];
685 versMismatch
[0] = '\0';
686 uint32_t imageMinOS
= this->minOSVersion();
687 // dyld is always built for the current OS, so we can get the current OS version
688 // from the load command in dyld itself.
689 extern const mach_header __dso_handle
;
690 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion(&__dso_handle
);
691 if ( imageMinOS
> dyldMinOS
) {
692 #if __MAC_OS_X_VERSION_MIN_REQUIRED
693 const char* msg
= dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
695 const char* msg
= dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
697 strcpy(versMismatch
, msg
);
700 throwSymbolNotFound(context
, symbolName
, this->getPath(), versMismatch
, definedInImage
->getPath());
704 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext
& context
, const char* symbolName
,
705 uint8_t symboFlags
, long libraryOrdinal
, const ImageLoader
** targetImage
,
706 LastLookup
* last
, bool runResolver
)
710 // only clients that benefit from caching last lookup pass in a LastLookup struct
711 if ( last
!= NULL
) {
712 if ( (last
->ordinal
== libraryOrdinal
)
713 && (last
->flags
== symboFlags
)
714 && (last
->name
== symbolName
) ) {
715 *targetImage
= last
->foundIn
;
720 bool weak_import
= (symboFlags
& BIND_SYMBOL_FLAGS_WEAK_IMPORT
);
721 uintptr_t symbolAddress
;
722 if ( context
.bindFlat
|| (libraryOrdinal
== BIND_SPECIAL_DYLIB_FLAT_LOOKUP
) ) {
723 symbolAddress
= this->resolveFlat(context
, symbolName
, weak_import
, runResolver
, targetImage
);
726 if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
) {
727 *targetImage
= context
.mainExecutable
;
729 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_SELF
) {
732 else if ( libraryOrdinal
<= 0 ) {
733 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
734 libraryOrdinal
, symbolName
, this->getPath());
736 else if ( (unsigned)libraryOrdinal
<= libraryCount() ) {
737 *targetImage
= libImage((unsigned int)libraryOrdinal
-1);
740 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
741 libraryOrdinal
, libraryCount(), symbolName
, this->getPath());
743 if ( *targetImage
== NULL
) {
745 // if target library not loaded and reference is weak or library is weak return 0
749 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
750 symbolName
, this->getPath(), libraryOrdinal
);
754 symbolAddress
= resolveTwolevel(context
, symbolName
, *targetImage
, this, (unsigned)libraryOrdinal
, weak_import
, runResolver
, targetImage
);
758 // save off lookup results if client wants
759 if ( last
!= NULL
) {
760 last
->ordinal
= libraryOrdinal
;
761 last
->flags
= symboFlags
;
762 last
->name
= symbolName
;
763 last
->foundIn
= *targetImage
;
764 last
->result
= symbolAddress
;
767 return symbolAddress
;
770 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
771 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
, const char* msg
,
772 LastLookup
* last
, bool runResolver
)
774 const ImageLoader
* targetImage
;
775 uintptr_t symbolAddress
;
778 symbolAddress
= this->resolve(context
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
781 return this->bindLocation(context
, addr
, symbolAddress
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, msg
);
785 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
786 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
788 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
789 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
790 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
794 void ImageLoaderMachOCompressed::doBind(const LinkContext
& context
, bool forceLazysBound
)
796 CRSetCrashLogMessage2(this->getPath());
798 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
799 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
800 if ( this->usablePrebinding(context
) ) {
801 // don't need to bind
804 uint64_t t0
= mach_absolute_time();
806 #if TEXT_RELOC_SUPPORT
807 // if there are __TEXT fixups, temporarily make __TEXT writable
808 if ( fTextSegmentBinds
)
809 this->makeTextSegmentWritable(context
, true);
812 // run through all binding opcodes
813 eachBind(context
, &ImageLoaderMachOCompressed::bindAt
);
815 #if TEXT_RELOC_SUPPORT
816 // if there were __TEXT fixups, restore write protection
817 if ( fTextSegmentBinds
)
818 this->makeTextSegmentWritable(context
, false);
821 // if this image is in the shared cache, but depends on something no longer in the shared cache,
822 // there is no way to reset the lazy pointers, so force bind them now
823 if ( forceLazysBound
|| fInSharedCache
)
824 this->doBindJustLazies(context
);
826 // this image is in cache, but something below it is not. If
827 // this image has lazy pointer to a resolver function, then
828 // the stub may have been altered to point to a shared lazy pointer.
829 if ( fInSharedCache
)
830 this->updateOptimizedLazyPointers(context
);
832 // tell kernel we are done with chunks of LINKEDIT
833 if ( !context
.preFetchDisabled
)
834 this->markFreeLINKEDIT(context
);
836 uint64_t t1
= mach_absolute_time();
837 ImageLoader::fgTotalRebindCacheTime
+= (t1
-t0
);
840 // set up dyld entry points in image
841 // do last so flat main executables will have __dyld or __program_vars set up
842 this->setupLazyPointerHandler(context
);
843 CRSetCrashLogMessage2(NULL
);
847 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext
& context
)
849 eachLazyBind(context
, &ImageLoaderMachOCompressed::bindAt
);
852 #if __arm__ || __arm64__
853 int ImageLoaderMachOCompressed::vmAccountingSetSuspended(bool suspend
, const LinkContext
& context
)
855 if ( context
.verboseBind
)
856 dyld::log("vm.footprint_suspend=%d\n", suspend
);
857 int newValue
= suspend
? 1 : 0;
859 size_t newlen
= sizeof(newValue
);
860 size_t oldlen
= sizeof(oldValue
);
861 return sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
865 void ImageLoaderMachOCompressed::eachBind(const LinkContext
& context
, bind_handler handler
)
867 #if __arm__ || __arm64__
868 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
869 if ( !sVmAccountingDisabled
) {
870 if ( fInSharedCache
) {
871 if ( !sVmAccountingSuspended
) {
872 int ret
= vmAccountingSetSuspended(true, context
);
873 if ( context
.verboseBind
&& (ret
!= 0) )
874 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
876 sVmAccountingSuspended
= true;
878 sVmAccountingDisabled
= true;
881 else if ( sVmAccountingSuspended
) {
882 int ret
= vmAccountingSetSuspended(false, context
);
884 sVmAccountingSuspended
= false;
885 else if ( errno
== ENOENT
)
886 sVmAccountingDisabled
= true;
893 int segmentIndex
= -1;
894 uintptr_t address
= segActualLoadAddress(0);
895 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
896 uintptr_t segmentEndAddress
= segActualEndAddress(0);
897 const char* symbolName
= NULL
;
898 uint8_t symboFlags
= 0;
899 bool libraryOrdinalSet
= false;
900 long libraryOrdinal
= 0;
905 LastLookup last
= { 0, 0, NULL
, 0, NULL
};
906 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->bind_off
;
907 const uint8_t* const end
= &start
[fDyldInfo
->bind_size
];
908 const uint8_t* p
= start
;
910 while ( !done
&& (p
< end
) ) {
911 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
912 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
915 case BIND_OPCODE_DONE
:
918 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
919 libraryOrdinal
= immediate
;
920 libraryOrdinalSet
= true;
922 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
923 libraryOrdinal
= read_uleb128(p
, end
);
924 libraryOrdinalSet
= true;
926 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
927 // the special ordinals are negative numbers
928 if ( immediate
== 0 )
931 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
932 libraryOrdinal
= signExtended
;
934 libraryOrdinalSet
= true;
936 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
937 symbolName
= (char*)p
;
938 symboFlags
= immediate
;
943 case BIND_OPCODE_SET_TYPE_IMM
:
946 case BIND_OPCODE_SET_ADDEND_SLEB
:
947 addend
= read_sleb128(p
, end
);
949 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
950 segmentIndex
= immediate
;
951 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
952 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
953 segmentIndex
, fSegmentsCount
-1);
954 #if TEXT_RELOC_SUPPORT
955 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
957 if ( !segWriteable(segmentIndex
) )
959 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
960 segOffset
= read_uleb128(p
, end
);
961 if ( segOffset
> segSize(segmentIndex
) )
962 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
963 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
964 address
= segmentStartAddress
+ segOffset
;
965 segmentEndAddress
= segActualEndAddress(segmentIndex
);
967 case BIND_OPCODE_ADD_ADDR_ULEB
:
968 address
+= read_uleb128(p
, end
);
970 case BIND_OPCODE_DO_BIND
:
971 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
972 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
973 if ( symbolName
== NULL
)
974 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
975 if ( segmentIndex
== -1 )
976 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
977 if ( !libraryOrdinalSet
)
978 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
979 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
980 address
+= sizeof(intptr_t);
982 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
983 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
984 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
985 if ( symbolName
== NULL
)
986 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
987 if ( segmentIndex
== -1 )
988 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
989 if ( !libraryOrdinalSet
)
990 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
991 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
992 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
994 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
995 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
996 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
997 if ( symbolName
== NULL
)
998 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
999 if ( segmentIndex
== -1 )
1000 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1001 if ( !libraryOrdinalSet
)
1002 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1003 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
1004 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1006 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1007 if ( symbolName
== NULL
)
1008 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1009 if ( segmentIndex
== -1 )
1010 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1011 count
= read_uleb128(p
, end
);
1012 if ( !libraryOrdinalSet
)
1013 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1014 skip
= read_uleb128(p
, end
);
1015 for (uint32_t i
=0; i
< count
; ++i
) {
1016 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1017 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1018 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
1019 address
+= skip
+ sizeof(intptr_t);
1023 dyld::throwf("bad bind opcode %d in bind info", *p
);
1027 catch (const char* msg
) {
1028 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1034 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext
& context
, bind_handler handler
)
1037 uint8_t type
= BIND_TYPE_POINTER
;
1038 int segmentIndex
= -1;
1039 uintptr_t address
= segActualLoadAddress(0);
1040 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1041 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1042 uintptr_t segOffset
;
1043 const char* symbolName
= NULL
;
1044 uint8_t symboFlags
= 0;
1045 long libraryOrdinal
= 0;
1046 intptr_t addend
= 0;
1047 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1048 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1049 const uint8_t* p
= start
;
1051 while ( !done
&& (p
< end
) ) {
1052 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1053 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1056 case BIND_OPCODE_DONE
:
1057 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1059 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1060 libraryOrdinal
= immediate
;
1062 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1063 libraryOrdinal
= read_uleb128(p
, end
);
1065 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1066 // the special ordinals are negative numbers
1067 if ( immediate
== 0 )
1070 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1071 libraryOrdinal
= signExtended
;
1074 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1075 symbolName
= (char*)p
;
1076 symboFlags
= immediate
;
1081 case BIND_OPCODE_SET_TYPE_IMM
:
1084 case BIND_OPCODE_SET_ADDEND_SLEB
:
1085 addend
= read_sleb128(p
, end
);
1087 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1088 segmentIndex
= immediate
;
1089 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1090 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1091 segmentIndex
, fSegmentsCount
-1);
1092 if ( !segWriteable(segmentIndex
) )
1093 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1094 segOffset
= read_uleb128(p
, end
);
1095 if ( segOffset
> segSize(segmentIndex
) )
1096 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1097 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1098 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1099 address
= segmentStartAddress
+ segOffset
;
1101 case BIND_OPCODE_ADD_ADDR_ULEB
:
1102 address
+= read_uleb128(p
, end
);
1104 case BIND_OPCODE_DO_BIND
:
1105 if ( segmentIndex
== -1 )
1106 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1107 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1108 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1109 if ( symbolName
== NULL
)
1110 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1111 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "forced lazy ", NULL
, false);
1112 address
+= sizeof(intptr_t);
1114 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1115 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1116 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1118 dyld::throwf("bad lazy bind opcode %d", *p
);
1123 catch (const char* msg
) {
1124 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1130 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1131 // the classic lazy loader is used even when running on 10.6
1132 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1134 // only works with compressed LINKEDIT if classic symbol table is also present
1135 const macho_nlist
* symbolTable
= NULL
;
1136 const char* symbolTableStrings
= NULL
;
1137 const dysymtab_command
* dynSymbolTable
= NULL
;
1138 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1139 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1140 const struct load_command
* cmd
= cmds
;
1141 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1145 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1146 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1147 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1151 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1154 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1156 // no symbol table => no lookup by address
1157 if ( (symbolTable
== NULL
) || (dynSymbolTable
== NULL
) )
1158 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer
, this->getPath());
1160 // scan for all lazy-pointer sections
1161 const bool twoLevel
= this->usesTwoLevelNameSpace();
1162 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1164 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1166 case LC_SEGMENT_COMMAND
:
1168 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1169 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1170 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1171 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1172 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1173 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1174 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1175 const size_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1176 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1177 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1178 const uint32_t indirectTableOffset
= sect
->reserved1
;
1179 const size_t lazyIndex
= lazyPointer
- symbolPointers
;
1180 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1183 if ( (symbolIndex
!= INDIRECT_SYMBOL_ABS
) && (symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) ) {
1184 const macho_nlist
* symbol
= &symbolTable
[symbolIndex
];
1185 const char* symbolName
= &symbolTableStrings
[symbol
->n_un
.n_strx
];
1186 int libraryOrdinal
= GET_LIBRARY_ORDINAL(symbol
->n_desc
);
1187 if ( !twoLevel
|| context
.bindFlat
)
1188 libraryOrdinal
= BIND_SPECIAL_DYLIB_FLAT_LOOKUP
;
1189 uintptr_t ptrToBind
= (uintptr_t)lazyPointer
;
1190 uintptr_t symbolAddr
= bindAt(context
, ptrToBind
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
);
1191 ++fgTotalLazyBindFixups
;
1198 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1200 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1205 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
,
1206 void (*lock
)(), void (*unlock
)())
1208 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1209 if ( this->usesTwoLevelNameSpace() ) {
1210 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1213 // acquire dyld global lock
1218 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1219 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1221 uintptr_t segOffset
;
1223 const char* symbolName
;
1227 if ( ! getLazyBindingInfo(lazyBindingInfoOffset
, start
, end
, &segIndex
, &segOffset
, &libraryOrdinal
, &symbolName
, &doneAfterBind
) )
1228 dyld::throwf("bad lazy bind info");
1230 if ( segIndex
>= fSegmentsCount
)
1231 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1232 segIndex
, fSegmentsCount
-1);
1233 if ( segOffset
> segSize(segIndex
) )
1234 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segIndex
));
1235 uintptr_t address
= segActualLoadAddress(segIndex
) + segOffset
;
1236 result
= this->bindAt(context
, address
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
, true);
1237 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1238 } while (!doneAfterBind
&& !context
.strictMachORequired
);
1240 if ( !this->usesTwoLevelNameSpace() ) {
1241 // release dyld global lock
1242 if ( unlock
!= NULL
)
1248 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
, unsigned)
1251 it
.symbolName
= " ";
1252 it
.loadOrder
= loadOrder
;
1253 it
.weakSymbol
= false;
1254 it
.symbolMatches
= false;
1257 it
.endIndex
= this->fDyldInfo
->weak_bind_size
;
1264 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator
& it
)
1269 if ( this->fDyldInfo
->weak_bind_size
== 0 ) {
1270 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1272 it
.symbolName
= "~~~";
1275 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1276 const uint8_t* p
= start
+ it
.curIndex
;
1277 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1280 uintptr_t segOffset
;
1282 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1283 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1286 case BIND_OPCODE_DONE
:
1288 it
.curIndex
= p
- start
;
1289 it
.symbolName
= "~~~"; // sorts to end
1291 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1292 it
.symbolName
= (char*)p
;
1293 it
.weakSymbol
= ((immediate
& BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION
) == 0);
1294 it
.symbolMatches
= false;
1298 it
.curIndex
= p
- start
;
1300 case BIND_OPCODE_SET_TYPE_IMM
:
1301 it
.type
= immediate
;
1303 case BIND_OPCODE_SET_ADDEND_SLEB
:
1304 it
.addend
= read_sleb128(p
, end
);
1306 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1307 if ( immediate
>= fSegmentsCount
)
1308 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1309 immediate
, fSegmentsCount
-1);
1311 // <rdar://problem/23138428> iOS app compatibility
1312 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1313 #elif TEXT_RELOC_SUPPORT
1314 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1315 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1316 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1318 if ( !segWriteable(immediate
) )
1320 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1321 segOffset
= read_uleb128(p
, end
);
1322 if ( segOffset
> segSize(immediate
) )
1323 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1324 it
.address
= segActualLoadAddress(immediate
) + segOffset
;
1326 case BIND_OPCODE_ADD_ADDR_ULEB
:
1327 it
.address
+= read_uleb128(p
, end
);
1329 case BIND_OPCODE_DO_BIND
:
1330 it
.address
+= sizeof(intptr_t);
1332 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1333 it
.address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1335 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1336 it
.address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1338 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1339 count
= read_uleb128(p
, end
);
1340 skip
= read_uleb128(p
, end
);
1341 for (uint32_t i
=0; i
< count
; ++i
) {
1342 it
.address
+= skip
+ sizeof(intptr_t);
1346 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p
, (int)(p
-start
), this->getPath());
1349 /// hmmm, BIND_OPCODE_DONE is missing...
1351 it
.symbolName
= "~~~";
1352 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1356 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1358 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1359 const ImageLoader
* foundIn
= NULL
;
1360 const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(it
.symbolName
, &foundIn
);
1361 if ( sym
!= NULL
) {
1362 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1363 return foundIn
->getExportedSymbolAddress(sym
, context
, this);
1369 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, unsigned targetIndex
, const LinkContext
& context
)
1371 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1372 if ( this->getState() < dyld_image_state_bound
)
1375 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1376 const uint8_t* p
= start
+ it
.curIndex
;
1377 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1379 uint8_t type
= it
.type
;
1380 uintptr_t address
= it
.address
;
1381 const char* symbolName
= it
.symbolName
;
1382 intptr_t addend
= it
.addend
;
1385 uintptr_t segOffset
;
1387 bool boundSomething
= false;
1388 while ( !done
&& (p
< end
) ) {
1389 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1390 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1393 case BIND_OPCODE_DONE
:
1396 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1399 case BIND_OPCODE_SET_TYPE_IMM
:
1402 case BIND_OPCODE_SET_ADDEND_SLEB
:
1403 addend
= read_sleb128(p
, end
);
1405 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1406 if ( immediate
>= fSegmentsCount
)
1407 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1408 immediate
, fSegmentsCount
-1);
1410 // <rdar://problem/23138428> iOS app compatibility
1411 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1412 #elif TEXT_RELOC_SUPPORT
1413 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1414 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1415 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1417 if ( !segWriteable(immediate
) )
1419 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1420 segOffset
= read_uleb128(p
, end
);
1421 if ( segOffset
> segSize(immediate
) )
1422 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1423 address
= segActualLoadAddress(immediate
) + segOffset
;
1425 case BIND_OPCODE_ADD_ADDR_ULEB
:
1426 address
+= read_uleb128(p
, end
);
1428 case BIND_OPCODE_DO_BIND
:
1429 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1430 boundSomething
= true;
1431 address
+= sizeof(intptr_t);
1433 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1434 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1435 boundSomething
= true;
1436 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1438 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1439 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1440 boundSomething
= true;
1441 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1443 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1444 count
= read_uleb128(p
, end
);
1445 skip
= read_uleb128(p
, end
);
1446 for (uint32_t i
=0; i
< count
; ++i
) {
1447 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1448 boundSomething
= true;
1449 address
+= skip
+ sizeof(intptr_t);
1453 dyld::throwf("bad bind opcode %d in weak binding info", *p
);
1456 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1457 if ( boundSomething
&& (targetImage
!= this) )
1458 context
.addDynamicReference(this, targetImage
);
1461 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char*,
1462 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1464 if ( type
== BIND_TYPE_POINTER
) {
1465 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1466 uintptr_t curValue
= *fixupLocation
;
1467 uintptr_t newValue
= interposedAddress(context
, curValue
, this);
1468 if ( newValue
!= curValue
) {
1469 *fixupLocation
= newValue
;
1475 void ImageLoaderMachOCompressed::doInterpose(const LinkContext
& context
)
1477 if ( context
.verboseInterposing
)
1478 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples
.size(), this->getPath());
1480 // update prebound symbols
1481 eachBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1482 eachLazyBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1486 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
1487 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1489 if ( type
== BIND_TYPE_POINTER
) {
1490 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1491 uintptr_t value
= *fixupLocation
;
1492 // don't apply interposing to table entries.
1493 if ( (context
.dynamicInterposeArray
<= (void*)addr
) && ((void*)addr
< &context
.dynamicInterposeArray
[context
.dynamicInterposeCount
]) )
1495 for(size_t i
=0; i
< context
.dynamicInterposeCount
; ++i
) {
1496 if ( value
== (uintptr_t)context
.dynamicInterposeArray
[i
].replacee
) {
1497 if ( context
.verboseInterposing
) {
1498 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1499 fixupLocation
, context
.dynamicInterposeArray
[i
].replacee
, context
.dynamicInterposeArray
[i
].replacement
, this->getPath());
1501 *fixupLocation
= (uintptr_t)context
.dynamicInterposeArray
[i
].replacement
;
1508 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext
& context
)
1510 if ( context
.verboseInterposing
)
1511 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context
.dynamicInterposeCount
, this->getPath());
1513 // update already bound references to symbols
1514 eachBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1515 eachLazyBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1518 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1520 return ImageLoaderMachO::findClosestSymbol((mach_header
*)fMachOData
, addr
, closestAddr
);
1524 #if PREBOUND_IMAGE_SUPPORT
1525 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext
& context
)
1527 // no way to back off a prebound compress image
1532 #if __arm__ || __x86_64__
1533 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub
, void** originalLazyPointerAddr
, const LinkContext
& context
)
1536 uint32_t* instructions
= (uint32_t*)stub
;
1537 // sanity check this is a stub we understand
1538 if ( (instructions
[0] != 0xe59fc004) || (instructions
[1] != 0xe08fc00c) || (instructions
[2] != 0xe59cf000) )
1541 void** lazyPointerAddr
= (void**)(instructions
[3] + (stub
+ 12));
1544 // sanity check this is a stub we understand
1545 if ( (stub
[0] != 0xFF) || (stub
[1] != 0x25) )
1547 int32_t ripOffset
= *((int32_t*)(&stub
[2]));
1548 void** lazyPointerAddr
= (void**)(ripOffset
+ stub
+ 6);
1551 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1552 if ( lazyPointerAddr
!= originalLazyPointerAddr
) {
1553 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1554 const ImageLoader
* lazyPointerImage
= context
.findImageContainingAddress(lazyPointerAddr
);
1555 if ( lazyPointerImage
!= NULL
)
1558 // copy newly re-bound lazy pointer value to shared lazy pointer
1559 *lazyPointerAddr
= *originalLazyPointerAddr
;
1561 if ( context
.verboseBind
)
1562 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1563 this->getShortName(), (long)lazyPointerAddr
, (long)*originalLazyPointerAddr
);
1569 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1570 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext
& context
)
1572 #if __arm__ || __x86_64__
1573 // find stubs and indirect symbol table
1574 const struct macho_section
* stubsSection
= NULL
;
1575 const dysymtab_command
* dynSymbolTable
= NULL
;
1576 const macho_header
* mh
= (macho_header
*)fMachOData
;
1577 const uint32_t cmd_count
= mh
->ncmds
;
1578 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1579 const struct load_command
* cmd
= cmds
;
1580 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1581 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1582 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1583 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1584 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1585 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1586 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1587 if ( type
== S_SYMBOL_STUBS
)
1588 stubsSection
= sect
;
1591 else if ( cmd
->cmd
== LC_DYSYMTAB
) {
1592 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1594 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1596 if ( dynSymbolTable
== NULL
)
1598 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1599 if ( stubsSection
== NULL
)
1601 const uint32_t stubsSize
= stubsSection
->reserved2
;
1602 const uint32_t stubsCount
= (uint32_t)(stubsSection
->size
/ stubsSize
);
1603 const uint32_t stubsIndirectTableOffset
= stubsSection
->reserved1
;
1604 if ( (stubsIndirectTableOffset
+stubsCount
) > dynSymbolTable
->nindirectsyms
)
1606 uint8_t* const stubsAddr
= (uint8_t*)(stubsSection
->addr
+ this->fSlide
);
1608 // for each lazy pointer section
1610 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1611 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1612 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1613 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1614 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1615 for (const struct macho_section
* lazyPointerSection
=sectionsStart
; lazyPointerSection
< sectionsEnd
; ++lazyPointerSection
) {
1616 const uint8_t type
= lazyPointerSection
->flags
& SECTION_TYPE
;
1617 if ( type
!= S_LAZY_SYMBOL_POINTERS
)
1619 const uint32_t lazyPointersCount
= (uint32_t)(lazyPointerSection
->size
/ sizeof(void*));
1620 const uint32_t lazyPointersIndirectTableOffset
= lazyPointerSection
->reserved1
;
1621 if ( (lazyPointersIndirectTableOffset
+lazyPointersCount
) > dynSymbolTable
->nindirectsyms
)
1623 void** const lazyPointersAddr
= (void**)(lazyPointerSection
->addr
+ this->fSlide
);
1624 // for each lazy pointer
1625 for(uint32_t lpIndex
=0; lpIndex
< lazyPointersCount
; ++lpIndex
) {
1626 const uint32_t lpSymbolIndex
= indirectTable
[lazyPointersIndirectTableOffset
+lpIndex
];
1627 // find matching stub and validate it uses this lazy pointer
1628 for(uint32_t stubIndex
=0; stubIndex
< stubsCount
; ++stubIndex
) {
1629 if ( indirectTable
[stubsIndirectTableOffset
+stubIndex
] == lpSymbolIndex
) {
1630 this->updateAlternateLazyPointer(stubsAddr
+stubIndex
*stubsSize
, &lazyPointersAddr
[lpIndex
], context
);
1638 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1645 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command
* encryptCmd
, const LinkContext
& context
)
1647 #if __arm__ || __arm64__
1648 if ( encryptCmd
== NULL
)
1650 const mach_header
* mh
= NULL
;
1651 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1652 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
1653 mh
= (mach_header
*)segActualLoadAddress(i
);
1657 void* start
= ((uint8_t*)mh
) + encryptCmd
->cryptoff
;
1658 size_t len
= encryptCmd
->cryptsize
;
1659 uint32_t cputype
= mh
->cputype
;
1660 uint32_t cpusubtype
= mh
->cpusubtype
;
1661 uint32_t cryptid
= encryptCmd
->cryptid
;
1662 if (context
.verboseMapping
) {
1663 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start
, (long)start
+len
);
1665 int result
= mremap_encrypted(start
, len
, cryptid
, cputype
, cpusubtype
);
1666 if ( result
!= 0 ) {
1667 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result
, errno
, this->getPath());