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 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
161 // don't do this on prebound images or if prefetching is disabled
162 if ( !context
.preFetchDisabled
&& !image
->isPrebindable()) {
163 image
->preFetchDATA(fd
, offsetInFat
, context
);
164 image
->markSequentialLINKEDIT(context
);
168 // ImageLoader::setMapped() can throw an exception to block loading of image
169 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
177 // create image by using cached mach-o file
178 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
,
179 const struct stat
& info
, unsigned int segCount
,
180 unsigned int libCount
, const LinkContext
& context
)
182 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
184 // record info about file
185 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
187 // remember this is from shared cache and cannot be unloaded
188 image
->fInSharedCache
= true;
189 image
->setNeverUnload();
190 image
->setSlide(slide
);
191 image
->disableCoverageCheck();
193 // segments already mapped in cache
194 if ( context
.verboseMapping
) {
195 dyld::log("dyld: Using shared cached for %s\n", path
);
196 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
197 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
201 image
->instantiateFinish(context
);
202 image
->setMapped(context
);
205 // ImageLoader::setMapped() can throw an exception to block loading of image
206 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
214 // create image by copying an in-memory mach-o file
215 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
216 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
218 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, moduleName
, segCount
, libCount
);
221 if ( mh
->filetype
== MH_EXECUTE
)
222 throw "can't load another MH_EXECUTE";
225 image
->mapSegments((const void*)mh
, len
, context
);
227 // for compatibility, never unload dylibs loaded from memory
228 image
->setNeverUnload();
230 image
->disableCoverageCheck();
232 // bundle loads need path copied
233 if ( moduleName
!= NULL
)
234 image
->setPath(moduleName
);
236 image
->instantiateFinish(context
);
237 image
->setMapped(context
);
240 // ImageLoader::setMapped() can throw an exception to block loading of image
241 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
250 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header
* mh
, const char* path
, unsigned int segCount
,
251 uint32_t segOffsets
[], unsigned int libCount
)
252 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fDyldInfo(NULL
)
256 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
258 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
264 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
265 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateStart(const macho_header
* mh
, const char* path
,
266 unsigned int segCount
, unsigned int libCount
)
268 size_t size
= sizeof(ImageLoaderMachOCompressed
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
269 ImageLoaderMachOCompressed
* allocatedSpace
= static_cast<ImageLoaderMachOCompressed
*>(malloc(size
));
270 if ( allocatedSpace
== NULL
)
271 throw "malloc failed";
272 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOCompressed
)));
273 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
274 return new (allocatedSpace
) ImageLoaderMachOCompressed(mh
, path
, segCount
, segOffsets
, libCount
);
278 // common code to finish initializing object
279 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext
& context
)
281 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
282 this->parseLoadCmds(context
);
285 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
287 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
)));
291 ImageLoader
* ImageLoaderMachOCompressed::libImage(unsigned int libIndex
) const
293 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
295 return (ImageLoader
*)(images
[libIndex
] & (-4));
298 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex
) const
300 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
301 // re-export flag is low bit
302 return ((images
[libIndex
] & 1) != 0);
305 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex
) const
307 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
308 // re-export flag is second bit
309 return ((images
[libIndex
] & 2) != 0);
313 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
, bool upward
)
315 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
316 uintptr_t value
= (uintptr_t)image
;
321 images
[libIndex
] = value
;
325 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext
& context
)
327 // mark that we are done with rebase and bind info
328 markLINKEDIT(context
, MADV_FREE
);
331 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext
& context
)
333 // mark the rebase and bind info and using sequential access
334 markLINKEDIT(context
, MADV_SEQUENTIAL
);
337 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext
& context
, int advise
)
339 // if not loaded at preferred address, mark rebase info
341 if ( (fSlide
!= 0) && (fDyldInfo
->rebase_size
!= 0) )
342 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
;
343 else if ( fDyldInfo
->bind_off
!= 0 )
344 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
;
346 return; // no binding info to prefetch
348 // end is at end of bind info
350 if ( fDyldInfo
->bind_off
!= 0 )
351 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
+ fDyldInfo
->bind_size
;
352 else if ( fDyldInfo
->rebase_off
!= 0 )
353 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
+ fDyldInfo
->rebase_size
;
358 // round to whole pages
359 start
= dyld_page_trunc(start
);
360 end
= dyld_page_round(end
);
362 // do nothing if only one page of rebase/bind info
363 if ( (end
-start
) <= dyld_page_size
)
366 // tell kernel about our access to these pages
367 madvise((void*)start
, end
-start
, advise
);
368 if ( context
.verboseMapping
) {
369 const char* adstr
= "sequential";
370 if ( advise
== MADV_FREE
)
372 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr
, start
, end
-1, this->getPath());
378 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext
& context
, uintptr_t addr
, uintptr_t slide
, uint8_t type
)
380 if ( context
.verboseRebase
) {
381 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr
, slide
);
383 //dyld::log("0x%08lX type=%d\n", addr, type);
384 uintptr_t* locationToFix
= (uintptr_t*)addr
;
386 case REBASE_TYPE_POINTER
:
387 *locationToFix
+= slide
;
389 case REBASE_TYPE_TEXT_ABSOLUTE32
:
390 *locationToFix
+= slide
;
393 dyld::throwf("bad rebase type %d", type
);
397 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
398 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
400 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
401 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
402 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
405 void ImageLoaderMachOCompressed::rebase(const LinkContext
& context
, uintptr_t slide
)
407 CRSetCrashLogMessage2(this->getPath());
408 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->rebase_off
;
409 const uint8_t* const end
= &start
[fDyldInfo
->rebase_size
];
410 const uint8_t* p
= start
;
414 int segmentIndex
= 0;
415 uintptr_t address
= segActualLoadAddress(0);
416 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
417 uintptr_t segmentEndAddress
= segActualEndAddress(0);
421 while ( !done
&& (p
< end
) ) {
422 uint8_t immediate
= *p
& REBASE_IMMEDIATE_MASK
;
423 uint8_t opcode
= *p
& REBASE_OPCODE_MASK
;
426 case REBASE_OPCODE_DONE
:
429 case REBASE_OPCODE_SET_TYPE_IMM
:
432 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
433 segmentIndex
= immediate
;
434 if ( segmentIndex
>= fSegmentsCount
)
435 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
436 segmentIndex
, fSegmentsCount
-1);
437 #if TEXT_RELOC_SUPPORT
438 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
440 if ( !segWriteable(segmentIndex
) )
442 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
443 segmentIndex
, segName(segmentIndex
));
444 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
445 segmentEndAddress
= segActualEndAddress(segmentIndex
);
446 address
= segmentStartAddress
+ read_uleb128(p
, end
);
448 case REBASE_OPCODE_ADD_ADDR_ULEB
:
449 address
+= read_uleb128(p
, end
);
451 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED
:
452 address
+= immediate
*sizeof(uintptr_t);
454 case REBASE_OPCODE_DO_REBASE_IMM_TIMES
:
455 for (int i
=0; i
< immediate
; ++i
) {
456 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
457 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
458 rebaseAt(context
, address
, slide
, type
);
459 address
+= sizeof(uintptr_t);
461 fgTotalRebaseFixups
+= immediate
;
463 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES
:
464 count
= read_uleb128(p
, end
);
465 for (uint32_t i
=0; i
< count
; ++i
) {
466 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
467 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
468 rebaseAt(context
, address
, slide
, type
);
469 address
+= sizeof(uintptr_t);
471 fgTotalRebaseFixups
+= count
;
473 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB
:
474 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
475 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
476 rebaseAt(context
, address
, slide
, type
);
477 address
+= read_uleb128(p
, end
) + sizeof(uintptr_t);
478 ++fgTotalRebaseFixups
;
480 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
:
481 count
= read_uleb128(p
, end
);
482 skip
= read_uleb128(p
, end
);
483 for (uint32_t i
=0; i
< count
; ++i
) {
484 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
485 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
486 rebaseAt(context
, address
, slide
, type
);
487 address
+= skip
+ sizeof(uintptr_t);
489 fgTotalRebaseFixups
+= count
;
492 dyld::throwf("bad rebase opcode %d", *p
);
496 catch (const char* msg
) {
497 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
501 CRSetCrashLogMessage2(NULL
);
504 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol
, const ImageLoader
** foundIn
) const
506 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
507 if ( fDyldInfo
->export_size
== 0 )
510 dyld::logBindings("%s: %s\n", this->getShortName(), symbol
);
512 ++ImageLoaderMachO::fgSymbolTrieSearchs
;
513 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
514 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
515 const uint8_t* foundNodeStart
= this->trieWalk(start
, end
, symbol
);
516 if ( foundNodeStart
!= NULL
) {
517 const uint8_t* p
= foundNodeStart
;
518 const uintptr_t flags
= read_uleb128(p
, end
);
519 // found match, return pointer to terminal part of node
520 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
521 // re-export from another dylib, lookup there
522 const uintptr_t ordinal
= read_uleb128(p
, end
);
523 const char* importedName
= (char*)p
;
524 if ( importedName
[0] == '\0' )
525 importedName
= symbol
;
526 if ( (ordinal
> 0) && (ordinal
<= libraryCount()) ) {
527 const ImageLoader
* reexportedFrom
= libImage((unsigned int)ordinal
-1);
528 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
529 const char* reExportLibPath
= libPath((unsigned int)ordinal
-1);
530 return reexportedFrom
->findExportedSymbol(importedName
, true, reExportLibPath
, foundIn
);
533 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
534 // ordinal, libraryCount(), symbol, this->getPath());
538 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
539 if ( foundIn
!= NULL
)
540 *foundIn
= (ImageLoader
*)this;
541 // return pointer to terminal part of node
542 return (Symbol
*)foundNodeStart
;
549 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr
) const
551 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
552 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
553 return ( (start
<= addr
) && (addr
< end
) );
557 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext
& context
, const Symbol
* symbol
, const ImageLoader
* requestor
, bool runResolver
) const
559 const uint8_t* exportNode
= (uint8_t*)symbol
;
560 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
561 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
562 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
563 throw "symbol is not in trie";
564 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
565 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
566 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
567 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
568 if ( runResolver
&& (flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) ) {
569 // this node has a stub and resolver, run the resolver to get target address
570 uintptr_t stub
= read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
; // skip over stub
571 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
572 uintptr_t interposedStub
= interposedAddress(context
, stub
, requestor
);
573 if ( interposedStub
!= stub
)
574 return interposedStub
;
575 // stub was not interposed, so run resolver
576 typedef uintptr_t (*ResolverProc
)(void);
577 ResolverProc resolver
= (ResolverProc
)(read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
);
578 uintptr_t result
= (*resolver
)();
579 if ( context
.verboseBind
)
580 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver
, result
);
583 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
584 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
585 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
586 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
587 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
588 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
589 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
590 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
591 return read_uleb128(exportNode
, exportTrieEnd
);
593 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
597 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
599 const uint8_t* exportNode
= (uint8_t*)symbol
;
600 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
601 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
602 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
603 throw "symbol is not in trie";
604 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
605 return ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
);
609 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol
* symbol
) const
611 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
614 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
616 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
619 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index
) const
621 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
624 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
626 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
629 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index
) const
631 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
634 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol
* symbol
) const
636 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
641 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
642 bool runResolver
, const ImageLoader
** foundIn
)
645 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
646 if ( *foundIn
!= this )
647 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
648 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
650 // if a bundle is loaded privately the above will not find its exports
651 if ( this->isBundle() && this->hasHiddenExports() ) {
652 // look in self for needed symbol
653 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
655 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
658 // definition can't be found anywhere, ok because it is weak, just return 0
661 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "flat namespace");
665 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext
& context
, const char* symbolName
, const ImageLoader
* definedInImage
,
666 const ImageLoader
* requestorImage
, unsigned requestorOrdinalOfDef
, bool weak_import
, bool runResolver
,
667 const ImageLoader
** foundIn
)
671 if ( definedInImage
->findExportedSymbolAddress(context
, symbolName
, requestorImage
, requestorOrdinalOfDef
, runResolver
, foundIn
, &address
) )
675 // definition can't be found anywhere, ok because it is weak, just return 0
679 // nowhere to be found, check if maybe this image is too new for this OS
680 char versMismatch
[256];
681 versMismatch
[0] = '\0';
682 uint32_t imageMinOS
= this->minOSVersion();
683 // dyld is always built for the current OS, so we can get the current OS version
684 // from the load command in dyld itself.
685 extern const mach_header __dso_handle
;
686 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion(&__dso_handle
);
687 if ( imageMinOS
> dyldMinOS
) {
688 #if __MAC_OS_X_VERSION_MIN_REQUIRED
689 const char* msg
= dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
691 const char* msg
= dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
693 strcpy(versMismatch
, msg
);
696 throwSymbolNotFound(context
, symbolName
, this->getPath(), versMismatch
, definedInImage
->getPath());
700 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext
& context
, const char* symbolName
,
701 uint8_t symboFlags
, long libraryOrdinal
, const ImageLoader
** targetImage
,
702 LastLookup
* last
, bool runResolver
)
706 // only clients that benefit from caching last lookup pass in a LastLookup struct
707 if ( last
!= NULL
) {
708 if ( (last
->ordinal
== libraryOrdinal
)
709 && (last
->flags
== symboFlags
)
710 && (last
->name
== symbolName
) ) {
711 *targetImage
= last
->foundIn
;
716 bool weak_import
= (symboFlags
& BIND_SYMBOL_FLAGS_WEAK_IMPORT
);
717 uintptr_t symbolAddress
;
718 if ( context
.bindFlat
|| (libraryOrdinal
== BIND_SPECIAL_DYLIB_FLAT_LOOKUP
) ) {
719 symbolAddress
= this->resolveFlat(context
, symbolName
, weak_import
, runResolver
, targetImage
);
722 if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
) {
723 *targetImage
= context
.mainExecutable
;
725 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_SELF
) {
728 else if ( libraryOrdinal
<= 0 ) {
729 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
730 libraryOrdinal
, symbolName
, this->getPath());
732 else if ( (unsigned)libraryOrdinal
<= libraryCount() ) {
733 *targetImage
= libImage((unsigned int)libraryOrdinal
-1);
736 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
737 libraryOrdinal
, libraryCount(), symbolName
, this->getPath());
739 if ( *targetImage
== NULL
) {
741 // if target library not loaded and reference is weak or library is weak return 0
745 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
746 symbolName
, this->getPath(), libraryOrdinal
);
750 symbolAddress
= resolveTwolevel(context
, symbolName
, *targetImage
, this, (unsigned)libraryOrdinal
, weak_import
, runResolver
, targetImage
);
754 // save off lookup results if client wants
755 if ( last
!= NULL
) {
756 last
->ordinal
= libraryOrdinal
;
757 last
->flags
= symboFlags
;
758 last
->name
= symbolName
;
759 last
->foundIn
= *targetImage
;
760 last
->result
= symbolAddress
;
763 return symbolAddress
;
766 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
767 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
, const char* msg
,
768 LastLookup
* last
, bool runResolver
)
770 const ImageLoader
* targetImage
;
771 uintptr_t symbolAddress
;
774 symbolAddress
= this->resolve(context
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
777 return this->bindLocation(context
, addr
, symbolAddress
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, msg
);
781 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
782 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
784 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
785 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
786 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
790 void ImageLoaderMachOCompressed::doBind(const LinkContext
& context
, bool forceLazysBound
)
792 CRSetCrashLogMessage2(this->getPath());
794 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
795 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
796 if ( this->usablePrebinding(context
) ) {
797 // don't need to bind
800 uint64_t t0
= mach_absolute_time();
802 #if TEXT_RELOC_SUPPORT
803 // if there are __TEXT fixups, temporarily make __TEXT writable
804 if ( fTextSegmentBinds
)
805 this->makeTextSegmentWritable(context
, true);
808 // run through all binding opcodes
809 eachBind(context
, &ImageLoaderMachOCompressed::bindAt
);
811 #if TEXT_RELOC_SUPPORT
812 // if there were __TEXT fixups, restore write protection
813 if ( fTextSegmentBinds
)
814 this->makeTextSegmentWritable(context
, false);
817 // if this image is in the shared cache, but depends on something no longer in the shared cache,
818 // there is no way to reset the lazy pointers, so force bind them now
819 if ( forceLazysBound
|| fInSharedCache
)
820 this->doBindJustLazies(context
);
822 // this image is in cache, but something below it is not. If
823 // this image has lazy pointer to a resolver function, then
824 // the stub may have been altered to point to a shared lazy pointer.
825 if ( fInSharedCache
)
826 this->updateOptimizedLazyPointers(context
);
828 // tell kernel we are done with chunks of LINKEDIT
829 if ( !context
.preFetchDisabled
)
830 this->markFreeLINKEDIT(context
);
832 uint64_t t1
= mach_absolute_time();
833 ImageLoader::fgTotalRebindCacheTime
+= (t1
-t0
);
836 // set up dyld entry points in image
837 // do last so flat main executables will have __dyld or __program_vars set up
838 this->setupLazyPointerHandler(context
);
839 CRSetCrashLogMessage2(NULL
);
843 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext
& context
)
845 eachLazyBind(context
, &ImageLoaderMachOCompressed::bindAt
);
848 #if __arm__ || __arm64__
849 int ImageLoaderMachOCompressed::vmAccountingSetSuspended(bool suspend
, const LinkContext
& context
)
851 if ( context
.verboseBind
)
852 dyld::log("vm.footprint_suspend=%d\n", suspend
);
853 int newValue
= suspend
? 1 : 0;
855 size_t newlen
= sizeof(newValue
);
856 size_t oldlen
= sizeof(oldValue
);
857 return sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
861 void ImageLoaderMachOCompressed::eachBind(const LinkContext
& context
, bind_handler handler
)
863 #if __arm__ || __arm64__
864 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
865 if ( !sVmAccountingDisabled
) {
866 if ( fInSharedCache
) {
867 if ( !sVmAccountingSuspended
) {
868 int ret
= vmAccountingSetSuspended(true, context
);
869 if ( context
.verboseBind
&& (ret
!= 0) )
870 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
872 sVmAccountingSuspended
= true;
874 sVmAccountingDisabled
= true;
877 else if ( sVmAccountingSuspended
) {
878 int ret
= vmAccountingSetSuspended(false, context
);
880 sVmAccountingSuspended
= false;
881 else if ( errno
== ENOENT
)
882 sVmAccountingDisabled
= true;
889 int segmentIndex
= -1;
890 uintptr_t address
= segActualLoadAddress(0);
891 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
892 uintptr_t segmentEndAddress
= segActualEndAddress(0);
893 const char* symbolName
= NULL
;
894 uint8_t symboFlags
= 0;
895 bool libraryOrdinalSet
= false;
896 long libraryOrdinal
= 0;
901 LastLookup last
= { 0, 0, NULL
, 0, NULL
};
902 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->bind_off
;
903 const uint8_t* const end
= &start
[fDyldInfo
->bind_size
];
904 const uint8_t* p
= start
;
906 while ( !done
&& (p
< end
) ) {
907 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
908 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
911 case BIND_OPCODE_DONE
:
914 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
915 libraryOrdinal
= immediate
;
916 libraryOrdinalSet
= true;
918 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
919 libraryOrdinal
= read_uleb128(p
, end
);
920 libraryOrdinalSet
= true;
922 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
923 // the special ordinals are negative numbers
924 if ( immediate
== 0 )
927 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
928 libraryOrdinal
= signExtended
;
930 libraryOrdinalSet
= true;
932 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
933 symbolName
= (char*)p
;
934 symboFlags
= immediate
;
939 case BIND_OPCODE_SET_TYPE_IMM
:
942 case BIND_OPCODE_SET_ADDEND_SLEB
:
943 addend
= read_sleb128(p
, end
);
945 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
946 segmentIndex
= immediate
;
947 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
948 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
949 segmentIndex
, fSegmentsCount
-1);
950 #if TEXT_RELOC_SUPPORT
951 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
953 if ( !segWriteable(segmentIndex
) )
955 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
956 segOffset
= read_uleb128(p
, end
);
957 if ( segOffset
> segSize(segmentIndex
) )
958 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
959 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
960 address
= segmentStartAddress
+ segOffset
;
961 segmentEndAddress
= segActualEndAddress(segmentIndex
);
963 case BIND_OPCODE_ADD_ADDR_ULEB
:
964 address
+= read_uleb128(p
, end
);
966 case BIND_OPCODE_DO_BIND
:
967 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
968 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
969 if ( symbolName
== NULL
)
970 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
971 if ( segmentIndex
== -1 )
972 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
973 if ( !libraryOrdinalSet
)
974 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
975 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
976 address
+= sizeof(intptr_t);
978 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
979 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
980 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
981 if ( symbolName
== NULL
)
982 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
983 if ( segmentIndex
== -1 )
984 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
985 if ( !libraryOrdinalSet
)
986 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
987 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
988 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
990 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
991 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
992 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
993 if ( symbolName
== NULL
)
994 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
995 if ( segmentIndex
== -1 )
996 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
997 if ( !libraryOrdinalSet
)
998 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
999 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
1000 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1002 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1003 if ( symbolName
== NULL
)
1004 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1005 if ( segmentIndex
== -1 )
1006 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1007 count
= read_uleb128(p
, end
);
1008 if ( !libraryOrdinalSet
)
1009 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1010 skip
= read_uleb128(p
, end
);
1011 for (uint32_t i
=0; i
< count
; ++i
) {
1012 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1013 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1014 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
1015 address
+= skip
+ sizeof(intptr_t);
1019 dyld::throwf("bad bind opcode %d in bind info", *p
);
1023 catch (const char* msg
) {
1024 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1030 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext
& context
, bind_handler handler
)
1033 uint8_t type
= BIND_TYPE_POINTER
;
1034 int segmentIndex
= -1;
1035 uintptr_t address
= segActualLoadAddress(0);
1036 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1037 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1038 uintptr_t segOffset
;
1039 const char* symbolName
= NULL
;
1040 uint8_t symboFlags
= 0;
1041 long libraryOrdinal
= 0;
1042 intptr_t addend
= 0;
1043 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1044 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1045 const uint8_t* p
= start
;
1047 while ( !done
&& (p
< end
) ) {
1048 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1049 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1052 case BIND_OPCODE_DONE
:
1053 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1055 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1056 libraryOrdinal
= immediate
;
1058 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1059 libraryOrdinal
= read_uleb128(p
, end
);
1061 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1062 // the special ordinals are negative numbers
1063 if ( immediate
== 0 )
1066 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1067 libraryOrdinal
= signExtended
;
1070 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1071 symbolName
= (char*)p
;
1072 symboFlags
= immediate
;
1077 case BIND_OPCODE_SET_TYPE_IMM
:
1080 case BIND_OPCODE_SET_ADDEND_SLEB
:
1081 addend
= read_sleb128(p
, end
);
1083 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1084 segmentIndex
= immediate
;
1085 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1086 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1087 segmentIndex
, fSegmentsCount
-1);
1088 if ( !segWriteable(segmentIndex
) )
1089 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1090 segOffset
= read_uleb128(p
, end
);
1091 if ( segOffset
> segSize(segmentIndex
) )
1092 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1093 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1094 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1095 address
= segmentStartAddress
+ segOffset
;
1097 case BIND_OPCODE_ADD_ADDR_ULEB
:
1098 address
+= read_uleb128(p
, end
);
1100 case BIND_OPCODE_DO_BIND
:
1101 if ( segmentIndex
== -1 )
1102 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1103 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1104 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1105 if ( symbolName
== NULL
)
1106 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1107 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "forced lazy ", NULL
, false);
1108 address
+= sizeof(intptr_t);
1110 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1111 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1112 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1114 dyld::throwf("bad lazy bind opcode %d", *p
);
1119 catch (const char* msg
) {
1120 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1126 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1127 // the classic lazy loader is used even when running on 10.6
1128 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1130 // only works with compressed LINKEDIT if classic symbol table is also present
1131 const macho_nlist
* symbolTable
= NULL
;
1132 const char* symbolTableStrings
= NULL
;
1133 const dysymtab_command
* dynSymbolTable
= NULL
;
1134 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1135 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1136 const struct load_command
* cmd
= cmds
;
1137 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1141 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1142 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1143 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1147 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1150 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1152 // no symbol table => no lookup by address
1153 if ( (symbolTable
== NULL
) || (dynSymbolTable
== NULL
) )
1154 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer
, this->getPath());
1156 // scan for all lazy-pointer sections
1157 const bool twoLevel
= this->usesTwoLevelNameSpace();
1158 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1160 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1162 case LC_SEGMENT_COMMAND
:
1164 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1165 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1166 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1167 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1168 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1169 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1170 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1171 const size_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1172 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1173 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1174 const uint32_t indirectTableOffset
= sect
->reserved1
;
1175 const size_t lazyIndex
= lazyPointer
- symbolPointers
;
1176 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1179 if ( (symbolIndex
!= INDIRECT_SYMBOL_ABS
) && (symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) ) {
1180 const macho_nlist
* symbol
= &symbolTable
[symbolIndex
];
1181 const char* symbolName
= &symbolTableStrings
[symbol
->n_un
.n_strx
];
1182 int libraryOrdinal
= GET_LIBRARY_ORDINAL(symbol
->n_desc
);
1183 if ( !twoLevel
|| context
.bindFlat
)
1184 libraryOrdinal
= BIND_SPECIAL_DYLIB_FLAT_LOOKUP
;
1185 uintptr_t ptrToBind
= (uintptr_t)lazyPointer
;
1186 uintptr_t symbolAddr
= bindAt(context
, ptrToBind
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
);
1187 ++fgTotalLazyBindFixups
;
1194 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1196 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1201 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
,
1202 void (*lock
)(), void (*unlock
)())
1204 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1205 if ( this->usesTwoLevelNameSpace() ) {
1206 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1209 // acquire dyld global lock
1214 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1215 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1217 uintptr_t segOffset
;
1219 const char* symbolName
;
1223 if ( ! getLazyBindingInfo(lazyBindingInfoOffset
, start
, end
, &segIndex
, &segOffset
, &libraryOrdinal
, &symbolName
, &doneAfterBind
) )
1224 dyld::throwf("bad lazy bind info");
1226 if ( segIndex
>= fSegmentsCount
)
1227 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1228 segIndex
, fSegmentsCount
-1);
1229 if ( segOffset
> segSize(segIndex
) )
1230 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segIndex
));
1231 uintptr_t address
= segActualLoadAddress(segIndex
) + segOffset
;
1232 result
= this->bindAt(context
, address
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
, true);
1233 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1234 } while (!doneAfterBind
&& !context
.strictMachORequired
);
1236 if ( !this->usesTwoLevelNameSpace() ) {
1237 // release dyld global lock
1238 if ( unlock
!= NULL
)
1244 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
, unsigned)
1247 it
.symbolName
= " ";
1248 it
.loadOrder
= loadOrder
;
1249 it
.weakSymbol
= false;
1250 it
.symbolMatches
= false;
1253 it
.endIndex
= this->fDyldInfo
->weak_bind_size
;
1260 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator
& it
)
1265 if ( this->fDyldInfo
->weak_bind_size
== 0 ) {
1266 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1268 it
.symbolName
= "~~~";
1271 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1272 const uint8_t* p
= start
+ it
.curIndex
;
1273 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1276 uintptr_t segOffset
;
1278 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1279 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1282 case BIND_OPCODE_DONE
:
1284 it
.curIndex
= p
- start
;
1285 it
.symbolName
= "~~~"; // sorts to end
1287 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1288 it
.symbolName
= (char*)p
;
1289 it
.weakSymbol
= ((immediate
& BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION
) == 0);
1290 it
.symbolMatches
= false;
1294 it
.curIndex
= p
- start
;
1296 case BIND_OPCODE_SET_TYPE_IMM
:
1297 it
.type
= immediate
;
1299 case BIND_OPCODE_SET_ADDEND_SLEB
:
1300 it
.addend
= read_sleb128(p
, end
);
1302 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1303 if ( immediate
>= fSegmentsCount
)
1304 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1305 immediate
, fSegmentsCount
-1);
1307 // <rdar://problem/23138428> iOS app compatibility
1308 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1309 #elif TEXT_RELOC_SUPPORT
1310 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1311 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1312 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1314 if ( !segWriteable(immediate
) )
1316 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1317 segOffset
= read_uleb128(p
, end
);
1318 if ( segOffset
> segSize(immediate
) )
1319 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1320 it
.address
= segActualLoadAddress(immediate
) + segOffset
;
1322 case BIND_OPCODE_ADD_ADDR_ULEB
:
1323 it
.address
+= read_uleb128(p
, end
);
1325 case BIND_OPCODE_DO_BIND
:
1326 it
.address
+= sizeof(intptr_t);
1328 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1329 it
.address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1331 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1332 it
.address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1334 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1335 count
= read_uleb128(p
, end
);
1336 skip
= read_uleb128(p
, end
);
1337 for (uint32_t i
=0; i
< count
; ++i
) {
1338 it
.address
+= skip
+ sizeof(intptr_t);
1342 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p
, (int)(p
-start
), this->getPath());
1345 /// hmmm, BIND_OPCODE_DONE is missing...
1347 it
.symbolName
= "~~~";
1348 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1352 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1354 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1355 const ImageLoader
* foundIn
= NULL
;
1356 const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(it
.symbolName
, &foundIn
);
1357 if ( sym
!= NULL
) {
1358 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1359 return foundIn
->getExportedSymbolAddress(sym
, context
, this);
1365 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, unsigned targetIndex
, const LinkContext
& context
)
1367 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1368 if ( this->getState() < dyld_image_state_bound
)
1371 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1372 const uint8_t* p
= start
+ it
.curIndex
;
1373 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1375 uint8_t type
= it
.type
;
1376 uintptr_t address
= it
.address
;
1377 const char* symbolName
= it
.symbolName
;
1378 intptr_t addend
= it
.addend
;
1381 uintptr_t segOffset
;
1383 bool boundSomething
= false;
1384 while ( !done
&& (p
< end
) ) {
1385 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1386 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1389 case BIND_OPCODE_DONE
:
1392 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1395 case BIND_OPCODE_SET_TYPE_IMM
:
1398 case BIND_OPCODE_SET_ADDEND_SLEB
:
1399 addend
= read_sleb128(p
, end
);
1401 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1402 if ( immediate
>= fSegmentsCount
)
1403 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1404 immediate
, fSegmentsCount
-1);
1406 // <rdar://problem/23138428> iOS app compatibility
1407 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1408 #elif TEXT_RELOC_SUPPORT
1409 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1410 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1411 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1413 if ( !segWriteable(immediate
) )
1415 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1416 segOffset
= read_uleb128(p
, end
);
1417 if ( segOffset
> segSize(immediate
) )
1418 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1419 address
= segActualLoadAddress(immediate
) + segOffset
;
1421 case BIND_OPCODE_ADD_ADDR_ULEB
:
1422 address
+= read_uleb128(p
, end
);
1424 case BIND_OPCODE_DO_BIND
:
1425 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1426 boundSomething
= true;
1427 address
+= sizeof(intptr_t);
1429 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1430 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1431 boundSomething
= true;
1432 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1434 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1435 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1436 boundSomething
= true;
1437 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1439 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1440 count
= read_uleb128(p
, end
);
1441 skip
= read_uleb128(p
, end
);
1442 for (uint32_t i
=0; i
< count
; ++i
) {
1443 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1444 boundSomething
= true;
1445 address
+= skip
+ sizeof(intptr_t);
1449 dyld::throwf("bad bind opcode %d in weak binding info", *p
);
1452 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1453 if ( boundSomething
&& (targetImage
!= this) )
1454 context
.addDynamicReference(this, targetImage
);
1457 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char*,
1458 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1460 if ( type
== BIND_TYPE_POINTER
) {
1461 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1462 uintptr_t curValue
= *fixupLocation
;
1463 uintptr_t newValue
= interposedAddress(context
, curValue
, this);
1464 if ( newValue
!= curValue
) {
1465 *fixupLocation
= newValue
;
1471 void ImageLoaderMachOCompressed::doInterpose(const LinkContext
& context
)
1473 if ( context
.verboseInterposing
)
1474 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples
.size(), this->getPath());
1476 // update prebound symbols
1477 eachBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1478 eachLazyBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1482 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
1483 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1485 if ( type
== BIND_TYPE_POINTER
) {
1486 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1487 uintptr_t value
= *fixupLocation
;
1488 // don't apply interposing to table entries.
1489 if ( (context
.dynamicInterposeArray
<= (void*)addr
) && ((void*)addr
< &context
.dynamicInterposeArray
[context
.dynamicInterposeCount
]) )
1491 for(size_t i
=0; i
< context
.dynamicInterposeCount
; ++i
) {
1492 if ( value
== (uintptr_t)context
.dynamicInterposeArray
[i
].replacee
) {
1493 if ( context
.verboseInterposing
) {
1494 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1495 fixupLocation
, context
.dynamicInterposeArray
[i
].replacee
, context
.dynamicInterposeArray
[i
].replacement
, this->getPath());
1497 *fixupLocation
= (uintptr_t)context
.dynamicInterposeArray
[i
].replacement
;
1504 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext
& context
)
1506 if ( context
.verboseInterposing
)
1507 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context
.dynamicInterposeCount
, this->getPath());
1509 // update already bound references to symbols
1510 eachBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1511 eachLazyBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1514 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1516 return ImageLoaderMachO::findClosestSymbol((mach_header
*)fMachOData
, addr
, closestAddr
);
1520 #if PREBOUND_IMAGE_SUPPORT
1521 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext
& context
)
1523 // no way to back off a prebound compress image
1528 #if __arm__ || __x86_64__
1529 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub
, void** originalLazyPointerAddr
, const LinkContext
& context
)
1532 uint32_t* instructions
= (uint32_t*)stub
;
1533 // sanity check this is a stub we understand
1534 if ( (instructions
[0] != 0xe59fc004) || (instructions
[1] != 0xe08fc00c) || (instructions
[2] != 0xe59cf000) )
1537 void** lazyPointerAddr
= (void**)(instructions
[3] + (stub
+ 12));
1540 // sanity check this is a stub we understand
1541 if ( (stub
[0] != 0xFF) || (stub
[1] != 0x25) )
1543 int32_t ripOffset
= *((int32_t*)(&stub
[2]));
1544 void** lazyPointerAddr
= (void**)(ripOffset
+ stub
+ 6);
1547 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1548 if ( lazyPointerAddr
!= originalLazyPointerAddr
) {
1549 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1550 const ImageLoader
* lazyPointerImage
= context
.findImageContainingAddress(lazyPointerAddr
);
1551 if ( lazyPointerImage
!= NULL
)
1554 // copy newly re-bound lazy pointer value to shared lazy pointer
1555 *lazyPointerAddr
= *originalLazyPointerAddr
;
1557 if ( context
.verboseBind
)
1558 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1559 this->getShortName(), (long)lazyPointerAddr
, (long)*originalLazyPointerAddr
);
1565 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1566 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext
& context
)
1568 #if __arm__ || __x86_64__
1569 // find stubs and indirect symbol table
1570 const struct macho_section
* stubsSection
= NULL
;
1571 const dysymtab_command
* dynSymbolTable
= NULL
;
1572 const macho_header
* mh
= (macho_header
*)fMachOData
;
1573 const uint32_t cmd_count
= mh
->ncmds
;
1574 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1575 const struct load_command
* cmd
= cmds
;
1576 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1577 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1578 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1579 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1580 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1581 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1582 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1583 if ( type
== S_SYMBOL_STUBS
)
1584 stubsSection
= sect
;
1587 else if ( cmd
->cmd
== LC_DYSYMTAB
) {
1588 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1590 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1592 if ( dynSymbolTable
== NULL
)
1594 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1595 if ( stubsSection
== NULL
)
1597 const uint32_t stubsSize
= stubsSection
->reserved2
;
1598 const uint32_t stubsCount
= (uint32_t)(stubsSection
->size
/ stubsSize
);
1599 const uint32_t stubsIndirectTableOffset
= stubsSection
->reserved1
;
1600 if ( (stubsIndirectTableOffset
+stubsCount
) > dynSymbolTable
->nindirectsyms
)
1602 uint8_t* const stubsAddr
= (uint8_t*)(stubsSection
->addr
+ this->fSlide
);
1604 // for each lazy pointer section
1606 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1607 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1608 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1609 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1610 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1611 for (const struct macho_section
* lazyPointerSection
=sectionsStart
; lazyPointerSection
< sectionsEnd
; ++lazyPointerSection
) {
1612 const uint8_t type
= lazyPointerSection
->flags
& SECTION_TYPE
;
1613 if ( type
!= S_LAZY_SYMBOL_POINTERS
)
1615 const uint32_t lazyPointersCount
= (uint32_t)(lazyPointerSection
->size
/ sizeof(void*));
1616 const uint32_t lazyPointersIndirectTableOffset
= lazyPointerSection
->reserved1
;
1617 if ( (lazyPointersIndirectTableOffset
+lazyPointersCount
) > dynSymbolTable
->nindirectsyms
)
1619 void** const lazyPointersAddr
= (void**)(lazyPointerSection
->addr
+ this->fSlide
);
1620 // for each lazy pointer
1621 for(uint32_t lpIndex
=0; lpIndex
< lazyPointersCount
; ++lpIndex
) {
1622 const uint32_t lpSymbolIndex
= indirectTable
[lazyPointersIndirectTableOffset
+lpIndex
];
1623 // find matching stub and validate it uses this lazy pointer
1624 for(uint32_t stubIndex
=0; stubIndex
< stubsCount
; ++stubIndex
) {
1625 if ( indirectTable
[stubsIndirectTableOffset
+stubIndex
] == lpSymbolIndex
) {
1626 this->updateAlternateLazyPointer(stubsAddr
+stubIndex
*stubsSize
, &lazyPointersAddr
[lpIndex
], context
);
1634 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1641 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command
* encryptCmd
, const LinkContext
& context
)
1643 #if __arm__ || __arm64__
1644 if ( encryptCmd
== NULL
)
1646 const mach_header
* mh
= NULL
;
1647 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1648 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
1649 mh
= (mach_header
*)segActualLoadAddress(i
);
1653 void* start
= ((uint8_t*)mh
) + encryptCmd
->cryptoff
;
1654 size_t len
= encryptCmd
->cryptsize
;
1655 uint32_t cputype
= mh
->cputype
;
1656 uint32_t cpusubtype
= mh
->cpusubtype
;
1657 uint32_t cryptid
= encryptCmd
->cryptid
;
1658 if (context
.verboseMapping
) {
1659 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start
, (long)start
+len
);
1661 int result
= mremap_encrypted(start
, len
, cryptid
, cputype
, cpusubtype
);
1662 if ( result
!= 0 ) {
1663 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result
, errno
, this->getPath());