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"
44 #ifndef EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
45 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
48 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
51 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
52 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
53 struct macho_segment_command
: public segment_command_64
{};
54 struct macho_section
: public section_64
{};
55 struct macho_routines_command
: public routines_command_64
{};
58 #define LC_SEGMENT_COMMAND LC_SEGMENT
59 #define LC_ROUTINES_COMMAND LC_ROUTINES
60 struct macho_segment_command
: public segment_command
{};
61 struct macho_section
: public section
{};
62 struct macho_routines_command
: public routines_command
{};
66 // create image for main executable
67 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
,
68 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
70 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
72 // set slide for PIE programs
73 image
->setSlide(slide
);
75 // for PIE record end of program, to know where to start loading dylibs
77 fgNextPIEDylibAddress
= (uintptr_t)image
->getEnd();
79 image
->disableCoverageCheck();
80 image
->instantiateFinish(context
);
81 image
->setMapped(context
);
83 if ( context
.verboseMapping
) {
84 dyld::log("dyld: Main executable mapped %s\n", path
);
85 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
86 const char* name
= image
->segName(i
);
87 if ( (strcmp(name
, "__PAGEZERO") == 0) || (strcmp(name
, "__UNIXSTACK") == 0) )
88 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segPreferredLoadAddress(i
), image
->segPreferredLoadAddress(i
)+image
->segSize(i
));
90 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
97 // create image by mapping in a mach-o file
98 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromFile(const char* path
, int fd
, const uint8_t* fileData
, size_t lenFileData
,
99 uint64_t offsetInFat
, uint64_t lenInFat
, const struct stat
& info
,
100 unsigned int segCount
, unsigned int libCount
,
101 const struct linkedit_data_command
* codeSigCmd
,
102 const struct encryption_info_command
* encryptCmd
,
103 const LinkContext
& context
)
105 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart((macho_header
*)fileData
, path
, segCount
, libCount
);
108 // record info about file
109 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
111 // if this image is code signed, let kernel validate signature before mapping any pages from image
112 image
->loadCodeSignature(codeSigCmd
, fd
, offsetInFat
, context
);
114 // Validate that first data we read with pread actually matches with code signature
115 image
->validateFirstPages(codeSigCmd
, fd
, fileData
, lenFileData
, offsetInFat
, context
);
118 image
->mapSegments(fd
, offsetInFat
, lenInFat
, info
.st_size
, context
);
120 // if framework is FairPlay encrypted, register with kernel
121 image
->registerEncryption(encryptCmd
, context
);
123 // probe to see if code signed correctly
124 image
->crashIfInvalidCodeSignature();
126 // finish construction
127 image
->instantiateFinish(context
);
129 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
130 const char* installName
= image
->getInstallPath();
131 if ( (installName
!= NULL
) && (strcmp(installName
, path
) == 0) && (path
[0] == '/') )
132 image
->setPathUnowned(installName
);
133 #if __MAC_OS_X_VERSION_MIN_REQUIRED
134 // <rdar://problem/6563887> app crashes when libSystem cannot be found
135 else if ( (installName
!= NULL
) && (strcmp(path
, "/usr/lib/libgcc_s.1.dylib") == 0) && (strcmp(installName
, "/usr/lib/libSystem.B.dylib") == 0) )
136 image
->setPathUnowned("/usr/lib/libSystem.B.dylib");
138 else if ( (path
[0] != '/') || (strstr(path
, "../") != NULL
) ) {
139 // rdar://problem/10733082 Fix up @rpath based paths during introspection
140 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
141 char realPath
[MAXPATHLEN
];
142 if ( fcntl(fd
, F_GETPATH
, realPath
) == 0 )
143 image
->setPaths(path
, realPath
);
145 image
->setPath(path
);
148 image
->setPath(path
);
150 // make sure path is stable before recording in dyld_all_image_infos
151 image
->setMapped(context
);
153 // pre-fetch content of __DATA and __LINKEDIT segment for faster launches
154 // don't do this on prebound images or if prefetching is disabled
155 if ( !context
.preFetchDisabled
&& !image
->isPrebindable()) {
156 image
->preFetchDATA(fd
, offsetInFat
, context
);
157 image
->markSequentialLINKEDIT(context
);
161 // ImageLoader::setMapped() can throw an exception to block loading of image
162 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
170 // create image by using cached mach-o file
171 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromCache(const macho_header
* mh
, const char* path
, long slide
,
172 const struct stat
& info
, unsigned int segCount
,
173 unsigned int libCount
, const LinkContext
& context
)
175 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, path
, segCount
, libCount
);
177 // record info about file
178 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
180 // remember this is from shared cache and cannot be unloaded
181 image
->fInSharedCache
= true;
182 image
->setNeverUnload();
183 image
->setSlide(slide
);
184 image
->disableCoverageCheck();
186 // segments already mapped in cache
187 if ( context
.verboseMapping
) {
188 dyld::log("dyld: Using shared cached for %s\n", path
);
189 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
190 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
194 image
->instantiateFinish(context
);
195 image
->setMapped(context
);
198 // ImageLoader::setMapped() can throw an exception to block loading of image
199 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
207 // create image by copying an in-memory mach-o file
208 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
209 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
211 ImageLoaderMachOCompressed
* image
= ImageLoaderMachOCompressed::instantiateStart(mh
, moduleName
, segCount
, libCount
);
214 if ( mh
->filetype
== MH_EXECUTE
)
215 throw "can't load another MH_EXECUTE";
218 image
->mapSegments((const void*)mh
, len
, context
);
220 // for compatibility, never unload dylibs loaded from memory
221 image
->setNeverUnload();
223 image
->disableCoverageCheck();
225 // bundle loads need path copied
226 if ( moduleName
!= NULL
)
227 image
->setPath(moduleName
);
229 image
->instantiateFinish(context
);
230 image
->setMapped(context
);
233 // ImageLoader::setMapped() can throw an exception to block loading of image
234 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
243 ImageLoaderMachOCompressed::ImageLoaderMachOCompressed(const macho_header
* mh
, const char* path
, unsigned int segCount
,
244 uint32_t segOffsets
[], unsigned int libCount
)
245 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fDyldInfo(NULL
)
249 ImageLoaderMachOCompressed::~ImageLoaderMachOCompressed()
251 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
257 // construct ImageLoaderMachOCompressed using "placement new" with SegmentMachO objects array at end
258 ImageLoaderMachOCompressed
* ImageLoaderMachOCompressed::instantiateStart(const macho_header
* mh
, const char* path
,
259 unsigned int segCount
, unsigned int libCount
)
261 size_t size
= sizeof(ImageLoaderMachOCompressed
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
262 ImageLoaderMachOCompressed
* allocatedSpace
= static_cast<ImageLoaderMachOCompressed
*>(malloc(size
));
263 if ( allocatedSpace
== NULL
)
264 throw "malloc failed";
265 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOCompressed
)));
266 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
267 return new (allocatedSpace
) ImageLoaderMachOCompressed(mh
, path
, segCount
, segOffsets
, libCount
);
271 // common code to finish initializing object
272 void ImageLoaderMachOCompressed::instantiateFinish(const LinkContext
& context
)
274 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
275 this->parseLoadCmds(context
);
278 uint32_t* ImageLoaderMachOCompressed::segmentCommandOffsets() const
280 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
)));
284 ImageLoader
* ImageLoaderMachOCompressed::libImage(unsigned int libIndex
) const
286 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
288 return (ImageLoader
*)(images
[libIndex
] & (-4));
291 bool ImageLoaderMachOCompressed::libReExported(unsigned int libIndex
) const
293 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
294 // re-export flag is low bit
295 return ((images
[libIndex
] & 1) != 0);
298 bool ImageLoaderMachOCompressed::libIsUpward(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 second bit
302 return ((images
[libIndex
] & 2) != 0);
306 void ImageLoaderMachOCompressed::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
, bool upward
)
308 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOCompressed
) + fSegmentsCount
*sizeof(uint32_t)));
309 uintptr_t value
= (uintptr_t)image
;
314 images
[libIndex
] = value
;
318 void ImageLoaderMachOCompressed::markFreeLINKEDIT(const LinkContext
& context
)
320 // mark that we are done with rebase and bind info
321 markLINKEDIT(context
, MADV_FREE
);
324 void ImageLoaderMachOCompressed::markSequentialLINKEDIT(const LinkContext
& context
)
326 // mark the rebase and bind info and using sequential access
327 markLINKEDIT(context
, MADV_SEQUENTIAL
);
330 void ImageLoaderMachOCompressed::markLINKEDIT(const LinkContext
& context
, int advise
)
332 // if not loaded at preferred address, mark rebase info
334 if ( (fSlide
!= 0) && (fDyldInfo
->rebase_size
!= 0) )
335 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
;
336 else if ( fDyldInfo
->bind_off
!= 0 )
337 start
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
;
339 return; // no binding info to prefetch
341 // end is at end of bind info
343 if ( fDyldInfo
->bind_off
!= 0 )
344 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->bind_off
+ fDyldInfo
->bind_size
;
345 else if ( fDyldInfo
->rebase_off
!= 0 )
346 end
= (uintptr_t)fLinkEditBase
+ fDyldInfo
->rebase_off
+ fDyldInfo
->rebase_size
;
351 // round to whole pages
352 start
= dyld_page_trunc(start
);
353 end
= dyld_page_round(end
);
355 // do nothing if only one page of rebase/bind info
356 if ( (end
-start
) <= dyld_page_size
)
359 // tell kernel about our access to these pages
360 madvise((void*)start
, end
-start
, advise
);
361 if ( context
.verboseMapping
) {
362 const char* adstr
= "sequential";
363 if ( advise
== MADV_FREE
)
365 dyld::log("%18s %s 0x%0lX -> 0x%0lX for %s\n", "__LINKEDIT", adstr
, start
, end
-1, this->getPath());
371 void ImageLoaderMachOCompressed::rebaseAt(const LinkContext
& context
, uintptr_t addr
, uintptr_t slide
, uint8_t type
)
373 if ( context
.verboseRebase
) {
374 dyld::log("dyld: rebase: %s:*0x%08lX += 0x%08lX\n", this->getShortName(), (uintptr_t)addr
, slide
);
376 //dyld::log("0x%08lX type=%d\n", addr, type);
377 uintptr_t* locationToFix
= (uintptr_t*)addr
;
379 case REBASE_TYPE_POINTER
:
380 *locationToFix
+= slide
;
382 case REBASE_TYPE_TEXT_ABSOLUTE32
:
383 *locationToFix
+= slide
;
386 dyld::throwf("bad rebase type %d", type
);
390 void ImageLoaderMachOCompressed::throwBadRebaseAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
391 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
393 dyld::throwf("malformed rebase opcodes (%ld/%ld): address 0x%08lX is outside of segment %s (0x%08lX -> 0x%08lX)",
394 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
395 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
398 void ImageLoaderMachOCompressed::rebase(const LinkContext
& context
, uintptr_t slide
)
400 CRSetCrashLogMessage2(this->getPath());
401 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->rebase_off
;
402 const uint8_t* const end
= &start
[fDyldInfo
->rebase_size
];
403 const uint8_t* p
= start
;
407 int segmentIndex
= 0;
408 uintptr_t address
= segActualLoadAddress(0);
409 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
410 uintptr_t segmentEndAddress
= segActualEndAddress(0);
414 while ( !done
&& (p
< end
) ) {
415 uint8_t immediate
= *p
& REBASE_IMMEDIATE_MASK
;
416 uint8_t opcode
= *p
& REBASE_OPCODE_MASK
;
419 case REBASE_OPCODE_DONE
:
422 case REBASE_OPCODE_SET_TYPE_IMM
:
425 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
426 segmentIndex
= immediate
;
427 if ( segmentIndex
>= fSegmentsCount
)
428 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
429 segmentIndex
, fSegmentsCount
-1);
430 #if TEXT_RELOC_SUPPORT
431 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
433 if ( !segWriteable(segmentIndex
) )
435 dyld::throwf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not a writable segment (%s)",
436 segmentIndex
, segName(segmentIndex
));
437 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
438 segmentEndAddress
= segActualEndAddress(segmentIndex
);
439 address
= segmentStartAddress
+ read_uleb128(p
, end
);
441 case REBASE_OPCODE_ADD_ADDR_ULEB
:
442 address
+= read_uleb128(p
, end
);
444 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED
:
445 address
+= immediate
*sizeof(uintptr_t);
447 case REBASE_OPCODE_DO_REBASE_IMM_TIMES
:
448 for (int i
=0; i
< immediate
; ++i
) {
449 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
450 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
451 rebaseAt(context
, address
, slide
, type
);
452 address
+= sizeof(uintptr_t);
454 fgTotalRebaseFixups
+= immediate
;
456 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES
:
457 count
= read_uleb128(p
, end
);
458 for (uint32_t i
=0; i
< count
; ++i
) {
459 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
460 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
461 rebaseAt(context
, address
, slide
, type
);
462 address
+= sizeof(uintptr_t);
464 fgTotalRebaseFixups
+= count
;
466 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB
:
467 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
468 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
469 rebaseAt(context
, address
, slide
, type
);
470 address
+= read_uleb128(p
, end
) + sizeof(uintptr_t);
471 ++fgTotalRebaseFixups
;
473 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
:
474 count
= read_uleb128(p
, end
);
475 skip
= read_uleb128(p
, end
);
476 for (uint32_t i
=0; i
< count
; ++i
) {
477 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
478 throwBadRebaseAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
479 rebaseAt(context
, address
, slide
, type
);
480 address
+= skip
+ sizeof(uintptr_t);
482 fgTotalRebaseFixups
+= count
;
485 dyld::throwf("bad rebase opcode %d", *p
);
489 catch (const char* msg
) {
490 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
494 CRSetCrashLogMessage2(NULL
);
497 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::findShallowExportedSymbol(const char* symbol
, const ImageLoader
** foundIn
) const
499 //dyld::log("Compressed::findExportedSymbol(%s) in %s\n", symbol, this->getShortName());
500 if ( fDyldInfo
->export_size
== 0 )
503 dyld::logBindings("%s: %s\n", this->getShortName(), symbol
);
505 ++ImageLoaderMachO::fgSymbolTrieSearchs
;
506 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
507 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
508 const uint8_t* foundNodeStart
= this->trieWalk(start
, end
, symbol
);
509 if ( foundNodeStart
!= NULL
) {
510 const uint8_t* p
= foundNodeStart
;
511 const uintptr_t flags
= read_uleb128(p
, end
);
512 // found match, return pointer to terminal part of node
513 if ( flags
& EXPORT_SYMBOL_FLAGS_REEXPORT
) {
514 // re-export from another dylib, lookup there
515 const uintptr_t ordinal
= read_uleb128(p
, end
);
516 const char* importedName
= (char*)p
;
517 if ( importedName
[0] == '\0' )
518 importedName
= symbol
;
519 if ( (ordinal
> 0) && (ordinal
<= libraryCount()) ) {
520 const ImageLoader
* reexportedFrom
= libImage((unsigned int)ordinal
-1);
521 //dyld::log("Compressed::findExportedSymbol(), %s -> %s/%s\n", symbol, reexportedFrom->getShortName(), importedName);
522 const char* reExportLibPath
= libPath((unsigned int)ordinal
-1);
523 return reexportedFrom
->findExportedSymbol(importedName
, true, reExportLibPath
, foundIn
);
526 //dyld::throwf("bad mach-o binary, library ordinal (%u) invalid (max %u) for re-exported symbol %s in %s",
527 // ordinal, libraryCount(), symbol, this->getPath());
531 //dyld::log("findExportedSymbol(%s) in %s found match, returning %p\n", symbol, this->getShortName(), p);
532 if ( foundIn
!= NULL
)
533 *foundIn
= (ImageLoader
*)this;
534 // return pointer to terminal part of node
535 return (Symbol
*)foundNodeStart
;
542 bool ImageLoaderMachOCompressed::containsSymbol(const void* addr
) const
544 const uint8_t* start
= &fLinkEditBase
[fDyldInfo
->export_off
];
545 const uint8_t* end
= &start
[fDyldInfo
->export_size
];
546 return ( (start
<= addr
) && (addr
< end
) );
550 uintptr_t ImageLoaderMachOCompressed::exportedSymbolAddress(const LinkContext
& context
, const Symbol
* symbol
, const ImageLoader
* requestor
, bool runResolver
) const
552 const uint8_t* exportNode
= (uint8_t*)symbol
;
553 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
554 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
555 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
556 throw "symbol is not in trie";
557 //dyld::log("exportedSymbolAddress(): node=%p, nodeOffset=0x%04X in %s\n", symbol, (int)((uint8_t*)symbol - exportTrieStart), this->getShortName());
558 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
559 switch ( flags
& EXPORT_SYMBOL_FLAGS_KIND_MASK
) {
560 case EXPORT_SYMBOL_FLAGS_KIND_REGULAR
:
561 if ( runResolver
&& (flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
) ) {
562 // this node has a stub and resolver, run the resolver to get target address
563 uintptr_t stub
= read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
; // skip over stub
564 // <rdar://problem/10657737> interposing dylibs have the stub address as their replacee
565 uintptr_t interposedStub
= interposedAddress(context
, stub
, requestor
);
566 if ( interposedStub
!= stub
)
567 return interposedStub
;
568 // stub was not interposed, so run resolver
569 typedef uintptr_t (*ResolverProc
)(void);
570 ResolverProc resolver
= (ResolverProc
)(read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
);
571 uintptr_t result
= (*resolver
)();
572 if ( context
.verboseBind
)
573 dyld::log("dyld: resolver at %p returned 0x%08lX\n", resolver
, result
);
576 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
577 case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
:
578 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
579 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
580 return read_uleb128(exportNode
, exportTrieEnd
) + (uintptr_t)fMachOData
;
581 case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
:
582 if ( flags
& EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
)
583 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
584 return read_uleb128(exportNode
, exportTrieEnd
);
586 dyld::throwf("unsupported exported symbol kind. flags=%lu at node=%p", flags
, symbol
);
590 bool ImageLoaderMachOCompressed::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
592 const uint8_t* exportNode
= (uint8_t*)symbol
;
593 const uint8_t* exportTrieStart
= fLinkEditBase
+ fDyldInfo
->export_off
;
594 const uint8_t* exportTrieEnd
= exportTrieStart
+ fDyldInfo
->export_size
;
595 if ( (exportNode
< exportTrieStart
) || (exportNode
> exportTrieEnd
) )
596 throw "symbol is not in trie";
597 uintptr_t flags
= read_uleb128(exportNode
, exportTrieEnd
);
598 return ( flags
& EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
);
602 const char* ImageLoaderMachOCompressed::exportedSymbolName(const Symbol
* symbol
) const
604 throw "NSNameOfSymbol() not supported with compressed LINKEDIT";
607 unsigned int ImageLoaderMachOCompressed::exportedSymbolCount() const
609 throw "NSSymbolDefinitionCountInObjectFileImage() not supported with compressed LINKEDIT";
612 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::exportedSymbolIndexed(unsigned int index
) const
614 throw "NSSymbolDefinitionNameInObjectFileImage() not supported with compressed LINKEDIT";
617 unsigned int ImageLoaderMachOCompressed::importedSymbolCount() const
619 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
622 const ImageLoader::Symbol
* ImageLoaderMachOCompressed::importedSymbolIndexed(unsigned int index
) const
624 throw "NSSymbolReferenceCountInObjectFileImage() not supported with compressed LINKEDIT";
627 const char* ImageLoaderMachOCompressed::importedSymbolName(const Symbol
* symbol
) const
629 throw "NSSymbolReferenceNameInObjectFileImage() not supported with compressed LINKEDIT";
634 uintptr_t ImageLoaderMachOCompressed::resolveFlat(const LinkContext
& context
, const char* symbolName
, bool weak_import
,
635 bool runResolver
, const ImageLoader
** foundIn
)
638 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
639 if ( *foundIn
!= this )
640 context
.addDynamicReference(this, const_cast<ImageLoader
*>(*foundIn
));
641 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
643 // if a bundle is loaded privately the above will not find its exports
644 if ( this->isBundle() && this->hasHiddenExports() ) {
645 // look in self for needed symbol
646 sym
= this->findShallowExportedSymbol(symbolName
, foundIn
);
648 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this, runResolver
);
651 // definition can't be found anywhere, ok because it is weak, just return 0
654 throwSymbolNotFound(context
, symbolName
, this->getPath(), "", "flat namespace");
658 uintptr_t ImageLoaderMachOCompressed::resolveTwolevel(const LinkContext
& context
, const char* symbolName
, const ImageLoader
* definedInImage
,
659 const ImageLoader
* requestorImage
, unsigned requestorOrdinalOfDef
, bool weak_import
, bool runResolver
,
660 const ImageLoader
** foundIn
)
664 if ( definedInImage
->findExportedSymbolAddress(context
, symbolName
, requestorImage
, requestorOrdinalOfDef
, runResolver
, foundIn
, &address
) )
668 // definition can't be found anywhere, ok because it is weak, just return 0
672 // nowhere to be found, check if maybe this image is too new for this OS
673 char versMismatch
[256];
674 versMismatch
[0] = '\0';
675 uint32_t imageMinOS
= this->minOSVersion();
676 // dyld is always built for the current OS, so we can get the current OS version
677 // from the load command in dyld itself.
678 extern const mach_header __dso_handle
;
679 uint32_t dyldMinOS
= ImageLoaderMachO::minOSVersion(&__dso_handle
);
680 if ( imageMinOS
> dyldMinOS
) {
681 #if __MAC_OS_X_VERSION_MIN_REQUIRED
682 const char* msg
= dyld::mkstringf(" (which was built for Mac OS X %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
684 const char* msg
= dyld::mkstringf(" (which was built for iOS %d.%d)", imageMinOS
>> 16, (imageMinOS
>> 8) & 0xFF);
686 strcpy(versMismatch
, msg
);
689 throwSymbolNotFound(context
, symbolName
, this->getPath(), versMismatch
, definedInImage
->getPath());
693 uintptr_t ImageLoaderMachOCompressed::resolve(const LinkContext
& context
, const char* symbolName
,
694 uint8_t symboFlags
, long libraryOrdinal
, const ImageLoader
** targetImage
,
695 LastLookup
* last
, bool runResolver
)
699 // only clients that benefit from caching last lookup pass in a LastLookup struct
700 if ( last
!= NULL
) {
701 if ( (last
->ordinal
== libraryOrdinal
)
702 && (last
->flags
== symboFlags
)
703 && (last
->name
== symbolName
) ) {
704 *targetImage
= last
->foundIn
;
709 bool weak_import
= (symboFlags
& BIND_SYMBOL_FLAGS_WEAK_IMPORT
);
710 uintptr_t symbolAddress
;
711 if ( context
.bindFlat
|| (libraryOrdinal
== BIND_SPECIAL_DYLIB_FLAT_LOOKUP
) ) {
712 symbolAddress
= this->resolveFlat(context
, symbolName
, weak_import
, runResolver
, targetImage
);
715 if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE
) {
716 *targetImage
= context
.mainExecutable
;
718 else if ( libraryOrdinal
== BIND_SPECIAL_DYLIB_SELF
) {
721 else if ( libraryOrdinal
<= 0 ) {
722 dyld::throwf("bad mach-o binary, unknown special library ordinal (%ld) too big for symbol %s in %s",
723 libraryOrdinal
, symbolName
, this->getPath());
725 else if ( (unsigned)libraryOrdinal
<= libraryCount() ) {
726 *targetImage
= libImage((unsigned int)libraryOrdinal
-1);
729 dyld::throwf("bad mach-o binary, library ordinal (%ld) too big (max %u) for symbol %s in %s",
730 libraryOrdinal
, libraryCount(), symbolName
, this->getPath());
732 if ( *targetImage
== NULL
) {
734 // if target library not loaded and reference is weak or library is weak return 0
738 dyld::throwf("can't resolve symbol %s in %s because dependent dylib #%ld could not be loaded",
739 symbolName
, this->getPath(), libraryOrdinal
);
743 symbolAddress
= resolveTwolevel(context
, symbolName
, *targetImage
, this, (unsigned)libraryOrdinal
, weak_import
, runResolver
, targetImage
);
747 // save off lookup results if client wants
748 if ( last
!= NULL
) {
749 last
->ordinal
= libraryOrdinal
;
750 last
->flags
= symboFlags
;
751 last
->name
= symbolName
;
752 last
->foundIn
= *targetImage
;
753 last
->result
= symbolAddress
;
756 return symbolAddress
;
759 uintptr_t ImageLoaderMachOCompressed::bindAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
760 uint8_t symbolFlags
, intptr_t addend
, long libraryOrdinal
, const char* msg
,
761 LastLookup
* last
, bool runResolver
)
763 const ImageLoader
* targetImage
;
764 uintptr_t symbolAddress
;
767 symbolAddress
= this->resolve(context
, symbolName
, symbolFlags
, libraryOrdinal
, &targetImage
, last
, runResolver
);
770 return this->bindLocation(context
, addr
, symbolAddress
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, msg
);
774 void ImageLoaderMachOCompressed::throwBadBindingAddress(uintptr_t address
, uintptr_t segmentEndAddress
, int segmentIndex
,
775 const uint8_t* startOpcodes
, const uint8_t* endOpcodes
, const uint8_t* pos
)
777 dyld::throwf("malformed binding opcodes (%ld/%ld): address 0x%08lX is outside segment %s (0x%08lX -> 0x%08lX)",
778 (intptr_t)(pos
-startOpcodes
), (intptr_t)(endOpcodes
-startOpcodes
), address
, segName(segmentIndex
),
779 segActualLoadAddress(segmentIndex
), segmentEndAddress
);
783 void ImageLoaderMachOCompressed::doBind(const LinkContext
& context
, bool forceLazysBound
)
785 CRSetCrashLogMessage2(this->getPath());
787 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
788 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
789 if ( this->usablePrebinding(context
) ) {
790 // don't need to bind
793 uint64_t t0
= mach_absolute_time();
795 #if TEXT_RELOC_SUPPORT
796 // if there are __TEXT fixups, temporarily make __TEXT writable
797 if ( fTextSegmentBinds
)
798 this->makeTextSegmentWritable(context
, true);
801 // run through all binding opcodes
802 eachBind(context
, &ImageLoaderMachOCompressed::bindAt
);
804 #if TEXT_RELOC_SUPPORT
805 // if there were __TEXT fixups, restore write protection
806 if ( fTextSegmentBinds
)
807 this->makeTextSegmentWritable(context
, false);
810 // if this image is in the shared cache, but depends on something no longer in the shared cache,
811 // there is no way to reset the lazy pointers, so force bind them now
812 if ( forceLazysBound
|| fInSharedCache
)
813 this->doBindJustLazies(context
);
815 // this image is in cache, but something below it is not. If
816 // this image has lazy pointer to a resolver function, then
817 // the stub may have been altered to point to a shared lazy pointer.
818 if ( fInSharedCache
)
819 this->updateOptimizedLazyPointers(context
);
821 // tell kernel we are done with chunks of LINKEDIT
822 if ( !context
.preFetchDisabled
)
823 this->markFreeLINKEDIT(context
);
825 uint64_t t1
= mach_absolute_time();
826 ImageLoader::fgTotalRebindCacheTime
+= (t1
-t0
);
829 // set up dyld entry points in image
830 // do last so flat main executables will have __dyld or __program_vars set up
831 this->setupLazyPointerHandler(context
);
832 CRSetCrashLogMessage2(NULL
);
836 void ImageLoaderMachOCompressed::doBindJustLazies(const LinkContext
& context
)
838 eachLazyBind(context
, &ImageLoaderMachOCompressed::bindAt
);
841 void ImageLoaderMachOCompressed::eachBind(const LinkContext
& context
, bind_handler handler
)
845 int segmentIndex
= -1;
846 uintptr_t address
= segActualLoadAddress(0);
847 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
848 uintptr_t segmentEndAddress
= segActualEndAddress(0);
849 const char* symbolName
= NULL
;
850 uint8_t symboFlags
= 0;
851 bool libraryOrdinalSet
= false;
852 long libraryOrdinal
= 0;
857 LastLookup last
= { 0, 0, NULL
, 0, NULL
};
858 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->bind_off
;
859 const uint8_t* const end
= &start
[fDyldInfo
->bind_size
];
860 const uint8_t* p
= start
;
862 while ( !done
&& (p
< end
) ) {
863 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
864 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
867 case BIND_OPCODE_DONE
:
870 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
871 libraryOrdinal
= immediate
;
872 libraryOrdinalSet
= true;
874 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
875 libraryOrdinal
= read_uleb128(p
, end
);
876 libraryOrdinalSet
= true;
878 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
879 // the special ordinals are negative numbers
880 if ( immediate
== 0 )
883 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
884 libraryOrdinal
= signExtended
;
886 libraryOrdinalSet
= true;
888 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
889 symbolName
= (char*)p
;
890 symboFlags
= immediate
;
895 case BIND_OPCODE_SET_TYPE_IMM
:
898 case BIND_OPCODE_SET_ADDEND_SLEB
:
899 addend
= read_sleb128(p
, end
);
901 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
902 segmentIndex
= immediate
;
903 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
904 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
905 segmentIndex
, fSegmentsCount
-1);
906 #if TEXT_RELOC_SUPPORT
907 if ( !segWriteable(segmentIndex
) && !segHasRebaseFixUps(segmentIndex
) && !segHasBindFixUps(segmentIndex
) )
909 if ( !segWriteable(segmentIndex
) )
911 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
912 segOffset
= read_uleb128(p
, end
);
913 if ( segOffset
> segSize(segmentIndex
) )
914 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
915 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
916 address
= segmentStartAddress
+ segOffset
;
917 segmentEndAddress
= segActualEndAddress(segmentIndex
);
919 case BIND_OPCODE_ADD_ADDR_ULEB
:
920 address
+= read_uleb128(p
, end
);
922 case BIND_OPCODE_DO_BIND
:
923 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
924 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
925 if ( symbolName
== NULL
)
926 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
927 if ( segmentIndex
== -1 )
928 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
929 if ( !libraryOrdinalSet
)
930 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
931 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
932 address
+= sizeof(intptr_t);
934 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
935 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
936 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
937 if ( symbolName
== NULL
)
938 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
939 if ( segmentIndex
== -1 )
940 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
941 if ( !libraryOrdinalSet
)
942 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
943 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
944 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
946 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
947 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
948 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
949 if ( symbolName
== NULL
)
950 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
951 if ( segmentIndex
== -1 )
952 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
953 if ( !libraryOrdinalSet
)
954 dyld::throwf("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
955 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
956 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
958 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
959 if ( symbolName
== NULL
)
960 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
961 if ( segmentIndex
== -1 )
962 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
963 count
= read_uleb128(p
, end
);
964 if ( !libraryOrdinalSet
)
965 dyld::throwf("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL*");
966 skip
= read_uleb128(p
, end
);
967 for (uint32_t i
=0; i
< count
; ++i
) {
968 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
969 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
970 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "", &last
, false);
971 address
+= skip
+ sizeof(intptr_t);
975 dyld::throwf("bad bind opcode %d in bind info", *p
);
979 catch (const char* msg
) {
980 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
986 void ImageLoaderMachOCompressed::eachLazyBind(const LinkContext
& context
, bind_handler handler
)
989 uint8_t type
= BIND_TYPE_POINTER
;
990 int segmentIndex
= -1;
991 uintptr_t address
= segActualLoadAddress(0);
992 uintptr_t segmentStartAddress
= segActualLoadAddress(0);
993 uintptr_t segmentEndAddress
= segActualEndAddress(0);
995 const char* symbolName
= NULL
;
996 uint8_t symboFlags
= 0;
997 long libraryOrdinal
= 0;
999 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1000 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1001 const uint8_t* p
= start
;
1003 while ( !done
&& (p
< end
) ) {
1004 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1005 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1008 case BIND_OPCODE_DONE
:
1009 // there is BIND_OPCODE_DONE at end of each lazy bind, don't stop until end of whole sequence
1011 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM
:
1012 libraryOrdinal
= immediate
;
1014 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB
:
1015 libraryOrdinal
= read_uleb128(p
, end
);
1017 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM
:
1018 // the special ordinals are negative numbers
1019 if ( immediate
== 0 )
1022 int8_t signExtended
= BIND_OPCODE_MASK
| immediate
;
1023 libraryOrdinal
= signExtended
;
1026 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1027 symbolName
= (char*)p
;
1028 symboFlags
= immediate
;
1033 case BIND_OPCODE_SET_TYPE_IMM
:
1036 case BIND_OPCODE_SET_ADDEND_SLEB
:
1037 addend
= read_sleb128(p
, end
);
1039 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1040 segmentIndex
= immediate
;
1041 if ( (segmentIndex
>= fSegmentsCount
) || (segmentIndex
< 0) )
1042 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is out of range (0..%d)",
1043 segmentIndex
, fSegmentsCount
-1);
1044 if ( !segWriteable(segmentIndex
) )
1045 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is not writable", segmentIndex
);
1046 segOffset
= read_uleb128(p
, end
);
1047 if ( segOffset
> segSize(segmentIndex
) )
1048 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segmentIndex
));
1049 segmentStartAddress
= segActualLoadAddress(segmentIndex
);
1050 segmentEndAddress
= segActualEndAddress(segmentIndex
);
1051 address
= segmentStartAddress
+ segOffset
;
1053 case BIND_OPCODE_ADD_ADDR_ULEB
:
1054 address
+= read_uleb128(p
, end
);
1056 case BIND_OPCODE_DO_BIND
:
1057 if ( segmentIndex
== -1 )
1058 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB");
1059 if ( (address
< segmentStartAddress
) || (address
>= segmentEndAddress
) )
1060 throwBadBindingAddress(address
, segmentEndAddress
, segmentIndex
, start
, end
, p
);
1061 if ( symbolName
== NULL
)
1062 dyld::throwf("BIND_OPCODE_DO_BIND missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM");
1063 (this->*handler
)(context
, address
, type
, symbolName
, symboFlags
, addend
, libraryOrdinal
, "forced lazy ", NULL
, false);
1064 address
+= sizeof(intptr_t);
1066 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1067 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1068 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1070 dyld::throwf("bad lazy bind opcode %d", *p
);
1075 catch (const char* msg
) {
1076 const char* newMsg
= dyld::mkstringf("%s in %s", msg
, this->getPath());
1082 // A program built targeting 10.5 will have hybrid stubs. When used with weak symbols
1083 // the classic lazy loader is used even when running on 10.6
1084 uintptr_t ImageLoaderMachOCompressed::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1086 // only works with compressed LINKEDIT if classic symbol table is also present
1087 const macho_nlist
* symbolTable
= NULL
;
1088 const char* symbolTableStrings
= NULL
;
1089 const dysymtab_command
* dynSymbolTable
= NULL
;
1090 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1091 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1092 const struct load_command
* cmd
= cmds
;
1093 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1097 const struct symtab_command
* symtab
= (struct symtab_command
*)cmd
;
1098 symbolTableStrings
= (const char*)&fLinkEditBase
[symtab
->stroff
];
1099 symbolTable
= (macho_nlist
*)(&fLinkEditBase
[symtab
->symoff
]);
1103 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1106 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1108 // no symbol table => no lookup by address
1109 if ( (symbolTable
== NULL
) || (dynSymbolTable
== NULL
) )
1110 dyld::throwf("classic lazy binding used with compressed LINKEDIT at %p in image %s", lazyPointer
, this->getPath());
1112 // scan for all lazy-pointer sections
1113 const bool twoLevel
= this->usesTwoLevelNameSpace();
1114 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1116 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1118 case LC_SEGMENT_COMMAND
:
1120 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1121 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1122 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1123 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1124 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1125 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1126 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1127 const size_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1128 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1129 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1130 const uint32_t indirectTableOffset
= sect
->reserved1
;
1131 const size_t lazyIndex
= lazyPointer
- symbolPointers
;
1132 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1135 if ( (symbolIndex
!= INDIRECT_SYMBOL_ABS
) && (symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) ) {
1136 const macho_nlist
* symbol
= &symbolTable
[symbolIndex
];
1137 const char* symbolName
= &symbolTableStrings
[symbol
->n_un
.n_strx
];
1138 int libraryOrdinal
= GET_LIBRARY_ORDINAL(symbol
->n_desc
);
1139 if ( !twoLevel
|| context
.bindFlat
)
1140 libraryOrdinal
= BIND_SPECIAL_DYLIB_FLAT_LOOKUP
;
1141 uintptr_t ptrToBind
= (uintptr_t)lazyPointer
;
1142 uintptr_t symbolAddr
= bindAt(context
, ptrToBind
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
);
1143 ++fgTotalLazyBindFixups
;
1150 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1152 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1157 uintptr_t ImageLoaderMachOCompressed::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
,
1158 void (*lock
)(), void (*unlock
)())
1160 // <rdar://problem/8663923> race condition with flat-namespace lazy binding
1161 if ( this->usesTwoLevelNameSpace() ) {
1162 // two-level namespace lookup does not require lock because dependents can't be unloaded before this image
1165 // acquire dyld global lock
1170 const uint8_t* const start
= fLinkEditBase
+ fDyldInfo
->lazy_bind_off
;
1171 const uint8_t* const end
= &start
[fDyldInfo
->lazy_bind_size
];
1173 uintptr_t segOffset
;
1175 const char* symbolName
;
1179 if ( ! getLazyBindingInfo(lazyBindingInfoOffset
, start
, end
, &segIndex
, &segOffset
, &libraryOrdinal
, &symbolName
, &doneAfterBind
) )
1180 dyld::throwf("bad lazy bind info");
1182 if ( segIndex
>= fSegmentsCount
)
1183 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1184 segIndex
, fSegmentsCount
-1);
1185 if ( segOffset
> segSize(segIndex
) )
1186 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(segIndex
));
1187 uintptr_t address
= segActualLoadAddress(segIndex
) + segOffset
;
1188 result
= this->bindAt(context
, address
, BIND_TYPE_POINTER
, symbolName
, 0, 0, libraryOrdinal
, "lazy ", NULL
, true);
1189 // <rdar://problem/24140465> Some old apps had multiple lazy symbols bound at once
1190 } while (!doneAfterBind
&& !context
.strictMachORequired
);
1192 if ( !this->usesTwoLevelNameSpace() ) {
1193 // release dyld global lock
1194 if ( unlock
!= NULL
)
1200 void ImageLoaderMachOCompressed::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
, unsigned)
1203 it
.symbolName
= " ";
1204 it
.loadOrder
= loadOrder
;
1205 it
.weakSymbol
= false;
1206 it
.symbolMatches
= false;
1209 it
.endIndex
= this->fDyldInfo
->weak_bind_size
;
1216 bool ImageLoaderMachOCompressed::incrementCoalIterator(CoalIterator
& it
)
1221 if ( this->fDyldInfo
->weak_bind_size
== 0 ) {
1222 /// hmmm, ld set MH_WEAK_DEFINES or MH_BINDS_TO_WEAK, but there is no weak binding info
1224 it
.symbolName
= "~~~";
1227 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1228 const uint8_t* p
= start
+ it
.curIndex
;
1229 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1232 uintptr_t segOffset
;
1234 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1235 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1238 case BIND_OPCODE_DONE
:
1240 it
.curIndex
= p
- start
;
1241 it
.symbolName
= "~~~"; // sorts to end
1243 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1244 it
.symbolName
= (char*)p
;
1245 it
.weakSymbol
= ((immediate
& BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION
) == 0);
1246 it
.symbolMatches
= false;
1250 it
.curIndex
= p
- start
;
1252 case BIND_OPCODE_SET_TYPE_IMM
:
1253 it
.type
= immediate
;
1255 case BIND_OPCODE_SET_ADDEND_SLEB
:
1256 it
.addend
= read_sleb128(p
, end
);
1258 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1259 if ( immediate
>= fSegmentsCount
)
1260 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1261 immediate
, fSegmentsCount
-1);
1263 // <rdar://problem/23138428> iOS app compatibility
1264 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1265 #elif TEXT_RELOC_SUPPORT
1266 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1267 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1268 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1270 if ( !segWriteable(immediate
) )
1272 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1273 segOffset
= read_uleb128(p
, end
);
1274 if ( segOffset
> segSize(immediate
) )
1275 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1276 it
.address
= segActualLoadAddress(immediate
) + segOffset
;
1278 case BIND_OPCODE_ADD_ADDR_ULEB
:
1279 it
.address
+= read_uleb128(p
, end
);
1281 case BIND_OPCODE_DO_BIND
:
1282 it
.address
+= sizeof(intptr_t);
1284 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1285 it
.address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1287 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1288 it
.address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1290 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1291 count
= read_uleb128(p
, end
);
1292 skip
= read_uleb128(p
, end
);
1293 for (uint32_t i
=0; i
< count
; ++i
) {
1294 it
.address
+= skip
+ sizeof(intptr_t);
1298 dyld::throwf("bad weak bind opcode '%d' found after processing %d bytes in '%s'", *p
, (int)(p
-start
), this->getPath());
1301 /// hmmm, BIND_OPCODE_DONE is missing...
1303 it
.symbolName
= "~~~";
1304 //dyld::log("missing BIND_OPCODE_DONE for image %s\n", this->getPath());
1308 uintptr_t ImageLoaderMachOCompressed::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1310 //dyld::log("looking for %s in %s\n", it.symbolName, this->getPath());
1311 const ImageLoader
* foundIn
= NULL
;
1312 const ImageLoader::Symbol
* sym
= this->findShallowExportedSymbol(it
.symbolName
, &foundIn
);
1313 if ( sym
!= NULL
) {
1314 //dyld::log("sym=%p, foundIn=%p\n", sym, foundIn);
1315 return foundIn
->getExportedSymbolAddress(sym
, context
, this);
1321 void ImageLoaderMachOCompressed::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, unsigned targetIndex
, const LinkContext
& context
)
1323 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1324 if ( this->getState() < dyld_image_state_bound
)
1327 const uint8_t* start
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
;
1328 const uint8_t* p
= start
+ it
.curIndex
;
1329 const uint8_t* end
= fLinkEditBase
+ fDyldInfo
->weak_bind_off
+ this->fDyldInfo
->weak_bind_size
;
1331 uint8_t type
= it
.type
;
1332 uintptr_t address
= it
.address
;
1333 const char* symbolName
= it
.symbolName
;
1334 intptr_t addend
= it
.addend
;
1337 uintptr_t segOffset
;
1339 bool boundSomething
= false;
1340 while ( !done
&& (p
< end
) ) {
1341 uint8_t immediate
= *p
& BIND_IMMEDIATE_MASK
;
1342 uint8_t opcode
= *p
& BIND_OPCODE_MASK
;
1345 case BIND_OPCODE_DONE
:
1348 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
:
1351 case BIND_OPCODE_SET_TYPE_IMM
:
1354 case BIND_OPCODE_SET_ADDEND_SLEB
:
1355 addend
= read_sleb128(p
, end
);
1357 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
:
1358 if ( immediate
>= fSegmentsCount
)
1359 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment %d which is too large (0..%d)",
1360 immediate
, fSegmentsCount
-1);
1362 // <rdar://problem/23138428> iOS app compatibility
1363 if ( !segWriteable(immediate
) && it
.image
->isPositionIndependentExecutable() )
1364 #elif TEXT_RELOC_SUPPORT
1365 // <rdar://problem/23479396&23590867> i386 OS X app compatibility
1366 if ( !segWriteable(immediate
) && !segHasRebaseFixUps(immediate
) && !segHasBindFixUps(immediate
)
1367 && (!it
.image
->isExecutable() || it
.image
->isPositionIndependentExecutable()) )
1369 if ( !segWriteable(immediate
) )
1371 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB targets segment %s which is not writable", segName(immediate
));
1372 segOffset
= read_uleb128(p
, end
);
1373 if ( segOffset
> segSize(immediate
) )
1374 dyld::throwf("BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has offset 0x%08lX beyond segment size (0x%08lX)", segOffset
, segSize(immediate
));
1375 address
= segActualLoadAddress(immediate
) + segOffset
;
1377 case BIND_OPCODE_ADD_ADDR_ULEB
:
1378 address
+= read_uleb128(p
, end
);
1380 case BIND_OPCODE_DO_BIND
:
1381 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1382 boundSomething
= true;
1383 address
+= sizeof(intptr_t);
1385 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB
:
1386 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1387 boundSomething
= true;
1388 address
+= read_uleb128(p
, end
) + sizeof(intptr_t);
1390 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED
:
1391 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1392 boundSomething
= true;
1393 address
+= immediate
*sizeof(intptr_t) + sizeof(intptr_t);
1395 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
:
1396 count
= read_uleb128(p
, end
);
1397 skip
= read_uleb128(p
, end
);
1398 for (uint32_t i
=0; i
< count
; ++i
) {
1399 bindLocation(context
, address
, value
, type
, symbolName
, addend
, this->getPath(), targetImage
? targetImage
->getPath() : NULL
, "weak ");
1400 boundSomething
= true;
1401 address
+= skip
+ sizeof(intptr_t);
1405 dyld::throwf("bad bind opcode %d in weak binding info", *p
);
1408 // C++ weak coalescing cannot be tracked by reference counting. Error on side of never unloading.
1409 if ( boundSomething
&& (targetImage
!= this) )
1410 context
.addDynamicReference(this, targetImage
);
1413 uintptr_t ImageLoaderMachOCompressed::interposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char*,
1414 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1416 if ( type
== BIND_TYPE_POINTER
) {
1417 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1418 uintptr_t curValue
= *fixupLocation
;
1419 uintptr_t newValue
= interposedAddress(context
, curValue
, this);
1420 if ( newValue
!= curValue
) {
1421 *fixupLocation
= newValue
;
1427 void ImageLoaderMachOCompressed::doInterpose(const LinkContext
& context
)
1429 if ( context
.verboseInterposing
)
1430 dyld::log("dyld: interposing %lu tuples onto image: %s\n", fgInterposingTuples
.size(), this->getPath());
1432 // update prebound symbols
1433 eachBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1434 eachLazyBind(context
, &ImageLoaderMachOCompressed::interposeAt
);
1438 uintptr_t ImageLoaderMachOCompressed::dynamicInterposeAt(const LinkContext
& context
, uintptr_t addr
, uint8_t type
, const char* symbolName
,
1439 uint8_t, intptr_t, long, const char*, LastLookup
*, bool runResolver
)
1441 if ( type
== BIND_TYPE_POINTER
) {
1442 uintptr_t* fixupLocation
= (uintptr_t*)addr
;
1443 uintptr_t value
= *fixupLocation
;
1444 // don't apply interposing to table entries.
1445 if ( (context
.dynamicInterposeArray
<= (void*)addr
) && ((void*)addr
< &context
.dynamicInterposeArray
[context
.dynamicInterposeCount
]) )
1447 for(size_t i
=0; i
< context
.dynamicInterposeCount
; ++i
) {
1448 if ( value
== (uintptr_t)context
.dynamicInterposeArray
[i
].replacee
) {
1449 if ( context
.verboseInterposing
) {
1450 dyld::log("dyld: dynamic interposing: at %p replace %p with %p in %s\n",
1451 fixupLocation
, context
.dynamicInterposeArray
[i
].replacee
, context
.dynamicInterposeArray
[i
].replacement
, this->getPath());
1453 *fixupLocation
= (uintptr_t)context
.dynamicInterposeArray
[i
].replacement
;
1460 void ImageLoaderMachOCompressed::dynamicInterpose(const LinkContext
& context
)
1462 if ( context
.verboseInterposing
)
1463 dyld::log("dyld: dynamic interposing %lu tuples onto image: %s\n", context
.dynamicInterposeCount
, this->getPath());
1465 // update already bound references to symbols
1466 eachBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1467 eachLazyBind(context
, &ImageLoaderMachOCompressed::dynamicInterposeAt
);
1470 const char* ImageLoaderMachOCompressed::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1472 return ImageLoaderMachO::findClosestSymbol((mach_header
*)fMachOData
, addr
, closestAddr
);
1476 #if PREBOUND_IMAGE_SUPPORT
1477 void ImageLoaderMachOCompressed::resetPreboundLazyPointers(const LinkContext
& context
)
1479 // no way to back off a prebound compress image
1484 #if __arm__ || __x86_64__
1485 void ImageLoaderMachOCompressed::updateAlternateLazyPointer(uint8_t* stub
, void** originalLazyPointerAddr
, const LinkContext
& context
)
1488 uint32_t* instructions
= (uint32_t*)stub
;
1489 // sanity check this is a stub we understand
1490 if ( (instructions
[0] != 0xe59fc004) || (instructions
[1] != 0xe08fc00c) || (instructions
[2] != 0xe59cf000) )
1493 void** lazyPointerAddr
= (void**)(instructions
[3] + (stub
+ 12));
1496 // sanity check this is a stub we understand
1497 if ( (stub
[0] != 0xFF) || (stub
[1] != 0x25) )
1499 int32_t ripOffset
= *((int32_t*)(&stub
[2]));
1500 void** lazyPointerAddr
= (void**)(ripOffset
+ stub
+ 6);
1503 // if stub does not use original lazy pointer (meaning it was optimized by update_dyld_shared_cache)
1504 if ( lazyPointerAddr
!= originalLazyPointerAddr
) {
1505 // <rdar://problem/12928448> only de-optimization lazy pointers if they are part of shared cache not loaded (because overridden)
1506 const ImageLoader
* lazyPointerImage
= context
.findImageContainingAddress(lazyPointerAddr
);
1507 if ( lazyPointerImage
!= NULL
)
1510 // copy newly re-bound lazy pointer value to shared lazy pointer
1511 *lazyPointerAddr
= *originalLazyPointerAddr
;
1513 if ( context
.verboseBind
)
1514 dyld::log("dyld: alter bind: %s: *0x%08lX = 0x%08lX \n",
1515 this->getShortName(), (long)lazyPointerAddr
, (long)*originalLazyPointerAddr
);
1521 // <rdar://problem/8890875> overriding shared cache dylibs with resolvers fails
1522 void ImageLoaderMachOCompressed::updateOptimizedLazyPointers(const LinkContext
& context
)
1524 #if __arm__ || __x86_64__
1525 // find stubs and indirect symbol table
1526 const struct macho_section
* stubsSection
= NULL
;
1527 const dysymtab_command
* dynSymbolTable
= NULL
;
1528 const macho_header
* mh
= (macho_header
*)fMachOData
;
1529 const uint32_t cmd_count
= mh
->ncmds
;
1530 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1531 const struct load_command
* cmd
= cmds
;
1532 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1533 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1534 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1535 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1536 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1537 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1538 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1539 if ( type
== S_SYMBOL_STUBS
)
1540 stubsSection
= sect
;
1543 else if ( cmd
->cmd
== LC_DYSYMTAB
) {
1544 dynSymbolTable
= (struct dysymtab_command
*)cmd
;
1546 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1548 if ( dynSymbolTable
== NULL
)
1550 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[dynSymbolTable
->indirectsymoff
];
1551 if ( stubsSection
== NULL
)
1553 const uint32_t stubsSize
= stubsSection
->reserved2
;
1554 const uint32_t stubsCount
= (uint32_t)(stubsSection
->size
/ stubsSize
);
1555 const uint32_t stubsIndirectTableOffset
= stubsSection
->reserved1
;
1556 if ( (stubsIndirectTableOffset
+stubsCount
) > dynSymbolTable
->nindirectsyms
)
1558 uint8_t* const stubsAddr
= (uint8_t*)(stubsSection
->addr
+ this->fSlide
);
1560 // for each lazy pointer section
1562 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1563 if (cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1564 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1565 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1566 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1567 for (const struct macho_section
* lazyPointerSection
=sectionsStart
; lazyPointerSection
< sectionsEnd
; ++lazyPointerSection
) {
1568 const uint8_t type
= lazyPointerSection
->flags
& SECTION_TYPE
;
1569 if ( type
!= S_LAZY_SYMBOL_POINTERS
)
1571 const uint32_t lazyPointersCount
= (uint32_t)(lazyPointerSection
->size
/ sizeof(void*));
1572 const uint32_t lazyPointersIndirectTableOffset
= lazyPointerSection
->reserved1
;
1573 if ( (lazyPointersIndirectTableOffset
+lazyPointersCount
) > dynSymbolTable
->nindirectsyms
)
1575 void** const lazyPointersAddr
= (void**)(lazyPointerSection
->addr
+ this->fSlide
);
1576 // for each lazy pointer
1577 for(uint32_t lpIndex
=0; lpIndex
< lazyPointersCount
; ++lpIndex
) {
1578 const uint32_t lpSymbolIndex
= indirectTable
[lazyPointersIndirectTableOffset
+lpIndex
];
1579 // find matching stub and validate it uses this lazy pointer
1580 for(uint32_t stubIndex
=0; stubIndex
< stubsCount
; ++stubIndex
) {
1581 if ( indirectTable
[stubsIndirectTableOffset
+stubIndex
] == lpSymbolIndex
) {
1582 this->updateAlternateLazyPointer(stubsAddr
+stubIndex
*stubsSize
, &lazyPointersAddr
[lpIndex
], context
);
1590 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1597 void ImageLoaderMachOCompressed::registerEncryption(const encryption_info_command
* encryptCmd
, const LinkContext
& context
)
1599 #if __arm__ || __arm64__
1600 if ( encryptCmd
== NULL
)
1602 const mach_header
* mh
= NULL
;
1603 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
1604 if ( (segFileOffset(i
) == 0) && (segFileSize(i
) != 0) ) {
1605 mh
= (mach_header
*)segActualLoadAddress(i
);
1609 void* start
= ((uint8_t*)mh
) + encryptCmd
->cryptoff
;
1610 size_t len
= encryptCmd
->cryptsize
;
1611 uint32_t cputype
= mh
->cputype
;
1612 uint32_t cpusubtype
= mh
->cpusubtype
;
1613 uint32_t cryptid
= encryptCmd
->cryptid
;
1614 if (context
.verboseMapping
) {
1615 dyld::log(" 0x%08lX->0x%08lX configured for FairPlay decryption\n", (long)start
, (long)start
+len
);
1617 int result
= mremap_encrypted(start
, len
, cryptid
, cputype
, cpusubtype
);
1618 if ( result
!= 0 ) {
1619 dyld::throwf("mremap_encrypted() => %d, errno=%d for %s\n", result
, errno
, this->getPath());