1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2008 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
26 #if __arm__ || __arm64__
27 #include <System/sys/mman.h>
34 #include <sys/types.h>
35 #include <sys/fcntl.h>
37 #include <sys/param.h>
38 #include <mach/mach.h>
39 #include <mach/thread_status.h>
40 #include <mach-o/loader.h>
41 #include "ImageLoaderMachOCompressed.h"
42 #include "mach-o/dyld_images.h"
46 #ifndef EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
47 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
51 #ifndef BIND_OPCODE_THREADED
52 #define BIND_OPCODE_THREADED 0xD0
55 #ifndef BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB
56 #define BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB 0x00
59 #ifndef BIND_SUBOPCODE_THREADED_APPLY
60 #define BIND_SUBOPCODE_THREADED_APPLY 0x01
64 #ifndef BIND_SPECIAL_DYLIB_WEAK_LOOKUP
65 #define BIND_SPECIAL_DYLIB_WEAK_LOOKUP -3
68 #ifndef CPU_SUBTYPE_ARM64_E
69 #define CPU_SUBTYPE_ARM64_E 2
72 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
75 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
76 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
77 struct macho_segment_command
: public segment_command_64
{};
78 struct macho_section
: public section_64
{};
79 struct macho_routines_command
: public routines_command_64
{};
82 #define LC_SEGMENT_COMMAND LC_SEGMENT
83 #define LC_ROUTINES_COMMAND LC_ROUTINES
84 struct macho_segment_command
: public segment_command
{};
85 struct macho_section
: public section
{};
86 struct macho_routines_command
: public routines_command
{};
91 // create image for main executable
92 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
,
93 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
95 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
97 // set slide for PIE programs
98 image
->setSlide(slide
);
100 // for PIE record end of program, to know where to start loading dylibs
102 fgNextPIEDylibAddress
= (uintptr_t)image
->getEnd();
104 image
->disableCoverageCheck();
105 image
->instantiateFinish(context
);
106 image
->setMapped(context
);
108 if ( context
.verboseMapping
) {
109 dyld::log("dyld: Main executable mapped %s\n", path
);
110 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
111 const char* name
= image
->segName(i
);
112 if ( (strcmp(name
, "__PAGEZERO") == 0) || (strcmp(name
, "__UNIXSTACK") == 0) )
113 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segPreferredLoadAddress(i
), image
->segPreferredLoadAddress(i
)+image
->segSize(i
));
115 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
122 // create image by mapping in a mach-o file
123 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromFile(const char* path
, int fd
, const uint8_t* fileData
, size_t lenFileData
,
124 uint64_t offsetInFat
, uint64_t lenInFat
, const struct stat
& info
,
125 unsigned int segCount
, unsigned int libCount
,
126 const struct linkedit_data_command
* codeSigCmd
,
127 const struct encryption_info_command
* encryptCmd
,
128 const LinkContext
& context
)
130 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart((macho_header
*)fileData
, path
, segCount
, libCount
);
133 // record info about file
134 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
136 // if this image is code signed, let kernel validate signature before mapping any pages from image
137 image
->loadCodeSignature(codeSigCmd
, fd
, offsetInFat
, context
);
139 // Validate that first data we read with pread actually matches with code signature
140 image
->validateFirstPages(codeSigCmd
, fd
, fileData
, lenFileData
, offsetInFat
, context
);
143 image
->mapSegments(fd
, offsetInFat
, lenInFat
, info
.st_size
, context
);
145 // if framework is FairPlay encrypted, register with kernel
146 image
->registerEncryption(encryptCmd
, context
);
148 // probe to see if code signed correctly
149 image
->crashIfInvalidCodeSignature();
151 // finish construction
152 image
->instantiateFinish(context
);
154 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
155 const char* installName
= image
->getInstallPath();
156 if ( (installName
!= NULL
) && (strcmp(installName
, path
) == 0) && (path
[0] == '/') )
157 image
->setPathUnowned(installName
);
158 #if __MAC_OS_X_VERSION_MIN_REQUIRED
159 // <rdar://problem/6563887> app crashes when libSystem cannot be found
160 else if ( (installName
!= NULL
) && (strcmp(path
, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName
, "/usr/lib/libSystem.B.dylib") == 0) )
161 image
->setPathUnowned("/usr/lib/libSystem.B.dylib");
163 else if ( (path
[0] != '/') || (strstr(path
, "../") != NULL
) ) {
164 // rdar://problem/10733082 Fix up @rpath based paths during introspection
165 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
166 char realPath
[MAXPATHLEN
];
167 if ( fcntl(fd
, F_GETPATH
, realPath
) == 0 )
168 image
->setPaths(path
, realPath
);
170 image
->setPath(path
);
173 image
->setPath(path
);
175 // make sure path is stable before recording in dyld_all_image_infos
176 image
->setMapped(context
);
178 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
179 // don't do this on prebound images or if prefetching is disabled
180 if ( !context
.preFetchDisabled
&& !image
->isPrebindable()) {
181 image
->preFetchDATA(fd
, offsetInFat
, context
);
182 image
->markSequentialLINKEDIT(context
);
186 // ImageLoader::setMapped() can throw an exception to block loading of image
187 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
195 // create image by using cached mach-o file
196 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
,
197 const struct stat
& info
, unsigned int segCount
,
198 unsigned int libCount
, const LinkContext
& context
)
200 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
202 // record info about file
203 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
205 // remember this is from shared cache and cannot be unloaded
206 image
->fInSharedCache
= true;
207 image
->setNeverUnload();
208 image
->setSlide(slide
);
209 image
->disableCoverageCheck();
211 // segments already mapped in cache
212 if ( context
.verboseMapping
) {
213 dyld::log("dyld: Using shared cached for %s\n", path
);
214 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
215 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
219 image
->instantiateFinish(context
);
220 image
->setMapped(context
);
223 // ImageLoader::setMapped() can throw an exception to block loading of image
224 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
232 // create image by copying an in-memory mach-o file
233 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
234 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
236 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, moduleName
, segCount
, libCount
);
239 if ( mh
->filetype
== MH_EXECUTE
)
240 throw "can't load another MH_EXECUTE";
243 image
->mapSegments((const void*)mh
, len
, context
);
245 // for compatibility, never unload dylibs loaded from memory
246 image
->setNeverUnload();
248 image
->disableCoverageCheck();
250 // bundle loads need path copied
251 if ( moduleName
!= NULL
)
252 image
->setPath(moduleName
);
254 image
->instantiateFinish(context
);
255 image
->setMapped(context
);
258 // ImageLoader::setMapped() can throw an exception to block loading of image
259 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
268 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header
* mh
, const char* path
, unsigned int segCount
,
269 uint32_t segOffsets
[], unsigned int libCount
)
270 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fDyldInfo(NULL
)
274 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
276 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
282 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
283 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateStart(const macho_header
* mh
, const char* path
,
284 unsigned int segCount
, unsigned int libCount
)
286 size_t size
= sizeof(ImageLoaderMachOCompressed
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
287 ImageLoaderMachOCompressed
* allocatedSpace
= static_cast<ImageLoaderMachOCompressed
*>(malloc(size
));
288 if ( allocatedSpace
== NULL
)
289 throw "malloc failed";
290 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOCompressed
)));
291 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
292 return new (allocatedSpace
) ImageLoaderMachOCompressed(mh
, path
, segCount
, segOffsets
, libCount
);
296 // common code to finish initializing object
297 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext
& context
)
299 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
300 this->parseLoadCmds(context
);
303 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
305 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
)));
309 ImageLoader
* ImageLoaderMachOCompressed::libImage(unsigned int libIndex
) const
311 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
313 return (ImageLoader
*)(images
[libIndex
] & (-4));
316 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex
) const
318 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
319 // re-export flag is low bit
320 return ((images
[libIndex
] & 1) != 0);
323 bool ImageLoaderMachOCompressed::libIsUpward(unsigned int libIndex
) const
325 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
326 // re-export flag is second bit
327 return ((images
[libIndex
] & 2) != 0);
331 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
, bool upward
)
333 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
334 uintptr_t value
= (uintptr_t)image
;
339 images
[libIndex
] = value
;
343 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext
& context
)
345 // mark that we are done with rebase and bind info
346 markLINKEDIT(context
, MADV_FREE
);
349 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext
& context
)
351 // mark the rebase and bind info and using sequential access
352 markLINKEDIT(context
, MADV_SEQUENTIAL
);
355 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext
& context
, int advise
)
357 // if not loaded at preferred address, mark rebase info
359 if ( (fSlide
!= 0) && (fDyldInfo
->rebase_size
!= 0) )
360 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
;
361 else if ( fDyldInfo
->bind_off
!= 0 )
362 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
;
364 return; // no binding info to prefetch
366 // end is at end of bind info
368 if ( fDyldInfo
->bind_off
!= 0 )
369 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
+ fDyldInfo
->bind_size
;
370 else if ( fDyldInfo
->rebase_off
!= 0 )
371 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
+ fDyldInfo
->rebase_size
;
376 // round to whole pages
377 start
= dyld_page_trunc(start
);
378 end
= dyld_page_round(end
);
380 // do nothing if only one page of rebase/bind info
381 if ( (end
-start
) <= dyld_page_size
)
384 // tell kernel about our access to these pages
385 madvise((void*)start
, end
-start
, advise
);
386 if ( context
.verboseMapping
) {
387 const char* adstr
= "sequential";
388 if ( advise
== MADV_FREE
)
390 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr
, start
, end
-1, this->getPath());
396 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext
& context
, uintptr_t addr
, uintptr_t slide
, uint8_t type
)
398 if ( context
.verboseRebase
) {
399 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr
, slide
);
401 //dyld::log("0x%08lX type=%d\n", addr, type);
402 uintptr_t* locationToFix
= (uintptr_t*)addr
;
404 case REBASE_TYPE_POINTER
:
405 *locationToFix
+= slide
;
407 case REBASE_TYPE_TEXT_ABSOLUTE32
:
408 *locationToFix
+= slide
;
411 dyld::throwf("bad rebase type %d", type
);
415 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
416 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
418 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
419 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
420 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
423 void ImageLoaderMachOCompressed::rebase(const LinkContext
& context
, uintptr_t slide
)
425 CRSetCrashLogMessage2(this->getPath());
426 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->rebase_off
;
427 const uint8_t* const end
= &start
[fDyldInfo
->rebase_size
];
428 const uint8_t* p
= start
;
432 int segmentIndex
= 0;
433 uintptr_t address
= segActualLoadAddress(0);
434 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
435 uintptr_t segmentEndAddress
= segActualEndAddress(0);
439 while ( !done
&& (p
< end
) ) {
440 uint8_t immediate
= *p
& REBASE_IMMEDIATE_MASK
;
441 uint8_t opcode
= *p
& REBASE_OPCODE_MASK
;
444 case REBASE_OPCODE_DONE
:
447 case REBASE_OPCODE_SET_TYPE_IMM
:
450 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
451 segmentIndex
= immediate
;
452 if ( segmentIndex
>= fSegmentsCount
)
453 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
454 segmentIndex
, fSegmentsCount
-1);
455 #if TEXT_RELOC_SUPPORT
456 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
458 if ( !segWriteable(segmentIndex
) )
460 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
461 segmentIndex
, segName(segmentIndex
));
462 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
463 segmentEndAddress
= segActualEndAddress(segmentIndex
);
464 address
= segmentStartAddress
+ read_uleb128(p
, end
);
466 case REBASE_OPCODE_ADD_ADDR_ULEB
:
467 address
+= read_uleb128(p
, end
);
469 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED
:
470 address
+= immediate
*sizeof(uintptr_t);
472 case REBASE_OPCODE_DO_REBASE_IMM_TIMES
:
473 for (int i
=0; i
< immediate
; ++i
) {
474 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
475 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
476 rebaseAt(context
, address
, slide
, type
);
477 address
+= sizeof(uintptr_t);
479 fgTotalRebaseFixups
+= immediate
;
481 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES
:
482 count
= read_uleb128(p
, end
);
483 for (uint32_t i
=0; i
< count
; ++i
) {
484 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
485 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
486 rebaseAt(context
, address
, slide
, type
);
487 address
+= sizeof(uintptr_t);
489 fgTotalRebaseFixups
+= count
;
491 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB
:
492 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
493 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
494 rebaseAt(context
, address
, slide
, type
);
495 address
+= read_uleb128(p
, end
) + sizeof(uintptr_t);
496 ++fgTotalRebaseFixups
;
498 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
:
499 count
= read_uleb128(p
, end
);
500 skip
= read_uleb128(p
, end
);
501 for (uint32_t i
=0; i
< count
; ++i
) {
502 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
503 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
504 rebaseAt(context
, address
, slide
, type
);
505 address
+= skip
+ sizeof(uintptr_t);
507 fgTotalRebaseFixups
+= count
;
510 dyld::throwf("bad rebase opcode %d", *(p
-1));
514 catch (const char* msg
) {
515 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
519 CRSetCrashLogMessage2(NULL
);
522 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol
, const ImageLoader
** foundIn
) const
524 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
525 if ( fDyldInfo
->export_size
== 0 )
528 dyld::logBindings("%s: %s\n", this->getShortName(), symbol
);
530 ++ImageLoaderMachO::fgSymbolTrieSearchs
;
531 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
532 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
533 const uint8_t* foundNodeStart
= this->trieWalk(start
, end
, symbol
);
534 if ( foundNodeStart
!= NULL
) {
535 const uint8_t* p
= foundNodeStart
;
536 const uintptr_t flags
= read_uleb128(p
, end
);
537 // found match, return pointer to terminal part of node
538 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
539 // re-export from another dylib, lookup there
540 const uintptr_t ordinal
= read_uleb128(p
, end
);
541 const char* importedName
= (char*)p
;
542 if ( importedName
[0] == '\0' )
543 importedName
= symbol
;
544 if ( (ordinal
> 0) && (ordinal
<= libraryCount()) ) {
545 const ImageLoader
* reexportedFrom
= libImage((unsigned int)ordinal
-1);
546 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
547 const char* reExportLibPath
= libPath((unsigned int)ordinal
-1);
548 return reexportedFrom
->findExportedSymbol(importedName
, true, reExportLibPath
, foundIn
);
551 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
552 // ordinal, libraryCount(), symbol, this->getPath());
556 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
557 if ( foundIn
!= NULL
)
558 *foundIn
= (ImageLoader
*)this;
559 // return pointer to terminal part of node
560 return (Symbol
*)foundNodeStart
;
567 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr
) const
569 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
570 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
571 return ( (start
<= addr
) && (addr
< end
) );
575 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext
& context
, const Symbol
* symbol
, const ImageLoader
* requestor
, bool runResolver
) const
577 const uint8_t* exportNode
= (uint8_t*)symbol
;
578 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
579 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
580 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
581 throw "symbol is not in trie";
582 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
583 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
584 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
585 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
586 if ( runResolver
&& (flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) ) {
587 // this node has a stub and resolver, run the resolver to get target address
588 uintptr_t stub
= read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
; // skip over stub
589 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
590 uintptr_t interposedStub
= interposedAddress(context
, stub
, requestor
);
591 if ( interposedStub
!= stub
)
592 return interposedStub
;
593 // stub was not interposed, so run resolver
594 typedef uintptr_t (*ResolverProc
)(void);
595 ResolverProc resolver
= (ResolverProc
)(read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
);
596 uintptr_t result
= (*resolver
)();
597 if ( context
.verboseBind
)
598 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver
, result
);
601 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
602 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
603 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
604 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
605 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
606 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
607 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
608 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
609 return read_uleb128(exportNode
, exportTrieEnd
);
611 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
615 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
617 const uint8_t* exportNode
= (uint8_t*)symbol
;
618 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
619 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
620 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
621 throw "symbol is not in trie";
622 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
623 return ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
);
627 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol
* symbol
) const
629 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
632 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
634 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
637 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index
) const
639 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
642 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
644 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
647 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index
) const
649 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
652 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol
* symbol
) const
654 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
659 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
660 bool runResolver
, const ImageLoader
** foundIn
)
663 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
664 if ( *foundIn
!= this )
665 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
666 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
668 // if a bundle is loaded privately the above will not find its exports
669 if ( this->isBundle() && this->hasHiddenExports() ) {
670 // look in self for needed symbol
671 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
673 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
676 // definition can't be found anywhere, ok because it is weak, just return 0
679 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "flat namespace");
683 #if USES_CHAINED_BINDS
684 static void patchCacheUsesOf(const ImageLoader::LinkContext
& context
, const dyld3::closure::Image
* overriddenImage
,
685 uint32_t cacheOffsetOfImpl
, const char* symbolName
, uintptr_t newImpl
)
687 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
688 overriddenImage
->forEachPatchableUseOfExport(cacheOffsetOfImpl
, ^(dyld3::closure::Image::PatchableExport::PatchLocation patchLocation
) {
689 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
690 #if __has_feature(ptrauth_calls)
691 if ( patchLocation
.authenticated
) {
692 dyld3::MachOLoaded::ChainedFixupPointerOnDisk fixupInfo
;
693 fixupInfo
.authRebase
.auth
= true;
694 fixupInfo
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
695 fixupInfo
.authRebase
.diversity
= patchLocation
.discriminator
;
696 fixupInfo
.authRebase
.key
= patchLocation
.key
;
697 uintptr_t newValue
= fixupInfo
.signPointer(loc
, newImpl
+ patchLocation
.getAddend());
698 if ( *loc
!= newValue
) {
700 if ( context
.verboseBind
)
701 dyld::log("dyld: cache fixup: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s) to %s\n",
702 loc
, (void*)newValue
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, patchLocation
.keyName(), symbolName
);
707 uintptr_t newValue
=newImpl
+ patchLocation
.getAddend();
708 if ( *loc
!= newValue
) {
710 if ( context
.verboseBind
)
711 dyld::log("dyld: cache fixup: *%p = %p to %s\n", loc
, (void*)newValue
, symbolName
);
718 uintptr_t ImageLoaderMachOCompressed::resolveWeak(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
719 bool runResolver
, const ImageLoader
** foundIn
)
722 #if USES_CHAINED_BINDS
723 __block
uintptr_t foundOutsideCache
= 0;
724 __block
uintptr_t lastFoundInCache
= 0;
725 CoalesceNotifier notifier
= ^(const Symbol
* implSym
, const ImageLoader
* implIn
, const mach_header
* implMh
) {
726 //dyld::log("notifier: found %s in %p %s\n", symbolName, implMh, implIn->getPath());
727 // This block is only called in dyld2 mode when a non-cached image is search for which weak-def implementation to use
728 // As a side effect of that search we notice any implementations outside and inside the cache,
729 // and use that to trigger patching the cache to use the implementation outside the cache.
730 uintptr_t implAddr
= implIn
->getExportedSymbolAddress(implSym
, context
, nullptr, false, symbolName
);
731 if ( ((dyld3::MachOLoaded
*)implMh
)->inDyldCache() ) {
732 if ( foundOutsideCache
!= 0 ) {
733 // have an implementation in cache and and earlier one not in the cache, patch cache to use earlier one
734 lastFoundInCache
= implAddr
;
736 if ( context
.dyldCache
->findMachHeaderImageIndex(implMh
, imageIndex
) ) {
737 const dyld3::closure::Image
* overriddenImage
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageIndex
+1);
738 uint32_t cacheOffsetOfImpl
= (uint32_t)((uintptr_t)implAddr
- (uintptr_t)context
.dyldCache
);
739 patchCacheUsesOf(context
, overriddenImage
, cacheOffsetOfImpl
, symbolName
, foundOutsideCache
);
744 // record first non-cache implementation
745 if ( foundOutsideCache
== 0 )
746 foundOutsideCache
= implAddr
;
750 CoalesceNotifier notifier
= nullptr;
752 if ( context
.coalescedExportFinder(symbolName
, &sym
, foundIn
, notifier
) ) {
753 if ( *foundIn
!= this )
754 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
755 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
757 // if a bundle is loaded privately the above will not find its exports
758 if ( this->isBundle() && this->hasHiddenExports() ) {
759 // look in self for needed symbol
760 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
762 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
765 // definition can't be found anywhere, ok because it is weak, just return 0
768 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "weak");
772 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext
& context
, const char* symbolName
, const ImageLoader
* definedInImage
,
773 const ImageLoader
* requestorImage
, unsigned requestorOrdinalOfDef
, bool weak_import
, bool runResolver
,
774 const ImageLoader
** foundIn
)
778 if ( definedInImage
->findExportedSymbolAddress(context
, symbolName
, requestorImage
, requestorOrdinalOfDef
, runResolver
, foundIn
, &address
) )
782 // definition can't be found anywhere, ok because it is weak, just return 0
786 // nowhere to be found, check if maybe this image is too new for this OS
787 char versMismatch
[256];
788 versMismatch
[0] = '\0';
789 uint32_t imageMinOS
= this->minOSVersion();
790 // dyld is always built for the current OS, so we can get the current OS version
791 // from the load command in dyld itself.
792 extern const mach_header __dso_handle
;
793 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion(&__dso_handle
);
794 if ( imageMinOS
> dyldMinOS
) {
795 #if __MAC_OS_X_VERSION_MIN_REQUIRED
796 const char* msg
= dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
798 const char* msg
= dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
800 strcpy(versMismatch
, msg
);
803 throwSymbolNotFound(context
, symbolName
, this->getPath(), versMismatch
, definedInImage
->getPath());
807 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext
& context
, const char* symbolName
,
808 uint8_t symboFlags
, long libraryOrdinal
, const ImageLoader
** targetImage
,
809 LastLookup
* last
, bool runResolver
)
813 // only clients that benefit from caching last lookup pass in a LastLookup struct
814 if ( last
!= NULL
) {
815 if ( (last
->ordinal
== libraryOrdinal
)
816 && (last
->flags
== symboFlags
)
817 && (last
->name
== symbolName
) ) {
818 *targetImage
= last
->foundIn
;
823 bool weak_import
= (symboFlags
& BIND_SYMBOL_FLAGS_WEAK_IMPORT
);
824 uintptr_t symbolAddress
;
825 if ( context
.bindFlat
|| (libraryOrdinal
== BIND_SPECIAL_DYLIB_FLAT_LOOKUP
) ) {
826 symbolAddress
= this->resolveFlat(context
, symbolName
, weak_import
, runResolver
, targetImage
);
828 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_WEAK_LOOKUP
) {
829 symbolAddress
= this->resolveWeak(context
, symbolName
, false, runResolver
, targetImage
);
832 if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
) {
833 *targetImage
= context
.mainExecutable
;
835 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_SELF
) {
838 else if ( libraryOrdinal
<= 0 ) {
839 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
840 libraryOrdinal
, symbolName
, this->getPath());
842 else if ( (unsigned)libraryOrdinal
<= libraryCount() ) {
843 *targetImage
= libImage((unsigned int)libraryOrdinal
-1);
846 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
847 libraryOrdinal
, libraryCount(), symbolName
, this->getPath());
849 if ( *targetImage
== NULL
) {
851 // if target library not loaded and reference is weak or library is weak return 0
855 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
856 symbolName
, this->getPath(), libraryOrdinal
);
860 symbolAddress
= resolveTwolevel(context
, symbolName
, *targetImage
, this, (unsigned)libraryOrdinal
, weak_import
, runResolver
, targetImage
);
864 // save off lookup results if client wants
865 if ( last
!= NULL
) {
866 last
->ordinal
= libraryOrdinal
;
867 last
->flags
= symboFlags
;
868 last
->name
= symbolName
;
869 last
->foundIn
= *targetImage
;
870 last
->result
= symbolAddress
;
873 return symbolAddress
;
876 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
877 uintptr_t addr
, uint8_t type
, const char* symbolName
,
878 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
879 ExtraBindData
*extraBindData
,
880 const char* msg
, LastLookup
* last
, bool runResolver
)
882 const ImageLoader
* targetImage
;
883 uintptr_t symbolAddress
;
886 if (type
== BIND_TYPE_THREADED_REBASE
) {
888 targetImage
= nullptr;
890 symbolAddress
= image
->resolve(context
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
893 return image
->bindLocation(context
, image
->imageBaseAddress(), addr
, symbolAddress
, type
, symbolName
, addend
, image
->getPath(), targetImage
? targetImage
->getPath() : NULL
, msg
, extraBindData
, image
->fSlide
);
897 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
898 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
900 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
901 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
902 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
906 void ImageLoaderMachOCompressed::doBind(const LinkContext
& context
, bool forceLazysBound
)
908 CRSetCrashLogMessage2(this->getPath());
910 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
911 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
912 if ( this->usablePrebinding(context
) ) {
913 // don't need to bind
914 // except weak which may now be inline with the regular binds
915 if (this->participatesInCoalescing()) {
916 // run through all binding opcodes
917 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
918 uintptr_t addr
, uint8_t type
, const char* symbolName
,
919 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
920 ExtraBindData
*extraBindData
,
921 const char* msg
, LastLookup
* last
, bool runResolver
) {
922 if ( libraryOrdinal
!= BIND_SPECIAL_DYLIB_WEAK_LOOKUP
)
924 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
925 addend
, libraryOrdinal
, extraBindData
,
926 msg
, last
, runResolver
);
931 uint64_t t0
= mach_absolute_time();
933 #if TEXT_RELOC_SUPPORT
934 // if there are __TEXT fixups, temporarily make __TEXT writable
935 if ( fTextSegmentBinds
)
936 this->makeTextSegmentWritable(context
, true);
940 bool bindingBecauseOfRoot
= ( this->overridesCachedDylib(ignore
) || this->inSharedCache() );
941 vmAccountingSetSuspended(context
, bindingBecauseOfRoot
);
943 // run through all binding opcodes
944 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
945 uintptr_t addr
, uint8_t type
, const char* symbolName
,
946 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
947 ExtraBindData
*extraBindData
,
948 const char* msg
, LastLookup
* last
, bool runResolver
) {
949 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
950 addend
, libraryOrdinal
, extraBindData
,
951 msg
, last
, runResolver
);
954 #if TEXT_RELOC_SUPPORT
955 // if there were __TEXT fixups, restore write protection
956 if ( fTextSegmentBinds
)
957 this->makeTextSegmentWritable(context
, false);
960 // if this image is in the shared cache, but depends on something no longer in the shared cache,
961 // there is no way to reset the lazy pointers, so force bind them now
962 if ( forceLazysBound
|| fInSharedCache
)
963 this->doBindJustLazies(context
);
965 // this image is in cache, but something below it is not. If
966 // this image has lazy pointer to a resolver function, then
967 // the stub may have been altered to point to a shared lazy pointer.
968 if ( fInSharedCache
)
969 this->updateOptimizedLazyPointers(context
);
971 // tell kernel we are done with chunks of LINKEDIT
972 if ( !context
.preFetchDisabled
)
973 this->markFreeLINKEDIT(context
);
975 uint64_t t1
= mach_absolute_time();
976 ImageLoader::fgTotalRebindCacheTime
+= (t1
-t0
);
979 #if USES_CHAINED_BINDS
980 // See if this dylib overrides something in the dyld cache
981 uint32_t dyldCacheOverrideImageNum
;
982 if ( context
.dyldCache
&& overridesCachedDylib(dyldCacheOverrideImageNum
) ) {
983 // need to patch all other places in cache that point to the overridden dylib, to point to this dylib instead
984 const dyld3::closure::Image
* overriddenImage
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(dyldCacheOverrideImageNum
);
985 overriddenImage
->forEachPatchableExport(^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
986 uintptr_t newImpl
= 0;
987 const ImageLoader
* foundIn
;
988 if ( const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(exportName
, &foundIn
) ) {
989 newImpl
= foundIn
->getExportedSymbolAddress(sym
, context
, this);
991 patchCacheUsesOf(context
, overriddenImage
, cacheOffsetOfImpl
, exportName
, newImpl
);
996 // set up dyld entry points in image
997 // do last so flat main executables will have __dyld or __program_vars set up
998 this->setupLazyPointerHandler(context
);
999 CRSetCrashLogMessage2(NULL
);
1003 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext
& context
)
1005 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1006 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1007 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1008 ExtraBindData
*extraBindData
,
1009 const char* msg
, LastLookup
* last
, bool runResolver
) {
1010 return ImageLoaderMachOCompressed::bindAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1011 addend
, libraryOrdinal
, extraBindData
,
1012 msg
, last
, runResolver
);
1016 void ImageLoaderMachOCompressed::registerInterposing(const LinkContext
& context
)
1018 // mach-o files advertise interposing by having a __DATA __interpose section
1019 struct InterposeData
{ uintptr_t replacement
; uintptr_t replacee
; };
1020 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1021 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1022 const struct load_command
* cmd
= cmds
;
1023 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1025 case LC_SEGMENT_COMMAND
:
1027 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1028 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1029 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1030 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1031 if ( ((sect
->flags
& SECTION_TYPE
) == S_INTERPOSING
) || ((strcmp(sect
->sectname
, "__interpose") == 0) && (strcmp(seg
->segname
, "__DATA") == 0)) ) {
1032 // <rdar://problem/23929217> Ensure section is within segment
1033 if ( (sect
->addr
< seg
->vmaddr
) || (sect
->addr
+sect
->size
> seg
->vmaddr
+seg
->vmsize
) || (sect
->addr
+sect
->size
< sect
->addr
) )
1034 dyld::throwf("interpose section has malformed address range for %s\n", this->getPath());
1035 __block
uintptr_t sectionStart
= sect
->addr
+ fSlide
;
1036 __block
uintptr_t sectionEnd
= sectionStart
+ sect
->size
;
1037 const size_t count
= sect
->size
/ sizeof(InterposeData
);
1038 InterposeData interposeArray
[count
];
1039 // Note, we memcpy here as rebases may have already been applied.
1040 memcpy(&interposeArray
[0], (void*)sectionStart
, sect
->size
);
1041 __block InterposeData
*interposeArrayStart
= &interposeArray
[0];
1042 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
, uintptr_t addr
, uint8_t type
,
1043 const char* symbolName
, uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1044 ExtraBindData
*extraBindData
,
1045 const char* msg
, LastLookup
* last
, bool runResolver
) {
1046 if (addr
>= sectionStart
&& addr
< sectionEnd
) {
1047 if ( context
.verboseInterposing
) {
1048 dyld::log("dyld: interposing %s at 0x%lx in range 0x%lx..0x%lx\n",
1049 symbolName
, addr
, sectionStart
, sectionEnd
);
1051 const ImageLoader
* targetImage
;
1052 uintptr_t symbolAddress
;
1055 if (type
== BIND_TYPE_THREADED_REBASE
) {
1057 targetImage
= nullptr;
1059 symbolAddress
= image
->resolve(ctx
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
1061 uintptr_t newValue
= symbolAddress
+addend
;
1062 uintptr_t index
= (addr
- sectionStart
) / sizeof(uintptr_t);
1064 case BIND_TYPE_POINTER
:
1065 ((uintptr_t*)interposeArrayStart
)[index
] = newValue
;
1067 case BIND_TYPE_TEXT_ABSOLUTE32
:
1070 case BIND_TYPE_TEXT_PCREL32
:
1073 case BIND_TYPE_THREADED_BIND
:
1074 ((uintptr_t*)interposeArrayStart
)[index
] = newValue
;
1076 case BIND_TYPE_THREADED_REBASE
: {
1077 // Regular pointer which needs to fit in 51-bits of value.
1078 // C++ RTTI uses the top bit, so we'll allow the whole top-byte
1079 // and the signed-extended bottom 43-bits to be fit in to 51-bits.
1080 uint64_t top8Bits
= (*(uint64_t*)addr
) & 0x0007F80000000000ULL
;
1081 uint64_t bottom43Bits
= (*(uint64_t*)addr
) & 0x000007FFFFFFFFFFULL
;
1082 uint64_t targetValue
= ( top8Bits
<< 13 ) | (((intptr_t)(bottom43Bits
<< 21) >> 21) & 0x00FFFFFFFFFFFFFF);
1083 newValue
= (uintptr_t)(targetValue
+ fSlide
);
1084 ((uintptr_t*)interposeArrayStart
)[index
] = newValue
;
1088 dyld::throwf("bad bind type %d", type
);
1091 return (uintptr_t)0;
1093 for (size_t j
=0; j
< count
; ++j
) {
1094 ImageLoader::InterposeTuple tuple
;
1095 tuple
.replacement
= interposeArray
[j
].replacement
;
1096 tuple
.neverImage
= this;
1097 tuple
.onlyImage
= NULL
;
1098 tuple
.replacee
= interposeArray
[j
].replacee
;
1099 if ( context
.verboseInterposing
) {
1100 dyld::log("dyld: interposing index %d 0x%lx with 0x%lx\n",
1101 (unsigned)j
, interposeArray
[j
].replacee
, interposeArray
[j
].replacement
);
1103 // <rdar://problem/25686570> ignore interposing on a weak function that does not exist
1104 if ( tuple
.replacee
== 0 )
1106 // <rdar://problem/7937695> verify that replacement is in this image
1107 if ( this->containsAddress((void*)tuple
.replacement
) ) {
1108 // chain to any existing interpositions
1109 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
1110 if ( it
->replacee
== tuple
.replacee
) {
1111 tuple
.replacee
= it
->replacement
;
1114 ImageLoader::fgInterposingTuples
.push_back(tuple
);
1122 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1126 bool ImageLoaderMachOCompressed::usesChainedFixups() const
1129 return ( machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64_E
);
1135 struct ThreadedBindData
{
1136 ThreadedBindData(const char* symbolName
, int64_t addend
, long libraryOrdinal
, uint8_t symbolFlags
, uint8_t type
)
1137 : symbolName(symbolName
), addend(addend
), libraryOrdinal(libraryOrdinal
), symbolFlags(symbolFlags
), type(type
) { }
1139 std::tuple
<const char*, int64_t, long, bool, uint8_t> pack() const {
1140 return std::make_tuple(symbolName
, addend
, libraryOrdinal
, symbolFlags
, type
);
1143 const char* symbolName
= nullptr;
1145 long libraryOrdinal
= 0;
1146 uint8_t symbolFlags
= 0;
1150 void ImageLoaderMachOCompressed::eachBind(const LinkContext
& context
, bind_handler handler
)
1153 const dysymtab_command
* dynSymbolTable
= NULL
;
1154 const macho_nlist
* symbolTable
= NULL
;
1155 const char* symbolTableStrings
= NULL
;
1156 uint32_t maxStringOffset
= 0;
1158 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1159 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1160 const struct load_command
* cmd
= cmds
;
1161 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1165 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1166 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1167 maxStringOffset
= symtab
->strsize
;
1168 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1172 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1175 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1179 int segmentIndex
= -1;
1180 uintptr_t address
= segActualLoadAddress(0);
1181 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1182 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1183 const char* symbolName
= NULL
;
1184 uint8_t symboFlags
= 0;
1185 bool libraryOrdinalSet
= false;
1186 long libraryOrdinal
= 0;
1187 intptr_t addend
= 0;
1190 uintptr_t segOffset
= 0;
1192 dyld3::OverflowSafeArray
<ThreadedBindData
> ordinalTable
;
1193 bool useThreadedRebaseBind
= false;
1194 ExtraBindData extraBindData
;
1195 LastLookup last
= { 0, 0, NULL
, 0, NULL
};
1196 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->bind_off
;
1197 const uint8_t* const end
= &start
[fDyldInfo
->bind_size
];
1198 const uint8_t* p
= start
;
1200 while ( !done
&& (p
< end
) ) {
1201 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1202 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1205 case BIND_OPCODE_DONE
:
1208 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1209 libraryOrdinal
= immediate
;
1210 libraryOrdinalSet
= true;
1212 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1213 libraryOrdinal
= read_uleb128(p
, end
);
1214 libraryOrdinalSet
= true;
1216 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1217 // the special ordinals are negative numbers
1218 if ( immediate
== 0 )
1221 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1222 libraryOrdinal
= signExtended
;
1224 libraryOrdinalSet
= true;
1226 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1227 symbolName
= (char*)p
;
1228 symboFlags
= immediate
;
1233 case BIND_OPCODE_SET_TYPE_IMM
:
1236 case BIND_OPCODE_SET_ADDEND_SLEB
:
1237 addend
= read_sleb128(p
, end
);
1239 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1240 segmentIndex
= immediate
;
1241 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1242 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1243 segmentIndex
, fSegmentsCount
-1);
1244 #if TEXT_RELOC_SUPPORT
1245 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
1247 if ( !segWriteable(segmentIndex
) )
1249 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1250 segOffset
= read_uleb128(p
, end
);
1251 if ( segOffset
> segSize(segmentIndex
) )
1252 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1253 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1254 address
= segmentStartAddress
+ segOffset
;
1255 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1257 case BIND_OPCODE_ADD_ADDR_ULEB
:
1258 address
+= read_uleb128(p
, end
);
1260 case BIND_OPCODE_DO_BIND
:
1261 if (!useThreadedRebaseBind
) {
1262 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1263 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1264 if ( symbolName
== NULL
)
1265 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1266 if ( segmentIndex
== -1 )
1267 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1268 if ( !libraryOrdinalSet
)
1269 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1270 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1271 &extraBindData
, "", &last
, false);
1272 address
+= sizeof(intptr_t);
1274 ordinalTable
.push_back(ThreadedBindData(symbolName
, addend
, libraryOrdinal
, symboFlags
, type
));
1277 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1278 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1279 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1280 if ( symbolName
== NULL
)
1281 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1282 if ( segmentIndex
== -1 )
1283 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1284 if ( !libraryOrdinalSet
)
1285 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1286 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1287 &extraBindData
, "", &last
, false);
1288 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1290 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1291 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1292 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1293 if ( symbolName
== NULL
)
1294 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1295 if ( segmentIndex
== -1 )
1296 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1297 if ( !libraryOrdinalSet
)
1298 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1299 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1300 &extraBindData
, "", &last
, false);
1301 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1303 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1304 if ( symbolName
== NULL
)
1305 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1306 if ( segmentIndex
== -1 )
1307 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1308 count
= read_uleb128(p
, end
);
1309 if ( !libraryOrdinalSet
)
1310 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
1311 skip
= read_uleb128(p
, end
);
1312 for (uint32_t i
=0; i
< count
; ++i
) {
1313 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1314 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1315 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1316 &extraBindData
, "", &last
, false);
1317 address
+= skip
+ sizeof(intptr_t);
1320 case BIND_OPCODE_THREADED
:
1321 if (sizeof(intptr_t) != 8) {
1322 dyld::throwf("BIND_OPCODE_THREADED require 64-bit");
1325 // Note the immediate is a sub opcode
1326 switch (immediate
) {
1327 case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB
:
1328 count
= read_uleb128(p
, end
);
1329 ordinalTable
.clear();
1330 // FIXME: ld64 wrote the wrong value here and we need to offset by 1 for now.
1331 ordinalTable
.reserve(count
+ 1);
1332 useThreadedRebaseBind
= true;
1334 case BIND_SUBOPCODE_THREADED_APPLY
: {
1337 address
= segmentStartAddress
+ segOffset
;
1338 uint64_t value
= *(uint64_t*)address
;
1341 bool isRebase
= (value
& (1ULL << 62)) == 0;
1344 // Call the bind handler which knows about our bind type being set to rebase
1345 handler(context
, this, address
, BIND_TYPE_THREADED_REBASE
, nullptr, 0, 0, 0,
1346 nullptr, "", &last
, false);
1349 // the ordinal is bits [0..15]
1350 uint16_t ordinal
= value
& 0xFFFF;
1351 if (ordinal
>= ordinalTable
.count()) {
1352 dyld::throwf("bind ordinal is out of range\n");
1355 std::tie(symbolName
, addend
, libraryOrdinal
, symboFlags
, type
) = ordinalTable
[ordinal
].pack();
1356 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1357 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1359 handler(context
, this, address
, BIND_TYPE_THREADED_BIND
,
1360 symbolName
, symboFlags
, addend
, libraryOrdinal
,
1361 nullptr, "", &last
, false);
1365 // The delta is bits [51..61]
1366 // And bit 62 is to tell us if we are a rebase (0) or bind (1)
1367 value
&= ~(1ULL << 62);
1368 delta
= ( value
& 0x3FF8000000000000 ) >> 51;
1369 segOffset
+= delta
* sizeof(intptr_t);
1370 } while ( delta
!= 0 );
1375 dyld::throwf("bad threaded bind subopcode 0x%02X", *p
);
1379 dyld::throwf("bad bind opcode %d in bind info", *p
);
1383 catch (const char* msg
) {
1384 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1390 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext
& context
, bind_handler handler
)
1393 uint8_t type
= BIND_TYPE_POINTER
;
1394 int segmentIndex
= -1;
1395 uintptr_t address
= segActualLoadAddress(0);
1396 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
1397 uintptr_t segmentEndAddress
= segActualEndAddress(0);
1398 uintptr_t segOffset
;
1399 const char* symbolName
= NULL
;
1400 uint8_t symboFlags
= 0;
1401 long libraryOrdinal
= 0;
1402 intptr_t addend
= 0;
1403 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1404 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1405 const uint8_t* p
= start
;
1407 while ( !done
&& (p
< end
) ) {
1408 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1409 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1412 case BIND_OPCODE_DONE
:
1413 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1415 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1416 libraryOrdinal
= immediate
;
1418 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1419 libraryOrdinal
= read_uleb128(p
, end
);
1421 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1422 // the special ordinals are negative numbers
1423 if ( immediate
== 0 )
1426 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1427 libraryOrdinal
= signExtended
;
1430 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1431 symbolName
= (char*)p
;
1432 symboFlags
= immediate
;
1437 case BIND_OPCODE_SET_TYPE_IMM
:
1440 case BIND_OPCODE_SET_ADDEND_SLEB
:
1441 addend
= read_sleb128(p
, end
);
1443 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1444 segmentIndex
= immediate
;
1445 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1446 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1447 segmentIndex
, fSegmentsCount
-1);
1448 if ( !segWriteable(segmentIndex
) )
1449 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1450 segOffset
= read_uleb128(p
, end
);
1451 if ( segOffset
> segSize(segmentIndex
) )
1452 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1453 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1454 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1455 address
= segmentStartAddress
+ segOffset
;
1457 case BIND_OPCODE_ADD_ADDR_ULEB
:
1458 address
+= read_uleb128(p
, end
);
1460 case BIND_OPCODE_DO_BIND
:
1461 if ( segmentIndex
== -1 )
1462 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1463 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1464 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1465 if ( symbolName
== NULL
)
1466 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1467 handler(context
, this, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
,
1468 NULL
, "forced lazy ", NULL
, false);
1469 address
+= sizeof(intptr_t);
1471 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1472 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1473 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1475 dyld::throwf("bad lazy bind opcode %d", *p
);
1480 catch (const char* msg
) {
1481 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1487 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1488 // the classic lazy loader is used even when running on 10.6
1489 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1491 // only works with compressed LINKEDIT if classic symbol table is also present
1492 const macho_nlist
* symbolTable
= NULL
;
1493 const char* symbolTableStrings
= NULL
;
1494 const dysymtab_command
* dynSymbolTable
= NULL
;
1495 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1496 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1497 const struct load_command
* cmd
= cmds
;
1498 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1502 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1503 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1504 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1508 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1511 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1513 // no symbol table => no lookup by address
1514 if ( (symbolTable
== NULL
) || (dynSymbolTable
== NULL
) )
1515 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer
, this->getPath());
1517 // scan for all lazy-pointer sections
1518 const bool twoLevel
= this->usesTwoLevelNameSpace();
1519 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1521 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1523 case LC_SEGMENT_COMMAND
:
1525 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1526 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1527 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1528 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1529 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1530 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1531 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1532 const size_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1533 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1534 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1535 const uint32_t indirectTableOffset
= sect
->reserved1
;
1536 const size_t lazyIndex
= lazyPointer
- symbolPointers
;
1537 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1540 if ( (symbolIndex
!= INDIRECT_SYMBOL_ABS
) && (symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) ) {
1541 const macho_nlist
* symbol
= &symbolTable
[symbolIndex
];
1542 const char* symbolName
= &symbolTableStrings
[symbol
->n_un
.n_strx
];
1543 int libraryOrdinal
= GET_LIBRARY_ORDINAL(symbol
->n_desc
);
1544 if ( !twoLevel
|| context
.bindFlat
)
1545 libraryOrdinal
= BIND_SPECIAL_DYLIB_FLAT_LOOKUP
;
1546 uintptr_t ptrToBind
= (uintptr_t)lazyPointer
;
1547 uintptr_t symbolAddr
= bindAt(context
, this, ptrToBind
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
,
1548 NULL
, "lazy ", NULL
);
1549 ++fgTotalLazyBindFixups
;
1556 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1558 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1563 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
,
1564 void (*lock
)(), void (*unlock
)())
1566 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1567 if ( this->usesTwoLevelNameSpace() ) {
1568 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1571 // acquire dyld global lock
1576 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1577 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1579 uintptr_t segOffset
;
1581 const char* symbolName
;
1585 if ( ! getLazyBindingInfo(lazyBindingInfoOffset
, start
, end
, &segIndex
, &segOffset
, &libraryOrdinal
, &symbolName
, &doneAfterBind
) )
1586 dyld::throwf("bad lazy bind info");
1588 if ( segIndex
>= fSegmentsCount
)
1589 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1590 segIndex
, fSegmentsCount
-1);
1591 if ( segOffset
> segSize(segIndex
) )
1592 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segIndex
));
1593 uintptr_t address
= segActualLoadAddress(segIndex
) + segOffset
;
1594 result
= bindAt(context
, this, address
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
,
1595 NULL
, "lazy ", NULL
, true);
1596 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1597 } while (!doneAfterBind
&& !context
.strictMachORequired
);
1599 if ( !this->usesTwoLevelNameSpace() ) {
1600 // release dyld global lock
1601 if ( unlock
!= NULL
)
1607 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
, unsigned)
1610 it
.symbolName
= " ";
1611 it
.loadOrder
= loadOrder
;
1612 it
.weakSymbol
= false;
1613 it
.symbolMatches
= false;
1616 it
.endIndex
= this->fDyldInfo
->weak_bind_size
;
1623 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator
& it
)
1628 if ( this->fDyldInfo
->weak_bind_size
== 0 ) {
1629 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1631 it
.symbolName
= "~~~";
1634 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1635 const uint8_t* p
= start
+ it
.curIndex
;
1636 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1639 uintptr_t segOffset
;
1641 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1642 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1645 case BIND_OPCODE_DONE
:
1647 it
.curIndex
= p
- start
;
1648 it
.symbolName
= "~~~"; // sorts to end
1650 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1651 it
.symbolName
= (char*)p
;
1652 it
.weakSymbol
= ((immediate
& BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION
) == 0);
1653 it
.symbolMatches
= false;
1657 it
.curIndex
= p
- start
;
1659 case BIND_OPCODE_SET_TYPE_IMM
:
1660 it
.type
= immediate
;
1662 case BIND_OPCODE_SET_ADDEND_SLEB
:
1663 it
.addend
= read_sleb128(p
, end
);
1665 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1666 if ( immediate
>= fSegmentsCount
)
1667 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1668 immediate
, fSegmentsCount
-1);
1670 // <rdar://problem/23138428> iOS app compatibility
1671 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1672 #elif TEXT_RELOC_SUPPORT
1673 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1674 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1675 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1677 if ( !segWriteable(immediate
) )
1679 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1680 segOffset
= read_uleb128(p
, end
);
1681 if ( segOffset
> segSize(immediate
) )
1682 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1683 it
.address
= segActualLoadAddress(immediate
) + segOffset
;
1685 case BIND_OPCODE_ADD_ADDR_ULEB
:
1686 it
.address
+= read_uleb128(p
, end
);
1688 case BIND_OPCODE_DO_BIND
:
1689 it
.address
+= sizeof(intptr_t);
1691 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1692 it
.address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1694 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1695 it
.address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1697 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1698 count
= read_uleb128(p
, end
);
1699 skip
= read_uleb128(p
, end
);
1700 for (uint32_t i
=0; i
< count
; ++i
) {
1701 it
.address
+= skip
+ sizeof(intptr_t);
1705 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p
, (int)(p
-start
), this->getPath());
1708 /// hmmm, BIND_OPCODE_DONE is missing...
1710 it
.symbolName
= "~~~";
1711 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1715 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1717 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1718 const ImageLoader
* foundIn
= NULL
;
1719 const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(it
.symbolName
, &foundIn
);
1720 if ( sym
!= NULL
) {
1721 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1722 return foundIn
->getExportedSymbolAddress(sym
, context
, this);
1728 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, unsigned targetIndex
, const LinkContext
& context
)
1730 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1731 if ( this->getState() < dyld_image_state_bound
)
1734 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1735 const uint8_t* p
= start
+ it
.curIndex
;
1736 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1738 uint8_t type
= it
.type
;
1739 uintptr_t address
= it
.address
;
1740 const char* symbolName
= it
.symbolName
;
1741 intptr_t addend
= it
.addend
;
1744 uintptr_t segOffset
;
1746 bool boundSomething
= false;
1747 while ( !done
&& (p
< end
) ) {
1748 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1749 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1752 case BIND_OPCODE_DONE
:
1755 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1758 case BIND_OPCODE_SET_TYPE_IMM
:
1761 case BIND_OPCODE_SET_ADDEND_SLEB
:
1762 addend
= read_sleb128(p
, end
);
1764 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1765 if ( immediate
>= fSegmentsCount
)
1766 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1767 immediate
, fSegmentsCount
-1);
1769 // <rdar://problem/23138428> iOS app compatibility
1770 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1771 #elif TEXT_RELOC_SUPPORT
1772 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1773 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1774 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1776 if ( !segWriteable(immediate
) )
1778 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1779 segOffset
= read_uleb128(p
, end
);
1780 if ( segOffset
> segSize(immediate
) )
1781 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1782 address
= segActualLoadAddress(immediate
) + segOffset
;
1784 case BIND_OPCODE_ADD_ADDR_ULEB
:
1785 address
+= read_uleb128(p
, end
);
1787 case BIND_OPCODE_DO_BIND
:
1788 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1789 boundSomething
= true;
1790 address
+= sizeof(intptr_t);
1792 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1793 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1794 boundSomething
= true;
1795 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1797 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1798 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1799 boundSomething
= true;
1800 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1802 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1803 count
= read_uleb128(p
, end
);
1804 skip
= read_uleb128(p
, end
);
1805 for (uint32_t i
=0; i
< count
; ++i
) {
1806 bindLocation(context
, this->imageBaseAddress(), address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ", NULL
, fSlide
);
1807 boundSomething
= true;
1808 address
+= skip
+ sizeof(intptr_t);
1812 dyld::throwf("bad bind opcode %d in weak binding info", *p
);
1815 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1816 if ( boundSomething
&& (targetImage
!= this) )
1817 context
.addDynamicReference(this, targetImage
);
1820 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
1821 uintptr_t addr
, uint8_t type
, const char*,
1822 uint8_t, intptr_t, long,
1823 ExtraBindData
*extraBindData
,
1824 const char*, LastLookup
*, bool runResolver
)
1826 if ( type
== BIND_TYPE_POINTER
) {
1827 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1828 uintptr_t curValue
= *fixupLocation
;
1829 uintptr_t newValue
= interposedAddress(context
, curValue
, image
);
1830 if ( newValue
!= curValue
) {
1831 *fixupLocation
= newValue
;
1837 void ImageLoaderMachOCompressed::doInterpose(const LinkContext
& context
)
1839 if ( context
.verboseInterposing
)
1840 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples
.size(), this->getPath());
1842 // update prebound symbols
1843 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1844 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1845 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1846 ExtraBindData
*extraBindData
,
1847 const char* msg
, LastLookup
* last
, bool runResolver
) {
1848 return ImageLoaderMachOCompressed::interposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1849 addend
, libraryOrdinal
, extraBindData
,
1850 msg
, last
, runResolver
);
1852 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1853 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1854 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1855 ExtraBindData
*extraBindData
,
1856 const char* msg
, LastLookup
* last
, bool runResolver
) {
1857 return ImageLoaderMachOCompressed::interposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1858 addend
, libraryOrdinal
, extraBindData
,
1859 msg
, last
, runResolver
);
1864 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext
& context
, ImageLoaderMachOCompressed
* image
,
1865 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1866 uint8_t, intptr_t, long,
1867 ExtraBindData
*extraBindData
,
1868 const char*, LastLookup
*, bool runResolver
)
1870 if ( type
== BIND_TYPE_POINTER
) {
1871 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1872 uintptr_t value
= *fixupLocation
;
1873 // don't apply interposing to table entries.
1874 if ( (context
.dynamicInterposeArray
<= (void*)addr
) && ((void*)addr
< &context
.dynamicInterposeArray
[context
.dynamicInterposeCount
]) )
1876 for(size_t i
=0; i
< context
.dynamicInterposeCount
; ++i
) {
1877 if ( value
== (uintptr_t)context
.dynamicInterposeArray
[i
].replacee
) {
1878 if ( context
.verboseInterposing
) {
1879 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1880 fixupLocation
, context
.dynamicInterposeArray
[i
].replacee
, context
.dynamicInterposeArray
[i
].replacement
, image
->getPath());
1882 *fixupLocation
= (uintptr_t)context
.dynamicInterposeArray
[i
].replacement
;
1889 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext
& context
)
1891 if ( context
.verboseInterposing
)
1892 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context
.dynamicInterposeCount
, this->getPath());
1894 // update already bound references to symbols
1895 eachBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1896 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1897 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1898 ExtraBindData
*extraBindData
,
1899 const char* msg
, LastLookup
* last
, bool runResolver
) {
1900 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1901 addend
, libraryOrdinal
, extraBindData
,
1902 msg
, last
, runResolver
);
1904 eachLazyBind(context
, ^(const LinkContext
& ctx
, ImageLoaderMachOCompressed
* image
,
1905 uintptr_t addr
, uint8_t type
, const char* symbolName
,
1906 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
,
1907 ExtraBindData
*extraBindData
,
1908 const char* msg
, LastLookup
* last
, bool runResolver
) {
1909 return ImageLoaderMachOCompressed::dynamicInterposeAt(ctx
, image
, addr
, type
, symbolName
, symbolFlags
,
1910 addend
, libraryOrdinal
, extraBindData
,
1911 msg
, last
, runResolver
);
1915 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1917 return ImageLoaderMachO::findClosestSymbol((mach_header
*)fMachOData
, addr
, closestAddr
);
1921 #if PREBOUND_IMAGE_SUPPORT
1922 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext
& context
)
1924 // no way to back off a prebound compress image
1929 #if __arm__ || __x86_64__
1930 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub
, void** originalLazyPointerAddr
, const LinkContext
& context
)
1933 uint32_t* instructions
= (uint32_t*)stub
;
1934 // sanity check this is a stub we understand
1935 if ( (instructions
[0] != 0xe59fc004) || (instructions
[1] != 0xe08fc00c) || (instructions
[2] != 0xe59cf000) )
1938 void** lazyPointerAddr
= (void**)(instructions
[3] + (stub
+ 12));
1941 // sanity check this is a stub we understand
1942 if ( (stub
[0] != 0xFF) || (stub
[1] != 0x25) )
1944 int32_t ripOffset
= *((int32_t*)(&stub
[2]));
1945 void** lazyPointerAddr
= (void**)(ripOffset
+ stub
+ 6);
1948 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1949 if ( lazyPointerAddr
!= originalLazyPointerAddr
) {
1950 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1951 const ImageLoader
* lazyPointerImage
= context
.findImageContainingAddress(lazyPointerAddr
);
1952 if ( lazyPointerImage
!= NULL
)
1955 // copy newly re-bound lazy pointer value to shared lazy pointer
1956 *lazyPointerAddr
= *originalLazyPointerAddr
;
1958 if ( context
.verboseBind
)
1959 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1960 this->getShortName(), (long)lazyPointerAddr
, (long)*originalLazyPointerAddr
);
1966 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1967 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext
& context
)
1969 #if __arm__ || __x86_64__
1970 // find stubs and indirect symbol table
1971 const struct macho_section
* stubsSection
= NULL
;
1972 const dysymtab_command
* dynSymbolTable
= NULL
;
1973 const macho_header
* mh
= (macho_header
*)fMachOData
;
1974 const uint32_t cmd_count
= mh
->ncmds
;
1975 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1976 const struct load_command
* cmd
= cmds
;
1977 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1978 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1979 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1980 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1981 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1982 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1983 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1984 if ( type
== S_SYMBOL_STUBS
)
1985 stubsSection
= sect
;
1988 else if ( cmd
->cmd
== LC_DYSYMTAB
) {
1989 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1991 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1993 if ( dynSymbolTable
== NULL
)
1995 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1996 if ( stubsSection
== NULL
)
1998 const uint32_t stubsSize
= stubsSection
->reserved2
;
1999 const uint32_t stubsCount
= (uint32_t)(stubsSection
->size
/ stubsSize
);
2000 const uint32_t stubsIndirectTableOffset
= stubsSection
->reserved1
;
2001 if ( (stubsIndirectTableOffset
+stubsCount
) > dynSymbolTable
->nindirectsyms
)
2003 uint8_t* const stubsAddr
= (uint8_t*)(stubsSection
->addr
+ this->fSlide
);
2005 // for each lazy pointer section
2007 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
2008 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
2009 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
2010 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
2011 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
2012 for (const struct macho_section
* lazyPointerSection
=sectionsStart
; lazyPointerSection
< sectionsEnd
; ++lazyPointerSection
) {
2013 const uint8_t type
= lazyPointerSection
->flags
& SECTION_TYPE
;
2014 if ( type
!= S_LAZY_SYMBOL_POINTERS
)
2016 const uint32_t lazyPointersCount
= (uint32_t)(lazyPointerSection
->size
/ sizeof(void*));
2017 const uint32_t lazyPointersIndirectTableOffset
= lazyPointerSection
->reserved1
;
2018 if ( (lazyPointersIndirectTableOffset
+lazyPointersCount
) > dynSymbolTable
->nindirectsyms
)
2020 void** const lazyPointersAddr
= (void**)(lazyPointerSection
->addr
+ this->fSlide
);
2021 // for each lazy pointer
2022 for(uint32_t lpIndex
=0; lpIndex
< lazyPointersCount
; ++lpIndex
) {
2023 const uint32_t lpSymbolIndex
= indirectTable
[lazyPointersIndirectTableOffset
+lpIndex
];
2024 // find matching stub and validate it uses this lazy pointer
2025 for(uint32_t stubIndex
=0; stubIndex
< stubsCount
; ++stubIndex
) {
2026 if ( indirectTable
[stubsIndirectTableOffset
+stubIndex
] == lpSymbolIndex
) {
2027 this->updateAlternateLazyPointer(stubsAddr
+stubIndex
*stubsSize
, &lazyPointersAddr
[lpIndex
], context
);
2035 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
2042 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command
* encryptCmd
, const LinkContext
& context
)
2044 #if __arm__ || __arm64__
2045 if ( encryptCmd
== NULL
)
2047 const mach_header
* mh
= NULL
;
2048 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
2049 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
2050 mh
= (mach_header
*)segActualLoadAddress(i
);
2054 void* start
= ((uint8_t*)mh
) + encryptCmd
->cryptoff
;
2055 size_t len
= encryptCmd
->cryptsize
;
2056 uint32_t cputype
= mh
->cputype
;
2057 uint32_t cpusubtype
= mh
->cpusubtype
;
2058 uint32_t cryptid
= encryptCmd
->cryptid
;
2059 if (context
.verboseMapping
) {
2060 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start
, (long)start
+len
);
2062 int result
= mremap_encrypted(start
, len
, cryptid
, cputype
, cpusubtype
);
2063 if ( result
!= 0 ) {
2064 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result
, errno
, this->getPath());