1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-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@
25 // work around until conformance work is complete rdar://problem/4508801
34 #include <sys/types.h>
35 #include <sys/fcntl.h>
38 #include <mach/mach.h>
39 #include <mach/thread_status.h>
40 #include <mach-o/loader.h>
41 #include <mach-o/reloc.h>
42 #include <mach-o/nlist.h>
43 #include <sys/sysctl.h>
44 #include <libkern/OSAtomic.h>
45 #include <libkern/OSCacheControl.h>
47 #if __ppc__ || __ppc64__
48 #include <mach-o/ppc/reloc.h>
51 #include <mach-o/x86_64/reloc.h>
54 #include <mach-o/arm/reloc.h>
57 #include "ImageLoaderMachOClassic.h"
58 #include "mach-o/dyld_images.h"
60 // optimize strcmp for ppc
62 #include <ppc_intrinsics.h>
64 #define astrcmp(a,b) strcmp(a,b)
69 extern "C" void fast_stub_binding_helper_interface();
73 #define POINTER_RELOC X86_64_RELOC_UNSIGNED
75 #define POINTER_RELOC GENERIC_RELOC_VANILLA
79 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
82 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
83 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
84 struct macho_segment_command
: public segment_command_64
{};
85 struct macho_section
: public section_64
{};
86 struct macho_routines_command
: public routines_command_64
{};
89 #define LC_SEGMENT_COMMAND LC_SEGMENT
90 #define LC_ROUTINES_COMMAND LC_ROUTINES
91 struct macho_segment_command
: public segment_command
{};
92 struct macho_section
: public section
{};
93 struct macho_routines_command
: public routines_command
{};
99 // create image for main executable
100 ImageLoaderMachOClassic
* ImageLoaderMachOClassic::instantiateMainExecutable(const macho_header
* mh
, uintptr_t slide
, const char* path
,
101 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
103 ImageLoaderMachOClassic
* image
= ImageLoaderMachOClassic::instantiateStart(mh
, path
, segCount
, libCount
);
105 // set slide for PIE programs
106 image
->setSlide(slide
);
108 // for PIE record end of program, to know where to start loading dylibs
109 if ( (mh
->flags
& MH_PIE
) && !context
.noPIE
)
110 fgNextPIEDylibAddress
= (uintptr_t)image
->getEnd();
112 image
->instantiateFinish(context
);
115 // kernel may have mapped in __IMPORT segment read-only, we need it read/write to do binding
116 if ( image
->fReadOnlyImportSegment
) {
117 for(unsigned int i
=0; i
< image
->fSegmentsCount
; ++i
) {
118 if ( image
->segIsReadOnlyImport(i
) )
119 image
->segMakeWritable(i
, context
);
124 if ( context
.verboseMapping
) {
125 dyld::log("dyld: Main executable mapped %s\n", path
);
126 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
127 const char* name
= image
->segName(i
);
128 if ( (strcmp(name
, "__PAGEZERO") == 0) || (strcmp(name
, "__UNIXSTACK") == 0) )
129 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segPreferredLoadAddress(i
), image
->segPreferredLoadAddress(i
)+image
->segSize(i
));
131 dyld::log("%18s at 0x%08lX->0x%08lX\n", name
, image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
138 // create image by mapping in a mach-o file
139 ImageLoaderMachOClassic
* ImageLoaderMachOClassic::instantiateFromFile(const char* path
, int fd
, const uint8_t* fileData
,
140 uint64_t offsetInFat
, uint64_t lenInFat
, const struct stat
& info
,
141 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
143 ImageLoaderMachOClassic
* image
= ImageLoaderMachOClassic::instantiateStart((macho_header
*)fileData
, path
, segCount
, libCount
);
145 // record info about file
146 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
149 image
->mapSegmentsClassic(fd
, offsetInFat
, lenInFat
, info
.st_size
, context
);
151 #if CODESIGNING_SUPPORT
152 // if this code is signed, validate the signature before accessing any mapped pages
153 image
->loadCodeSignature(fileData
, fd
, offsetInFat
);
156 // if path happens to be same as in LC_DYLIB_ID load command use that, otherwise malloc a copy of the path
157 const char* installName
= image
->getInstallPath();
158 if ( (installName
!= NULL
) && (strcmp(installName
, path
) == 0) && (path
[0] == '/') )
159 image
->setPathUnowned(installName
);
160 else if ( path
[0] != '/' ) {
161 // rdar://problem/5135363 turn relative paths into absolute paths so gdb, Symbolication can later find them
162 char realPath
[MAXPATHLEN
];
163 if ( realpath(path
, realPath
) != NULL
)
164 image
->setPath(realPath
);
166 image
->setPath(path
);
169 image
->setPath(path
);
171 // pre-fetch content of __DATA segment for faster launches
172 // don't do this on prebound images or if prefetching is disabled
173 if ( !context
.preFetchDisabled
&& !image
->isPrebindable())
174 image
->preFetchDATA(fd
, offsetInFat
, context
);
177 image
->instantiateFinish(context
);
180 // ImageLoader::setMapped() can throw an exception to block loading of image
181 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
189 // create image by using cached mach-o file
190 ImageLoaderMachOClassic
* ImageLoaderMachOClassic::instantiateFromCache(const macho_header
* mh
, const char* path
, const struct stat
& info
,
191 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
193 ImageLoaderMachOClassic
* image
= ImageLoaderMachOClassic::instantiateStart(mh
, path
, segCount
, libCount
);
195 // record info about file
196 image
->setFileInfo(info
.st_dev
, info
.st_ino
, info
.st_mtime
);
198 // remember this is from shared cache and cannot be unloaded
199 image
->fInSharedCache
= true;
200 image
->setNeverUnload();
202 // segments already mapped in cache
203 if ( context
.verboseMapping
) {
204 dyld::log("dyld: Using shared cached for %s\n", path
);
205 for(unsigned int i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
206 dyld::log("%18s at 0x%08lX->0x%08lX\n", image
->segName(i
), image
->segActualLoadAddress(i
), image
->segActualEndAddress(i
));
210 image
->instantiateFinish(context
);
213 // ImageLoader::setMapped() can throw an exception to block loading of image
214 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
222 // create image by copying an in-memory mach-o file
223 ImageLoaderMachOClassic
* ImageLoaderMachOClassic::instantiateFromMemory(const char* moduleName
, const macho_header
* mh
, uint64_t len
,
224 unsigned int segCount
, unsigned int libCount
, const LinkContext
& context
)
226 ImageLoaderMachOClassic
* image
= ImageLoaderMachOClassic::instantiateStart(mh
, moduleName
, segCount
, libCount
);
229 if ( mh
->filetype
== MH_EXECUTE
)
230 throw "can't load another MH_EXECUTE";
233 image
->ImageLoaderMachO::mapSegments((const void*)mh
, len
, context
);
235 // for compatibility, never unload dylibs loaded from memory
236 image
->setNeverUnload();
238 // bundle loads need path copied
239 if ( moduleName
!= NULL
)
240 image
->setPath(moduleName
);
242 image
->instantiateFinish(context
);
245 // ImageLoader::setMapped() can throw an exception to block loading of image
246 // <rdar://problem/6169686> Leaked fSegmentsArray and image segments during failed dlopen_preflight
255 ImageLoaderMachOClassic::ImageLoaderMachOClassic(const macho_header
* mh
, const char* path
,
256 unsigned int segCount
, uint32_t segOffsets
[], unsigned int libCount
)
257 : ImageLoaderMachO(mh
, path
, segCount
, segOffsets
, libCount
), fStrings(NULL
), fSymbolTable(NULL
), fDynamicInfo(NULL
)
261 // construct ImageLoaderMachOClassic using "placement new" with SegmentMachO objects array at end
262 ImageLoaderMachOClassic
* ImageLoaderMachOClassic::instantiateStart(const macho_header
* mh
, const char* path
,
263 unsigned int segCount
, unsigned int libCount
)
265 size_t size
= sizeof(ImageLoaderMachOClassic
) + segCount
* sizeof(uint32_t) + libCount
* sizeof(ImageLoader
*);
266 ImageLoaderMachOClassic
* allocatedSpace
= static_cast<ImageLoaderMachOClassic
*>(malloc(size
));
267 if ( allocatedSpace
== NULL
)
268 throw "malloc failed";
269 uint32_t* segOffsets
= ((uint32_t*)(((uint8_t*)allocatedSpace
) + sizeof(ImageLoaderMachOClassic
)));
270 bzero(&segOffsets
[segCount
], libCount
*sizeof(void*)); // zero out lib array
271 return new (allocatedSpace
) ImageLoaderMachOClassic(mh
, path
, segCount
, segOffsets
, libCount
);
276 // common code to finish initializing object
277 void ImageLoaderMachOClassic::instantiateFinish(const LinkContext
& context
)
279 // now that segments are mapped in, get real fMachOData, fLinkEditBase, and fSlide
280 this->parseLoadCmds();
282 // notify state change
283 this->setMapped(context
);
286 ImageLoaderMachOClassic::~ImageLoaderMachOClassic()
288 // don't do clean up in ~ImageLoaderMachO() because virtual call to segmentCommandOffsets() won't work
292 uint32_t* ImageLoaderMachOClassic::segmentCommandOffsets() const
294 return ((uint32_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOClassic
)));
298 ImageLoader
* ImageLoaderMachOClassic::libImage(unsigned int libIndex
) const
300 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOClassic
) + fSegmentsCount
*sizeof(uint32_t)));
302 return (ImageLoader
*)(images
[libIndex
] & (-2));
305 bool ImageLoaderMachOClassic::libReExported(unsigned int libIndex
) const
307 const uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOClassic
) + fSegmentsCount
*sizeof(uint32_t)));
308 // re-export flag is low bit
309 return ((images
[libIndex
] & 1) != 0);
313 void ImageLoaderMachOClassic::setLibImage(unsigned int libIndex
, ImageLoader
* image
, bool reExported
)
315 uintptr_t* images
= ((uintptr_t*)(((uint8_t*)this) + sizeof(ImageLoaderMachOClassic
) + fSegmentsCount
*sizeof(uint32_t)));
316 uintptr_t value
= (uintptr_t)image
;
319 images
[libIndex
] = value
;
323 void ImageLoaderMachOClassic::setSymbolTableInfo(const macho_nlist
* symbols
, const char* strings
, const dysymtab_command
* dynSym
)
325 fSymbolTable
= symbols
;
327 fDynamicInfo
= dynSym
;
330 void ImageLoaderMachOClassic::prefetchLINKEDIT(const LinkContext
& context
)
332 // always prefetch a subrange of __LINKEDIT pages
333 uintptr_t symbolTableStart
= (uintptr_t)fSymbolTable
;
334 uintptr_t stringTableStart
= (uintptr_t)fStrings
;
336 // if image did not load at preferred address
337 if ( segPreferredLoadAddress(0) != (uintptr_t)fMachOData
) {
338 // local relocations will be processed, so start pre-fetch at local symbols
339 start
= (uintptr_t)fMachOData
+ fDynamicInfo
->locreloff
;
342 // otherwise start pre-fetch at global symbols section of symbol table
343 start
= symbolTableStart
+ fDynamicInfo
->iextdefsym
* sizeof(macho_nlist
);
345 // prefetch ends at end of last undefined string in string pool
346 uintptr_t end
= stringTableStart
;
347 if ( fDynamicInfo
->nundefsym
!= 0 )
348 end
+= fSymbolTable
[fDynamicInfo
->iundefsym
+fDynamicInfo
->nundefsym
-1].n_un
.n_strx
;
349 else if ( fDynamicInfo
->nextdefsym
!= 0 )
350 end
+= fSymbolTable
[fDynamicInfo
->iextdefsym
+fDynamicInfo
->nextdefsym
-1].n_un
.n_strx
;
352 // round to whole pages
353 start
= start
& (-4096);
354 end
= (end
+ 4095) & (-4096);
356 // skip if there is only one page
357 if ( (end
-start
) > 4096 ) {
358 madvise((void*)start
, end
-start
, MADV_WILLNEED
);
359 fgTotalBytesPreFetched
+= (end
-start
);
360 if ( context
.verboseMapping
) {
361 dyld::log("%18s prefetching 0x%0lX -> 0x%0lX\n", "__LINKEDIT", start
, end
-1);
367 #if SPLIT_SEG_DYLIB_SUPPORT
369 ImageLoaderMachOClassic::getExtraZeroFillEntriesCount()
371 // calculate mapping entries
372 unsigned int extraZeroFillEntries
= 0;
373 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
374 if ( segHasTrailingZeroFill(i
) )
375 ++extraZeroFillEntries
;
378 return extraZeroFillEntries
;
382 ImageLoaderMachOClassic::initMappingTable(uint64_t offsetInFat
,
383 shared_file_mapping_np
*mappingTable
)
385 for(unsigned int i
=0,entryIndex
=0; i
< fSegmentsCount
; ++i
, ++entryIndex
) {
386 shared_file_mapping_np
* entry
= &mappingTable
[entryIndex
];
387 entry
->sfm_address
= segActualLoadAddress(i
);
388 entry
->sfm_size
= segFileSize(i
);
389 entry
->sfm_file_offset
= segFileOffset(i
) + offsetInFat
;
390 entry
->sfm_init_prot
= VM_PROT_NONE
;
391 if ( !segUnaccessible(i
) ) {
392 if ( segExecutable(i
) )
393 entry
->sfm_init_prot
|= VM_PROT_EXECUTE
;
394 if ( segReadable(i
) )
395 entry
->sfm_init_prot
|= VM_PROT_READ
;
396 if ( segWriteable(i
) )
397 entry
->sfm_init_prot
|= VM_PROT_WRITE
| VM_PROT_COW
;
399 entry
->sfm_max_prot
= entry
->sfm_init_prot
;
400 if ( segHasTrailingZeroFill(i
) ) {
401 shared_file_mapping_np
* zfentry
= &mappingTable
[++entryIndex
];
402 zfentry
->sfm_address
= entry
->sfm_address
+ segFileSize(i
);
403 zfentry
->sfm_size
= segSize(i
) - segFileSize(i
);
404 zfentry
->sfm_file_offset
= 0;
405 zfentry
->sfm_init_prot
= entry
->sfm_init_prot
| VM_PROT_COW
| VM_PROT_ZF
;
406 zfentry
->sfm_max_prot
= zfentry
->sfm_init_prot
;
412 ImageLoaderMachOClassic::mapSplitSegDylibOutsideSharedRegion(int fd
,
413 uint64_t offsetInFat
,
416 const LinkContext
& context
)
418 uintptr_t nextAltLoadAddress
= 0;
419 const unsigned int segmentCount
= fSegmentsCount
;
420 const unsigned int extraZeroFillEntries
= getExtraZeroFillEntriesCount();
421 const unsigned int regionCount
= segmentCount
+extraZeroFillEntries
;
422 shared_file_mapping_np regions
[regionCount
];
423 initMappingTable(offsetInFat
, regions
);
425 // find space somewhere to allocate split seg
426 bool foundRoom
= false;
427 while ( ! foundRoom
) {
429 for(unsigned int i
=0; i
< regionCount
; ++i
) {
430 vm_address_t addr
= nextAltLoadAddress
+ regions
[i
].sfm_address
- regions
[0].sfm_address
;
431 vm_size_t size
= regions
[i
].sfm_size
;
432 r
= vm_allocate(mach_task_self(), &addr
, size
, false /*only this range*/);
434 // no room here, deallocate what has succeeded so far
435 for(unsigned int j
=0; j
< i
; ++j
) {
436 vm_address_t addr
= nextAltLoadAddress
+ regions
[j
].sfm_address
- regions
[0].sfm_address
;
437 vm_size_t size
= regions
[j
].sfm_size
;
438 (void)vm_deallocate(mach_task_self(), addr
, size
);
440 nextAltLoadAddress
+= 0x00100000; // skip ahead 1MB and try again
441 // skip over shared region
442 if ( (SHARED_REGION_BASE
<= nextAltLoadAddress
) && (nextAltLoadAddress
< (SHARED_REGION_BASE
+ SHARED_REGION_SIZE
)) )
443 nextAltLoadAddress
= (SHARED_REGION_BASE
+ SHARED_REGION_SIZE
);
444 if ( nextAltLoadAddress
> 0xFF000000 )
445 throw "can't map split seg anywhere";
452 // map in each region
453 uintptr_t slide
= nextAltLoadAddress
- regions
[0].sfm_address
;
454 this->setSlide(slide
);
455 for(unsigned int i
=0; i
< regionCount
; ++i
) {
456 if ( ((regions
[i
].sfm_init_prot
& VM_PROT_ZF
) != 0) || (regions
[i
].sfm_size
== 0) ) {
457 // nothing to mmap for zero-fills areas, they are just vm_allocated
460 void* mmapAddress
= (void*)(uintptr_t)(regions
[i
].sfm_address
+ slide
);
461 size_t size
= regions
[i
].sfm_size
;
463 if ( regions
[i
].sfm_init_prot
& VM_PROT_EXECUTE
)
464 protection
|= PROT_EXEC
;
465 if ( regions
[i
].sfm_init_prot
& VM_PROT_READ
)
466 protection
|= PROT_READ
;
467 if ( regions
[i
].sfm_init_prot
& VM_PROT_WRITE
)
468 protection
|= PROT_WRITE
;
469 off_t offset
= regions
[i
].sfm_file_offset
;
470 //dyld::log("mmap(%p, 0x%08lX, %s\n", mmapAddress, size, fPath);
471 mmapAddress
= mmap(mmapAddress
, size
, protection
, MAP_FIXED
| MAP_PRIVATE
, fd
, offset
);
472 if ( mmapAddress
== ((void*)(-1)) )
478 if ( context
.verboseMapping
) {
479 dyld::log("dyld: Mapping split-seg outside shared region, slid by 0x%08lX %s\n", this->fSlide
, this->getPath());
480 for(unsigned int segIndex
=0,entryIndex
=0; segIndex
< segmentCount
; ++segIndex
, ++entryIndex
){
481 const shared_file_mapping_np
* entry
= ®ions
[entryIndex
];
482 if ( (entry
->sfm_init_prot
& VM_PROT_ZF
) == 0 )
483 dyld::log("%18s at 0x%08lX->0x%08lX\n",
484 segName(segIndex
), segActualLoadAddress(segIndex
), segActualEndAddress(segIndex
)-1);
485 if ( entryIndex
< (regionCount
-1) ) {
486 const shared_file_mapping_np
* nextEntry
= ®ions
[entryIndex
+1];
487 if ( (nextEntry
->sfm_init_prot
& VM_PROT_ZF
) != 0 ) {
488 uint64_t segOffset
= nextEntry
->sfm_address
- entry
->sfm_address
;
489 dyld::log("%18s at 0x%08lX->0x%08lX (zerofill)\n",
490 segName(segIndex
), (uintptr_t)(segActualLoadAddress(segIndex
) + segOffset
), (uintptr_t)(segActualLoadAddress(segIndex
) + segOffset
+ nextEntry
->sfm_size
- 1));
499 #endif // SPLIT_SEG_DYLIB_SUPPORT
502 void ImageLoaderMachOClassic::mapSegmentsClassic(int fd
, uint64_t offsetInFat
, uint64_t lenInFat
, uint64_t fileLen
, const LinkContext
& context
)
504 // non-split segment libraries handled by super class
506 return ImageLoaderMachO::mapSegments(fd
, offsetInFat
, lenInFat
, fileLen
, context
);
508 #if SPLIT_SEG_SHARED_REGION_SUPPORT
509 // try to map into shared region at preferred address
510 if ( mapSplitSegDylibInfoSharedRegion(fd
, offsetInFat
, lenInFat
, fileLen
, context
) == 0)
512 // if there is a problem, fall into case where we map file somewhere outside the shared region
515 #if SPLIT_SEG_DYLIB_SUPPORT
516 // support old split-seg dylibs by mapping them where ever we find space
517 if ( mapSplitSegDylibOutsideSharedRegion(fd
, offsetInFat
, lenInFat
, fileLen
, context
) != 0 )
519 throw "mapping error";
523 #if SPLIT_SEG_SHARED_REGION_SUPPORT
524 static int _shared_region_map_np(int fd
, uint32_t count
, const shared_file_mapping_np mappings
[])
526 return syscall(295, fd
, count
, mappings
);
530 ImageLoaderMachOClassic::mapSplitSegDylibInfoSharedRegion(int fd
,
531 uint64_t offsetInFat
,
534 const LinkContext
& context
)
536 // build table of segments to map
537 const unsigned int segmentCount
= fSegmentsCount
;
538 const unsigned int extraZeroFillEntries
= getExtraZeroFillEntriesCount();
539 const unsigned int mappingTableCount
= segmentCount
+extraZeroFillEntries
;
540 shared_file_mapping_np mappingTable
[mappingTableCount
];
541 initMappingTable(offsetInFat
, mappingTable
);
543 // try to map it in shared
544 int r
= _shared_region_map_np(fd
, mappingTableCount
, mappingTable
);
546 this->setNeverUnload();
547 if ( context
.verboseMapping
) {
548 dyld::log("dyld: Mapping split-seg shared %s\n", this->getPath());
549 for(unsigned int segIndex
=0,entryIndex
=0; segIndex
< segmentCount
; ++segIndex
, ++entryIndex
){
550 const shared_file_mapping_np
* entry
= &mappingTable
[entryIndex
];
551 if ( (entry
->sfm_init_prot
& VM_PROT_ZF
) == 0 )
552 dyld::log("%18s at 0x%08lX->0x%08lX\n",
553 segName(segIndex
), segActualLoadAddress(segIndex
), segActualEndAddress(segIndex
)-1);
554 if ( entryIndex
< (mappingTableCount
-1) ) {
555 const shared_file_mapping_np
* nextEntry
= &mappingTable
[entryIndex
+1];
556 if ( (nextEntry
->sfm_init_prot
& VM_PROT_ZF
) != 0 ) {
557 uint64_t segOffset
= nextEntry
->sfm_address
- entry
->sfm_address
;
558 dyld::log("%18s at 0x%08lX->0x%08lX\n",
559 segName(segIndex
), (uintptr_t)(segActualLoadAddress(segIndex
) + segOffset
),
560 (uintptr_t)(segActualLoadAddress(segIndex
) + segOffset
+ nextEntry
->sfm_size
- 1));
570 #endif // SPLIT_SEG_SHARED_REGION_SUPPORT
572 // test if this image is re-exported through parent (the image that loaded this one)
573 bool ImageLoaderMachOClassic::isSubframeworkOf(const LinkContext
& context
, const ImageLoader
* parent
) const
576 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
577 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
578 const struct load_command
* cmd
= cmds
;
579 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
580 if (cmd
->cmd
== LC_SUB_FRAMEWORK
) {
581 const struct sub_framework_command
* subf
= (struct sub_framework_command
*)cmd
;
582 const char* exportThruName
= (char*)cmd
+ subf
->umbrella
.offset
;
583 // need to match LC_SUB_FRAMEWORK string against the leaf name of the install location of parent...
584 const char* parentInstallPath
= parent
->getInstallPath();
585 if ( parentInstallPath
!= NULL
) {
586 const char* lastSlash
= strrchr(parentInstallPath
, '/');
587 if ( lastSlash
!= NULL
) {
588 if ( strcmp(&lastSlash
[1], exportThruName
) == 0 )
590 if ( context
.imageSuffix
!= NULL
) {
591 // when DYLD_IMAGE_SUFFIX is used, lastSlash string needs imageSuffix removed from end
592 char reexportAndSuffix
[strlen(context
.imageSuffix
)+strlen(exportThruName
)+1];
593 strcpy(reexportAndSuffix
, exportThruName
);
594 strcat(reexportAndSuffix
, context
.imageSuffix
);
595 if ( strcmp(&lastSlash
[1], reexportAndSuffix
) == 0 )
601 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
607 // test if child is re-exported
608 bool ImageLoaderMachOClassic::hasSubLibrary(const LinkContext
& context
, const ImageLoader
* child
) const
610 if ( fHasSubLibraries
) {
611 // need to match LC_SUB_LIBRARY string against the leaf name (without extension) of the install location of child...
612 const char* childInstallPath
= child
->getInstallPath();
613 if ( childInstallPath
!= NULL
) {
614 const char* lastSlash
= strrchr(childInstallPath
, '/');
615 if ( lastSlash
!= NULL
) {
616 const char* firstDot
= strchr(lastSlash
, '.');
618 if ( firstDot
== NULL
)
619 len
= strlen(lastSlash
);
621 len
= firstDot
-lastSlash
-1;
622 char childLeafName
[len
+1];
623 strncpy(childLeafName
, &lastSlash
[1], len
);
624 childLeafName
[len
] = '\0';
625 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
626 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
627 const struct load_command
* cmd
= cmds
;
628 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
632 const struct sub_library_command
* lib
= (struct sub_library_command
*)cmd
;
633 const char* aSubLibName
= (char*)cmd
+ lib
->sub_library
.offset
;
634 if ( strcmp(aSubLibName
, childLeafName
) == 0 )
636 if ( context
.imageSuffix
!= NULL
) {
637 // when DYLD_IMAGE_SUFFIX is used, childLeafName string needs imageSuffix removed from end
638 char aSubLibNameAndSuffix
[strlen(context
.imageSuffix
)+strlen(aSubLibName
)+1];
639 strcpy(aSubLibNameAndSuffix
, aSubLibName
);
640 strcat(aSubLibNameAndSuffix
, context
.imageSuffix
);
641 if ( strcmp(aSubLibNameAndSuffix
, childLeafName
) == 0 )
647 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
652 if ( fHasSubUmbrella
) {
653 // need to match LC_SUB_UMBRELLA string against the leaf name of install location of child...
654 const char* childInstallPath
= child
->getInstallPath();
655 if ( childInstallPath
!= NULL
) {
656 const char* lastSlash
= strrchr(childInstallPath
, '/');
657 if ( lastSlash
!= NULL
) {
658 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
659 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
660 const struct load_command
* cmd
= cmds
;
661 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
663 case LC_SUB_UMBRELLA
:
665 const struct sub_umbrella_command
* um
= (struct sub_umbrella_command
*)cmd
;
666 const char* aSubUmbrellaName
= (char*)cmd
+ um
->sub_umbrella
.offset
;
667 if ( strcmp(aSubUmbrellaName
, &lastSlash
[1]) == 0 )
669 if ( context
.imageSuffix
!= NULL
) {
670 // when DYLD_IMAGE_SUFFIX is used, lastSlash string needs imageSuffix removed from end
671 char umbrellaAndSuffix
[strlen(context
.imageSuffix
)+strlen(aSubUmbrellaName
)+1];
672 strcpy(umbrellaAndSuffix
, aSubUmbrellaName
);
673 strcat(umbrellaAndSuffix
, context
.imageSuffix
);
674 if ( strcmp(umbrellaAndSuffix
, &lastSlash
[1]) == 0 )
680 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
689 uintptr_t ImageLoaderMachOClassic::getFirstWritableSegmentAddress()
691 // in split segment libraries r_address is offset from first writable segment
692 for(unsigned int i
=0; i
< fSegmentsCount
; ++i
) {
693 if ( segWriteable(i
) )
694 return segActualLoadAddress(i
);
696 throw "no writable segment";
699 uintptr_t ImageLoaderMachOClassic::getRelocBase()
701 // r_address is either an offset from the first segment address
702 // or from the first writable segment address
704 return getFirstWritableSegmentAddress();
707 return getFirstWritableSegmentAddress();
709 return segActualLoadAddress(0);
715 static inline void otherRelocsPPC(uintptr_t* locationToFix
, uint8_t relocationType
, uint16_t otherHalf
, uintptr_t slide
)
717 // low 16 bits of 32-bit ppc instructions need fixing
718 struct ppcInstruction
{ uint16_t opcode
; int16_t immediateValue
; };
719 ppcInstruction
* instruction
= (ppcInstruction
*)locationToFix
;
720 //uint32_t before = *((uint32_t*)locationToFix);
721 switch ( relocationType
)
724 instruction
->immediateValue
= ((otherHalf
<< 16) | instruction
->immediateValue
) + slide
;
727 instruction
->immediateValue
= ((((instruction
->immediateValue
<< 16) | otherHalf
) + slide
) >> 16);
730 int16_t signedOtherHalf
= (int16_t)(otherHalf
& 0xffff);
731 uint32_t temp
= (instruction
->immediateValue
<< 16) + signedOtherHalf
+ slide
;
732 if ( (temp
& 0x00008000) != 0 )
734 instruction
->immediateValue
= temp
>> 16;
736 //uint32_t after = *((uint32_t*)locationToFix);
737 //dyld::log("dyld: ppc fixup %0p type %d from 0x%08X to 0x%08X\n", locationToFix, relocationType, before, after);
741 #if PREBOUND_IMAGE_SUPPORT
742 void ImageLoaderMachOClassic::resetPreboundLazyPointers(const LinkContext
& context
)
744 // loop through all local (internal) relocation records looking for pre-bound-lazy-pointer values
745 const uintptr_t relocBase
= this->getRelocBase();
746 register const uintptr_t slide
= this->fSlide
;
747 const relocation_info
* const relocsStart
= (struct relocation_info
*)(&fLinkEditBase
[fDynamicInfo
->locreloff
]);
748 const relocation_info
* const relocsEnd
= &relocsStart
[fDynamicInfo
->nlocrel
];
749 for (const relocation_info
* reloc
=relocsStart
; reloc
< relocsEnd
; ++reloc
) {
750 if ( (reloc
->r_address
& R_SCATTERED
) != 0 ) {
751 const struct scattered_relocation_info
* sreloc
= (struct scattered_relocation_info
*)reloc
;
752 if (sreloc
->r_length
== RELOC_SIZE
) {
753 uintptr_t* locationToFix
= (uintptr_t*)(sreloc
->r_address
+ relocBase
);
754 switch(sreloc
->r_type
) {
756 case PPC_RELOC_PB_LA_PTR
:
757 *locationToFix
= sreloc
->r_value
+ slide
;
761 case GENERIC_RELOC_PB_LA_PTR
:
762 *locationToFix
= sreloc
->r_value
+ slide
;
766 case ARM_RELOC_PB_LA_PTR
:
767 *locationToFix
= sreloc
->r_value
+ slide
;
780 void ImageLoaderMachOClassic::rebase(const LinkContext
& context
)
782 register const uintptr_t slide
= this->fSlide
;
783 const uintptr_t relocBase
= this->getRelocBase();
785 // prefetch any LINKEDIT pages needed
786 if ( !context
.preFetchDisabled
&& !this->isPrebindable())
787 this->prefetchLINKEDIT(context
);
789 // loop through all local (internal) relocation records
790 const relocation_info
* const relocsStart
= (struct relocation_info
*)(&fLinkEditBase
[fDynamicInfo
->locreloff
]);
791 const relocation_info
* const relocsEnd
= &relocsStart
[fDynamicInfo
->nlocrel
];
792 for (const relocation_info
* reloc
=relocsStart
; reloc
< relocsEnd
; ++reloc
) {
794 #if LINKEDIT_USAGE_DEBUG
795 noteAccessedLinkEditAddress(reloc
);
798 // only one kind of local relocation supported for x86_64
799 if ( reloc
->r_length
!= 3 )
800 throw "bad local relocation length";
801 if ( reloc
->r_type
!= X86_64_RELOC_UNSIGNED
)
802 throw "unknown local relocation type";
803 if ( reloc
->r_pcrel
!= 0 )
804 throw "bad local relocation pc_rel";
805 if ( reloc
->r_extern
!= 0 )
806 throw "extern relocation found with local relocations";
807 *((uintptr_t*)(reloc
->r_address
+ relocBase
)) += slide
;
809 if ( (reloc
->r_address
& R_SCATTERED
) == 0 ) {
810 if ( reloc
->r_symbolnum
== R_ABS
) {
811 // ignore absolute relocations
813 else if (reloc
->r_length
== RELOC_SIZE
) {
814 switch(reloc
->r_type
) {
815 case GENERIC_RELOC_VANILLA
:
816 *((uintptr_t*)(reloc
->r_address
+ relocBase
)) += slide
;
822 // some tools leave object file relocations in linked images
823 otherRelocsPPC((uintptr_t*)(reloc
->r_address
+ relocBase
), reloc
->r_type
, reloc
[1].r_address
, slide
);
824 ++reloc
; // these relocations come in pairs, skip next
828 throw "unknown local relocation type";
832 throw "bad local relocation length";
836 const struct scattered_relocation_info
* sreloc
= (struct scattered_relocation_info
*)reloc
;
837 if (sreloc
->r_length
== RELOC_SIZE
) {
838 uintptr_t* locationToFix
= (uintptr_t*)(sreloc
->r_address
+ relocBase
);
839 switch(sreloc
->r_type
) {
840 case GENERIC_RELOC_VANILLA
:
841 *locationToFix
+= slide
;
847 // Metrowerks compiler sometimes leaves object file relocations in linked images???
848 ++reloc
; // these relocations come in pairs, get next one
849 otherRelocsPPC(locationToFix
, sreloc
->r_type
, reloc
->r_address
, slide
);
851 case PPC_RELOC_PB_LA_PTR
:
855 case PPC_RELOC_PB_LA_PTR
:
856 // needed for compatibility with ppc64 binaries built with the first ld64
857 // which used PPC_RELOC_PB_LA_PTR relocs instead of GENERIC_RELOC_VANILLA for lazy pointers
858 *locationToFix
+= slide
;
861 case GENERIC_RELOC_PB_LA_PTR
:
865 case ARM_RELOC_PB_LA_PTR
:
870 throw "unknown local scattered relocation type";
874 throw "bad local scattered relocation length";
879 catch (const char* msg
) {
880 const uint8_t* r
= (uint8_t*)reloc
;
881 dyld::throwf("%s in %s. reloc record at %p: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
882 msg
, this->getPath(), reloc
, r
[0], r
[1], r
[2], r
[3], r
[4], r
[5], r
[6], r
[7]);
887 fgTotalRebaseFixups
+= fDynamicInfo
->nlocrel
;
892 const struct macho_nlist
* ImageLoaderMachOClassic::binarySearchWithToc(const char* key
, const char stringPool
[], const struct macho_nlist symbols
[],
893 const struct dylib_table_of_contents toc
[], uint32_t symbolCount
, uint32_t hintIndex
) const
895 int32_t high
= symbolCount
-1;
896 int32_t mid
= hintIndex
;
898 // handle out of range hint
899 if ( mid
>= (int32_t)symbolCount
)
901 ++ImageLoaderMachO::fgSymbolTableBinarySearchs
;
902 ++fgTotalBindImageSearches
;
904 //dyld::log("dyld: binarySearchWithToc for %s in %s\n", key, this->getShortName());
906 for (int32_t low
= 0; low
<= high
; mid
= (low
+high
)/2) {
907 const uint32_t index
= toc
[mid
].symbol_index
;
908 const struct macho_nlist
* pivot
= &symbols
[index
];
909 const char* pivotStr
= &stringPool
[pivot
->n_un
.n_strx
];
910 #if LINKEDIT_USAGE_DEBUG
911 noteAccessedLinkEditAddress(&toc
[mid
]);
912 noteAccessedLinkEditAddress(pivot
);
913 noteAccessedLinkEditAddress(pivotStr
);
915 int cmp
= astrcmp(key
, pivotStr
);
930 const struct macho_nlist
* ImageLoaderMachOClassic::binarySearch(const char* key
, const char stringPool
[], const struct macho_nlist symbols
[], uint32_t symbolCount
) const
933 ++fgTotalBindImageSearches
;
934 ++ImageLoaderMachO::fgSymbolTableBinarySearchs
;
936 //dyld::log("dyld: binarySearch for %s in %s, stringpool=%p, symbols=%p, symbolCount=%u\n",
937 // key, this->getShortName(), stringPool, symbols, symbolCount);
939 const struct macho_nlist
* base
= symbols
;
940 for (uint32_t n
= symbolCount
; n
> 0; n
/= 2) {
941 const struct macho_nlist
* pivot
= &base
[n
/2];
942 const char* pivotStr
= &stringPool
[pivot
->n_un
.n_strx
];
943 #if LINKEDIT_USAGE_DEBUG
944 noteAccessedLinkEditAddress(pivot
);
945 noteAccessedLinkEditAddress(pivotStr
);
947 int cmp
= astrcmp(key
, pivotStr
);
952 // move base to symbol after pivot
965 const ImageLoader::Symbol
* ImageLoaderMachOClassic::findExportedSymbol(const char* name
, const ImageLoader
** foundIn
) const
967 const struct macho_nlist
* sym
= NULL
;
968 if ( fDynamicInfo
->tocoff
== 0 )
969 sym
= binarySearch(name
, fStrings
, &fSymbolTable
[fDynamicInfo
->iextdefsym
], fDynamicInfo
->nextdefsym
);
971 sym
= binarySearchWithToc(name
, fStrings
, fSymbolTable
, (dylib_table_of_contents
*)&fLinkEditBase
[fDynamicInfo
->tocoff
],
972 fDynamicInfo
->ntoc
, fDynamicInfo
->nextdefsym
);
974 if ( foundIn
!= NULL
)
975 *foundIn
= (ImageLoader
*)this;
976 return (const Symbol
*)sym
;
983 bool ImageLoaderMachOClassic::containsSymbol(const void* addr
) const
985 return ( (fSymbolTable
<= addr
) && (addr
< fStrings
) );
989 uintptr_t ImageLoaderMachOClassic::exportedSymbolAddress(const Symbol
* symbol
) const
991 const struct macho_nlist
* sym
= (macho_nlist
*)symbol
;
992 uintptr_t result
= sym
->n_value
+ fSlide
;
994 // processor assumes code address with low bit set is thumb
995 if (sym
->n_desc
& N_ARM_THUMB_DEF
)
1001 bool ImageLoaderMachOClassic::exportedSymbolIsWeakDefintion(const Symbol
* symbol
) const
1003 const struct macho_nlist
* nlistSym
= (const struct macho_nlist
*)symbol
;
1004 return ( (nlistSym
->n_desc
& N_WEAK_DEF
) != 0 );
1007 const char* ImageLoaderMachOClassic::exportedSymbolName(const Symbol
* symbol
) const
1009 const struct macho_nlist
* nlistSym
= (const struct macho_nlist
*)symbol
;
1010 return &fStrings
[nlistSym
->n_un
.n_strx
];
1013 unsigned int ImageLoaderMachOClassic::exportedSymbolCount() const
1015 return fDynamicInfo
->nextdefsym
;
1018 const ImageLoader::Symbol
* ImageLoaderMachOClassic::exportedSymbolIndexed(unsigned int index
) const
1020 if ( index
< fDynamicInfo
->nextdefsym
) {
1021 const struct macho_nlist
* sym
= &fSymbolTable
[fDynamicInfo
->iextdefsym
+ index
];
1022 return (const ImageLoader::Symbol
*)sym
;
1027 unsigned int ImageLoaderMachOClassic::importedSymbolCount() const
1029 return fDynamicInfo
->nundefsym
;
1032 const ImageLoader::Symbol
* ImageLoaderMachOClassic::importedSymbolIndexed(unsigned int index
) const
1034 if ( index
< fDynamicInfo
->nundefsym
) {
1035 const struct macho_nlist
* sym
= &fSymbolTable
[fDynamicInfo
->iundefsym
+ index
];
1036 return (const ImageLoader::Symbol
*)sym
;
1041 const char* ImageLoaderMachOClassic::importedSymbolName(const Symbol
* symbol
) const
1043 const struct macho_nlist
* nlistSym
= (const struct macho_nlist
*)symbol
;
1044 return &fStrings
[nlistSym
->n_un
.n_strx
];
1049 bool ImageLoaderMachOClassic::symbolIsWeakDefinition(const struct macho_nlist
* symbol
)
1051 // if a define and weak ==> coalesced
1052 if ( ((symbol
->n_type
& N_TYPE
) == N_SECT
) && ((symbol
->n_desc
& N_WEAK_DEF
) != 0) )
1059 bool ImageLoaderMachOClassic::symbolIsWeakReference(const struct macho_nlist
* symbol
)
1061 // if an undefine and not referencing a weak symbol ==> coalesced
1062 if ( ((symbol
->n_type
& N_TYPE
) != N_SECT
) && ((symbol
->n_desc
& N_REF_TO_WEAK
) != 0) )
1069 uintptr_t ImageLoaderMachOClassic::getSymbolAddress(const macho_nlist
* sym
, const LinkContext
& context
) const
1071 return ImageLoaderMachO::getSymbolAddress((Symbol
*)sym
, this, context
);
1074 uintptr_t ImageLoaderMachOClassic::resolveUndefined(const LinkContext
& context
, const struct macho_nlist
* undefinedSymbol
,
1075 bool twoLevel
, bool dontCoalesce
, const ImageLoader
** foundIn
)
1077 ++fgTotalBindSymbolsResolved
;
1078 const char* symbolName
= &fStrings
[undefinedSymbol
->n_un
.n_strx
];
1080 #if LINKEDIT_USAGE_DEBUG
1081 noteAccessedLinkEditAddress(undefinedSymbol
);
1082 noteAccessedLinkEditAddress(symbolName
);
1084 if ( context
.bindFlat
|| !twoLevel
) {
1086 if ( ((undefinedSymbol
->n_type
& N_PEXT
) != 0) && ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) ) {
1087 // is a multi-module private_extern internal reference that the linker did not optimize away
1088 uintptr_t addr
= this->getSymbolAddress(undefinedSymbol
, context
);
1093 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) ) {
1094 if ( (*foundIn
!= this) && !(*foundIn
)->neverUnload() )
1095 this->addDynamicReference(*foundIn
);
1096 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1098 // if a bundle is loaded privately the above will not find its exports
1099 if ( this->isBundle() && this->hasHiddenExports() ) {
1100 // look in self for needed symbol
1101 sym
= this->findExportedSymbol(symbolName
, foundIn
);
1103 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1105 if ( (undefinedSymbol
->n_desc
& N_WEAK_REF
) != 0 ) {
1106 // definition can't be found anywhere
1107 // if reference is weak_import, then it is ok, just return 0
1110 throwSymbolNotFound(symbolName
, this->getPath(), "flat namespace");
1113 // symbol requires searching images with coalesced symbols (not done during prebinding)
1114 if ( !context
.prebinding
&& !dontCoalesce
&& (symbolIsWeakReference(undefinedSymbol
) || symbolIsWeakDefinition(undefinedSymbol
)) ) {
1116 if ( context
.coalescedExportFinder(symbolName
, &sym
, foundIn
) ) {
1117 if ( (*foundIn
!= this) && !(*foundIn
)->neverUnload() )
1118 this->addDynamicReference(*foundIn
);
1119 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1121 //throwSymbolNotFound(symbolName, this->getPath(), "coalesced namespace");
1122 //dyld::log("dyld: coalesced symbol %s not found in any coalesced image, falling back to two-level lookup", symbolName);
1125 // if this is a real definition (not an undefined symbol) there is no ordinal
1126 if ( (undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) {
1127 // static linker should never generate this case, but if it does, do something sane
1128 uintptr_t addr
= this->getSymbolAddress(undefinedSymbol
, context
);
1134 ImageLoader
* target
= NULL
;
1135 uint8_t ord
= GET_LIBRARY_ORDINAL(undefinedSymbol
->n_desc
);
1136 if ( ord
== EXECUTABLE_ORDINAL
) {
1137 target
= context
.mainExecutable
;
1139 else if ( ord
== SELF_LIBRARY_ORDINAL
) {
1142 else if ( ord
== DYNAMIC_LOOKUP_ORDINAL
) {
1143 // rnielsen: HACKHACK
1146 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) )
1147 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1148 // no image has exports this symbol
1150 context
.undefinedHandler(symbolName
);
1151 // try looking again
1152 if ( context
.flatExportFinder(symbolName
, &sym
, foundIn
) )
1153 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1155 throwSymbolNotFound(symbolName
, this->getPath(), "dynamic lookup");
1157 else if ( ord
<= libraryCount() ) {
1158 target
= libImage(ord
-1);
1159 if ( target
== NULL
) {
1160 // if target library not loaded and reference is weak or library is weak return 0
1165 dyld::throwf("bad mach-o binary, library ordinal (%u) too big (max %u) for symbol %s in %s",
1166 ord
, libraryCount(), symbolName
, this->getPath());
1169 if ( target
== NULL
) {
1170 //dyld::log("resolveUndefined(%s) in %s\n", symbolName, this->getPath());
1171 throw "symbol not found";
1174 const Symbol
* sym
= target
->findExportedSymbol(symbolName
, true, foundIn
);
1176 return (*foundIn
)->getExportedSymbolAddress(sym
, context
, this);
1178 else if ( (undefinedSymbol
->n_type
& N_PEXT
) != 0 ) {
1179 // don't know why the static linker did not eliminate the internal reference to a private extern definition
1181 return this->getSymbolAddress(undefinedSymbol
, context
);
1183 else if ( (undefinedSymbol
->n_desc
& N_WEAK_REF
) != 0 ) {
1184 // if definition not found and reference is weak return 0
1188 // nowhere to be found
1189 throwSymbolNotFound(symbolName
, this->getPath(), target
->getPath());
1195 // returns if 'addr' is within the address range of section 'sectionIndex'
1196 // fSlide is not used. 'addr' is assumed to be a prebound address in this image
1197 bool ImageLoaderMachOClassic::isAddrInSection(uintptr_t addr
, uint8_t sectionIndex
)
1199 uint8_t currentSectionIndex
= 1;
1200 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1201 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1202 const struct load_command
* cmd
= cmds
;
1203 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1204 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1205 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1206 if ( (currentSectionIndex
<= sectionIndex
) && (sectionIndex
< currentSectionIndex
+seg
->nsects
) ) {
1207 // 'sectionIndex' is in this segment, get section info
1208 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1209 const struct macho_section
* const section
= §ionsStart
[sectionIndex
-currentSectionIndex
];
1210 return ( (section
->addr
<= addr
) && (addr
< section
->addr
+section
->size
) );
1213 // 'sectionIndex' not in this segment, skip to next segment
1214 currentSectionIndex
+= seg
->nsects
;
1217 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1223 void ImageLoaderMachOClassic::doBindExternalRelocations(const LinkContext
& context
)
1225 const uintptr_t relocBase
= this->getRelocBase();
1226 const bool twoLevel
= this->usesTwoLevelNameSpace();
1227 const bool prebound
= this->isPrebindable();
1229 #if TEXT_RELOC_SUPPORT
1230 // if there are __TEXT fixups, temporarily make __TEXT writable
1231 if ( fTextSegmentBinds
)
1232 this->makeTextSegmentWritable(context
, true);
1234 // cache last lookup
1235 const struct macho_nlist
* lastUndefinedSymbol
= NULL
;
1236 uintptr_t symbolAddr
= 0;
1237 const ImageLoader
* image
= NULL
;
1239 // loop through all external relocation records and bind each
1240 const relocation_info
* const relocsStart
= (struct relocation_info
*)(&fLinkEditBase
[fDynamicInfo
->extreloff
]);
1241 const relocation_info
* const relocsEnd
= &relocsStart
[fDynamicInfo
->nextrel
];
1242 for (const relocation_info
* reloc
=relocsStart
; reloc
< relocsEnd
; ++reloc
) {
1243 if (reloc
->r_length
== RELOC_SIZE
) {
1244 switch(reloc
->r_type
) {
1247 const struct macho_nlist
* undefinedSymbol
= &fSymbolTable
[reloc
->r_symbolnum
];
1248 uintptr_t* location
= ((uintptr_t*)(reloc
->r_address
+ relocBase
));
1249 uintptr_t value
= *location
;
1250 bool symbolAddrCached
= true;
1252 if ( reloc
->r_pcrel
) {
1253 value
+= (uintptr_t)location
+ 4 - fSlide
;
1257 // we are doing relocations, so prebinding was not usable
1258 // in a prebound executable, the n_value field of an undefined symbol is set to the address where the symbol was found when prebound
1259 // so, subtracting that gives the initial displacement which we need to add to the newly found symbol address
1260 // if mach-o relocation structs had an "addend" field this complication would not be necessary.
1261 if ( ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) && ((undefinedSymbol
->n_desc
& N_WEAK_DEF
) != 0) ) {
1262 // weak symbols need special casing, since *location may have been prebound to a definition in another image.
1263 // If *location is currently prebound to somewhere in the same section as the weak definition, we assume
1264 // that we can subtract off the weak symbol address to get the addend.
1265 // If prebound elsewhere, we've lost the addend and have to assume it is zero.
1266 // The prebinding to elsewhere only happens with 10.4+ update_prebinding which only operates on a small set of Apple dylibs
1267 if ( (value
== undefinedSymbol
->n_value
) || this->isAddrInSection(value
, undefinedSymbol
->n_sect
) ) {
1268 value
-= undefinedSymbol
->n_value
;
1270 // if weak and thumb subtract off extra thumb bit
1271 if ( (undefinedSymbol
->n_desc
& N_ARM_THUMB_DEF
) != 0 )
1279 else if ( ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) && ((undefinedSymbol
->n_desc
& N_ARM_THUMB_DEF
) != 0) ) {
1280 // it was prebound to a defined symbol for thumb code in the same linkage unit
1281 // we need to subtract off one to get real addend
1282 value
-= (undefinedSymbol
->n_value
+1);
1286 // is undefined or non-weak symbol, so do subtraction to get addend
1287 value
-= undefinedSymbol
->n_value
;
1290 // if undefinedSymbol is same as last time, then symbolAddr and image will resolve to the same too
1291 if ( undefinedSymbol
!= lastUndefinedSymbol
) {
1292 bool dontCoalesce
= true;
1293 if ( symbolIsWeakReference(undefinedSymbol
) ) {
1294 // when weakbind() is run on a classic mach-o encoding, it won't try
1295 // to coalesce N_REF_TO_WEAK symbols because they are not in the sorted
1296 // range of global symbols. To handle that case we do the coalesing now.
1297 dontCoalesce
= false;
1299 symbolAddr
= this->resolveUndefined(context
, undefinedSymbol
, twoLevel
, dontCoalesce
, &image
);
1300 lastUndefinedSymbol
= undefinedSymbol
;
1301 symbolAddrCached
= false;
1303 if ( context
.verboseBind
) {
1304 const char *path
= NULL
;
1305 if ( image
!= NULL
) {
1306 path
= image
->getShortName();
1308 const char* cachedString
= "(cached)";
1309 if ( !symbolAddrCached
)
1312 dyld::log("dyld: bind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX%s\n",
1313 this->getShortName(), (uintptr_t)location
,
1314 path
, &fStrings
[undefinedSymbol
->n_un
.n_strx
], (uintptr_t)location
, symbolAddr
, cachedString
);
1317 dyld::log("dyld: bind: %s:0x%08lX = %s:%s, *0x%08lX = 0x%08lX%s + %ld\n",
1318 this->getShortName(), (uintptr_t)location
,
1319 path
, &fStrings
[undefinedSymbol
->n_un
.n_strx
], (uintptr_t)location
, symbolAddr
, cachedString
, value
);
1322 value
+= symbolAddr
;
1324 if ( reloc
->r_pcrel
) {
1325 *location
= value
- ((uintptr_t)location
+ 4);
1328 // don't dirty page if prebound value was correct
1329 if ( !prebound
|| (*location
!= value
) )
1333 // don't dirty page if prebound value was correct
1334 if ( !prebound
|| (*location
!= value
) )
1338 ++fgTotalBindFixups
;
1342 throw "unknown external relocation type";
1346 throw "bad external relocation length";
1350 #if TEXT_RELOC_SUPPORT
1351 // if there were __TEXT fixups, restore write protection
1352 if ( fTextSegmentBinds
) {
1353 this->makeTextSegmentWritable(context
, true);
1360 uintptr_t ImageLoaderMachOClassic::bindIndirectSymbol(uintptr_t* ptrToBind
, const struct macho_section
* sect
, const char* symbolName
, uintptr_t targetAddr
, const ImageLoader
* targetImage
, const LinkContext
& context
)
1362 if ( context
.verboseBind
) {
1363 const char* path
= NULL
;
1364 if ( targetImage
!= NULL
)
1365 path
= targetImage
->getShortName();
1366 dyld::log("dyld: bind indirect sym: %s:%s$%s = %s:%s, *0x%08lx = 0x%08lx\n",
1367 this->getShortName(), symbolName
, (((sect
->flags
& SECTION_TYPE
)==S_NON_LAZY_SYMBOL_POINTERS
) ? "non_lazy_ptr" : "lazy_ptr"),
1368 ((path
!= NULL
) ? path
: "<weak_import-not-found>"), symbolName
, (uintptr_t)ptrToBind
, targetAddr
);
1370 if ( context
.bindingHandler
!= NULL
) {
1371 const char* path
= NULL
;
1372 if ( targetImage
!= NULL
)
1373 path
= targetImage
->getShortName();
1374 targetAddr
= (uintptr_t)context
.bindingHandler(path
, symbolName
, (void *)targetAddr
);
1377 // i386 has special self-modifying stubs that change from "CALL rel32" to "JMP rel32"
1378 if ( ((sect
->flags
& SECTION_TYPE
) == S_SYMBOL_STUBS
) && ((sect
->flags
& S_ATTR_SELF_MODIFYING_CODE
) != 0) && (sect
->reserved2
== 5) ) {
1379 uint32_t rel32
= targetAddr
- (((uint32_t)ptrToBind
)+5);
1380 // re-write instruction in a thread-safe manner
1381 // use 8-byte compare-and-swap to alter 5-byte jump table entries
1382 // loop is required in case the extra three bytes that cover the next entry are altered by another thread
1385 volatile int64_t* jumpPtr
= (int64_t*)ptrToBind
;
1387 // By default the three extra bytes swapped follow the 5-byte JMP.
1388 // But, if the 5-byte jump is up against the end of the __IMPORT segment
1389 // We don't want to access bytes off the end of the segment, so we shift
1390 // the extra bytes to precede the 5-byte JMP.
1391 if ( (((uint32_t)ptrToBind
+ 8) & 0x00000FFC) == 0x00000000 ) {
1392 jumpPtr
= (int64_t*)((uint32_t)ptrToBind
- 3);
1395 int64_t oldEntry
= *jumpPtr
;
1400 newEntry
.int64
= oldEntry
;
1401 newEntry
.bytes
[pad
+0] = 0xE9; // JMP rel32
1402 newEntry
.bytes
[pad
+1] = rel32
& 0xFF;
1403 newEntry
.bytes
[pad
+2] = (rel32
>> 8) & 0xFF;
1404 newEntry
.bytes
[pad
+3] = (rel32
>> 16) & 0xFF;
1405 newEntry
.bytes
[pad
+4] = (rel32
>> 24) & 0xFF;
1406 done
= OSAtomicCompareAndSwap64Barrier(oldEntry
, newEntry
.int64
, (int64_t*)jumpPtr
);
1411 *ptrToBind
= targetAddr
;
1415 uintptr_t ImageLoaderMachOClassic::doBindFastLazySymbol(uint32_t lazyBindingInfoOffset
, const LinkContext
& context
)
1417 throw "compressed LINKEDIT lazy binder called with classic LINKEDIT";
1420 uintptr_t ImageLoaderMachOClassic::doBindLazySymbol(uintptr_t* lazyPointer
, const LinkContext
& context
)
1422 // scan for all lazy-pointer sections
1423 const bool twoLevel
= this->usesTwoLevelNameSpace();
1424 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1425 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1426 const struct load_command
* cmd
= cmds
;
1427 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[fDynamicInfo
->indirectsymoff
];
1428 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1430 case LC_SEGMENT_COMMAND
:
1432 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1433 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1434 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1435 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1436 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1437 uint32_t symbolIndex
= INDIRECT_SYMBOL_LOCAL
;
1438 if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1439 const uint32_t pointerCount
= sect
->size
/ sizeof(uintptr_t);
1440 uintptr_t* const symbolPointers
= (uintptr_t*)(sect
->addr
+ fSlide
);
1441 if ( (lazyPointer
>= symbolPointers
) && (lazyPointer
< &symbolPointers
[pointerCount
]) ) {
1442 const uint32_t indirectTableOffset
= sect
->reserved1
;
1443 const uint32_t lazyIndex
= lazyPointer
- symbolPointers
;
1444 symbolIndex
= indirectTable
[indirectTableOffset
+ lazyIndex
];
1448 else if ( (type
== S_SYMBOL_STUBS
) && (sect
->flags
& S_ATTR_SELF_MODIFYING_CODE
) && (sect
->reserved2
== 5) ) {
1449 // 5 bytes stubs on i386 are new "fast stubs"
1450 uint8_t* const jmpTableBase
= (uint8_t*)(sect
->addr
+ fSlide
);
1451 uint8_t* const jmpTableEnd
= jmpTableBase
+ sect
->size
;
1452 // initial CALL instruction in jump table leaves pointer to next entry, so back up
1453 uint8_t* const jmpTableEntryToPatch
= ((uint8_t*)lazyPointer
) - 5;
1454 lazyPointer
= (uintptr_t*)jmpTableEntryToPatch
;
1455 if ( (jmpTableEntryToPatch
>= jmpTableBase
) && (jmpTableEntryToPatch
< jmpTableEnd
) ) {
1456 const uint32_t indirectTableOffset
= sect
->reserved1
;
1457 const uint32_t entryIndex
= (jmpTableEntryToPatch
- jmpTableBase
)/5;
1458 symbolIndex
= indirectTable
[indirectTableOffset
+ entryIndex
];
1462 if ( symbolIndex
!= INDIRECT_SYMBOL_ABS
&& symbolIndex
!= INDIRECT_SYMBOL_LOCAL
) {
1463 const char* symbolName
= &fStrings
[fSymbolTable
[symbolIndex
].n_un
.n_strx
];
1464 const ImageLoader
* image
= NULL
;
1465 uintptr_t symbolAddr
= this->resolveUndefined(context
, &fSymbolTable
[symbolIndex
], twoLevel
, false, &image
);
1466 symbolAddr
= this->bindIndirectSymbol(lazyPointer
, sect
, symbolName
, symbolAddr
, image
, context
);
1467 ++fgTotalLazyBindFixups
;
1474 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1476 dyld::throwf("lazy pointer not found at address %p in image %s", lazyPointer
, this->getPath());
1481 void ImageLoaderMachOClassic::initializeCoalIterator(CoalIterator
& it
, unsigned int loadOrder
)
1484 it
.symbolName
= " ";
1485 it
.loadOrder
= loadOrder
;
1486 it
.weakSymbol
= false;
1487 it
.symbolMatches
= false;
1490 if ( fDynamicInfo
->tocoff
!= 0 ) {
1492 it
.endIndex
= fDynamicInfo
->ntoc
;
1496 it
.endIndex
= fDynamicInfo
->nextdefsym
;
1501 bool ImageLoaderMachOClassic::incrementCoalIterator(CoalIterator
& it
)
1506 if ( fDynamicInfo
->tocoff
!= 0 ) {
1507 if ( it
.curIndex
>= fDynamicInfo
->ntoc
) {
1509 it
.symbolName
= "~~~";
1513 const dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)&fLinkEditBase
[fDynamicInfo
->tocoff
];
1514 const uint32_t index
= toc
[it
.curIndex
].symbol_index
;
1515 const struct macho_nlist
* sym
= &fSymbolTable
[index
];
1516 const char* symStr
= &fStrings
[sym
->n_un
.n_strx
];
1517 it
.symbolName
= symStr
;
1518 it
.weakSymbol
= (sym
->n_desc
& N_WEAK_DEF
);
1519 it
.symbolMatches
= false;
1520 it
.type
= 0; // clear flag that says we applied updates for this symbol
1521 //dyld::log("incrementCoalIterator() curIndex=%ld, symbolName=%s in %s\n", it.curIndex, symStr, this->getPath());
1527 if ( it
.curIndex
>= fDynamicInfo
->nextdefsym
) {
1529 it
.symbolName
= "~~~";
1533 const struct macho_nlist
* sym
= &fSymbolTable
[fDynamicInfo
->iextdefsym
+it
.curIndex
];
1534 const char* symStr
= &fStrings
[sym
->n_un
.n_strx
];
1535 it
.symbolName
= symStr
;
1536 it
.weakSymbol
= (sym
->n_desc
& N_WEAK_DEF
);
1537 it
.symbolMatches
= false;
1538 it
.type
= 0; // clear flag that says we applied updates for this symbol
1539 //dyld::log("incrementCoalIterator() curIndex=%ld, symbolName=%s in %s\n", it.curIndex, symStr, this->getPath());
1548 uintptr_t ImageLoaderMachOClassic::getAddressCoalIterator(CoalIterator
& it
, const LinkContext
& context
)
1550 uint32_t symbol_index
= 0;
1551 if ( fDynamicInfo
->tocoff
!= 0 ) {
1552 const dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)&fLinkEditBase
[fDynamicInfo
->tocoff
];
1553 symbol_index
= toc
[it
.curIndex
-1].symbol_index
;
1556 symbol_index
= fDynamicInfo
->iextdefsym
+it
.curIndex
-1;
1558 const struct macho_nlist
* sym
= &fSymbolTable
[symbol_index
];
1559 //dyld::log("getAddressCoalIterator() => 0x%llX, %s symbol_index=%d, in %s\n", (uint64_t)(sym->n_value + fSlide), &fStrings[sym->n_un.n_strx], symbol_index, this->getPath());
1560 return sym
->n_value
+ fSlide
;
1564 void ImageLoaderMachOClassic::updateUsesCoalIterator(CoalIterator
& it
, uintptr_t value
, ImageLoader
* targetImage
, const LinkContext
& context
)
1566 // flat_namespace images with classic LINKEDIT do not need late coalescing.
1567 // They still need to be iterated becuase they may implement
1568 // something needed by other coalescing images.
1569 // But they need no updating because during the bind phase every symbol lookup is a full scan.
1570 if ( !this->usesTwoLevelNameSpace() )
1573 // <rdar://problem/6570879> weak binding done too early with inserted libraries
1574 if ( this->getState() < dyld_image_state_bound
)
1577 uint32_t symbol_index
= 0;
1578 if ( fDynamicInfo
->tocoff
!= 0 ) {
1579 const dylib_table_of_contents
* toc
= (dylib_table_of_contents
*)&fLinkEditBase
[fDynamicInfo
->tocoff
];
1580 symbol_index
= toc
[it
.curIndex
-1].symbol_index
;
1583 symbol_index
= fDynamicInfo
->iextdefsym
+it
.curIndex
-1;
1586 // if this image's copy of the symbol is not a weak definition nor a weak reference then nothing to coalesce here
1587 if ( !symbolIsWeakReference(&fSymbolTable
[symbol_index
]) && !symbolIsWeakDefinition(&fSymbolTable
[symbol_index
]) ) {
1591 // <rdar://problem/6555720> malformed dylib with duplicate weak symbols causes re-binding
1595 bool boundSomething
= false;
1596 // scan external relocations for uses of symbol_index
1597 const uintptr_t relocBase
= this->getRelocBase();
1598 const bool prebound
= this->isPrebindable();
1599 const relocation_info
* const relocsStart
= (struct relocation_info
*)(&fLinkEditBase
[fDynamicInfo
->extreloff
]);
1600 const relocation_info
* const relocsEnd
= &relocsStart
[fDynamicInfo
->nextrel
];
1601 for (const relocation_info
* reloc
=relocsStart
; reloc
< relocsEnd
; ++reloc
) {
1602 if ( reloc
->r_symbolnum
== symbol_index
) {
1603 //dyld::log("found external reloc using symbol_index=%d in %s\n",symbol_index, this->getPath());
1604 const struct macho_nlist
* undefinedSymbol
= &fSymbolTable
[reloc
->r_symbolnum
];
1605 const char* symbolName
= &fStrings
[undefinedSymbol
->n_un
.n_strx
];
1606 uintptr_t* location
= ((uintptr_t*)(reloc
->r_address
+ relocBase
));
1607 const uintptr_t initialValue
= *location
;
1608 uintptr_t addend
= 0;
1610 // we are doing relocations, so prebinding was not usable
1611 // in a prebound executable, the n_value field of an undefined symbol is set to the address where the symbol was found when prebound
1612 // so, subtracting that gives the initial displacement which we need to add to the newly found symbol address
1613 // if mach-o relocation structs had an "addend" field this complication would not be necessary.
1614 if ( ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) && ((undefinedSymbol
->n_desc
& N_WEAK_DEF
) != 0) ) {
1615 // weak symbols need special casing, since *location may have been prebound to a definition in another image.
1616 // If *location is currently prebound to somewhere in the same section as the weak definition, we assume
1617 // that we can subtract off the weak symbol address to get the addend.
1618 // If prebound elsewhere, we've lost the addend and have to assume it is zero.
1619 // The prebinding to elsewhere only happens with 10.4+ update_prebinding which only operates on a small set of Apple dylibs
1620 if ( (initialValue
== undefinedSymbol
->n_value
) || this->isAddrInSection(initialValue
, undefinedSymbol
->n_sect
) ) {
1621 addend
= initialValue
- undefinedSymbol
->n_value
;
1623 // if weak and thumb subtract off extra thumb bit
1624 if ( (undefinedSymbol
->n_desc
& N_ARM_THUMB_DEF
) != 0 )
1630 else if ( ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) && ((undefinedSymbol
->n_desc
& N_ARM_THUMB_DEF
) != 0) ) {
1631 // it was prebound to a defined symbol for thumb code in the same linkage unit
1632 // we need to subtract off one to get real addend
1633 addend
= initialValue
- (undefinedSymbol
->n_value
+1);
1637 // is undefined or non-weak symbol, so do subtraction to get addend
1638 addend
= initialValue
- undefinedSymbol
->n_value
;
1642 // non-prebound case
1643 if ( ((undefinedSymbol
->n_type
& N_TYPE
) == N_SECT
) && ((undefinedSymbol
->n_desc
& N_WEAK_DEF
) != 0) ) {
1644 // if target is weak-def in same linkage unit, then bind phase has already set initialValue
1645 // to be definition address plus addend
1646 //dyld::log("weak def, initialValue=0x%lX, undefAddr=0x%lX\n", initialValue, undefinedSymbol->n_value+fSlide);
1647 addend
= initialValue
- (undefinedSymbol
->n_value
+ fSlide
);
1650 // nothing fixed up yet, addend is just initial value
1651 //dyld::log("addend=0x%lX\n", initialValue);
1652 addend
= initialValue
;
1656 uint8_t type
= BIND_TYPE_POINTER
;
1658 if ( reloc
->r_pcrel
)
1659 type
= BIND_TYPE_TEXT_PCREL32
;
1661 this->bindLocation(context
, (uintptr_t)location
, value
, targetImage
, type
, symbolName
, addend
, "weak ");
1662 boundSomething
= true;
1666 // scan lazy and non-lazy pointers for uses of symbol_index
1667 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1668 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1669 const struct load_command
* cmd
= cmds
;
1670 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[fDynamicInfo
->indirectsymoff
];
1671 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1672 if ( cmd
->cmd
== LC_SEGMENT_COMMAND
) {
1673 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1674 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1675 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1676 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1677 uint32_t elementSize
= sizeof(uintptr_t);
1678 switch ( sect
->flags
& SECTION_TYPE
) {
1680 case S_SYMBOL_STUBS
:
1681 if ( ((sect
->flags
& S_ATTR_SELF_MODIFYING_CODE
) ==0) || (sect
->reserved2
!= 5) )
1685 case S_NON_LAZY_SYMBOL_POINTERS
:
1686 case S_LAZY_SYMBOL_POINTERS
:
1688 uint32_t elementCount
= sect
->size
/ elementSize
;
1689 const uint32_t indirectTableOffset
= sect
->reserved1
;
1690 uint8_t* ptrToBind
= (uint8_t*)(sect
->addr
+ fSlide
);
1691 //dyld::log(" scanning section %s of %s starting at %p\n", sect->sectname, this->getShortName(), ptrToBind);
1692 for (uint32_t j
=0; j
< elementCount
; ++j
, ptrToBind
+= elementSize
) {
1693 if ( indirectTable
[indirectTableOffset
+ j
] == symbol_index
) {
1694 //dyld::log(" found symbol index match at %d/%d, ptrToBind=%p\n", j, elementCount, ptrToBind);
1696 this->bindIndirectSymbol((uintptr_t*)ptrToBind
, sect
, it
.symbolName
, value
, targetImage
, context
);
1697 boundSomething
= true;
1705 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1707 if ( boundSomething
&& (targetImage
!= this) && !targetImage
->neverUnload() )
1708 this->addDynamicReference(targetImage
);
1710 // mark that this symbol has already been bound, so we don't try to bind again
1715 void ImageLoaderMachOClassic::bindIndirectSymbolPointers(const LinkContext
& context
, bool bindNonLazys
, bool bindLazys
)
1717 // scan for all non-lazy-pointer sections
1718 const bool twoLevel
= this->usesTwoLevelNameSpace();
1719 const uint32_t cmd_count
= ((macho_header
*)fMachOData
)->ncmds
;
1720 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1721 const struct load_command
* cmd
= cmds
;
1722 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[fDynamicInfo
->indirectsymoff
];
1723 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1725 case LC_SEGMENT_COMMAND
:
1727 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1728 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1729 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1730 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1731 bool isLazySymbol
= false;
1732 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1733 uint32_t elementSize
= sizeof(uintptr_t);
1734 uint32_t elementCount
= sect
->size
/ elementSize
;
1735 if ( type
== S_NON_LAZY_SYMBOL_POINTERS
) {
1736 if ( ! bindNonLazys
)
1739 else if ( type
== S_LAZY_SYMBOL_POINTERS
) {
1740 // process each symbol pointer in this section
1741 fgTotalPossibleLazyBindFixups
+= elementCount
;
1742 isLazySymbol
= true;
1747 else if ( (type
== S_SYMBOL_STUBS
) && (sect
->flags
& S_ATTR_SELF_MODIFYING_CODE
) && (sect
->reserved2
== 5) ) {
1748 // process each jmp entry in this section
1749 elementCount
= sect
->size
/ 5;
1751 fgTotalPossibleLazyBindFixups
+= elementCount
;
1752 isLazySymbol
= true;
1760 const uint32_t indirectTableOffset
= sect
->reserved1
;
1761 uint8_t* ptrToBind
= (uint8_t*)(sect
->addr
+ fSlide
);
1762 for (uint32_t j
=0; j
< elementCount
; ++j
, ptrToBind
+= elementSize
) {
1763 #if LINKEDIT_USAGE_DEBUG
1764 noteAccessedLinkEditAddress(&indirectTable
[indirectTableOffset
+ j
]);
1766 uint32_t symbolIndex
= indirectTable
[indirectTableOffset
+ j
];
1767 if ( symbolIndex
== INDIRECT_SYMBOL_LOCAL
) {
1768 *((uintptr_t*)ptrToBind
) += this->fSlide
;
1770 else if ( symbolIndex
== INDIRECT_SYMBOL_ABS
) {
1771 // do nothing since already has absolute address
1774 const struct macho_nlist
* sym
= &fSymbolTable
[symbolIndex
];
1775 if ( symbolIndex
== 0 ) {
1776 // This could be rdar://problem/3534709
1777 if ( ((const macho_header
*)fMachOData
)->filetype
== MH_EXECUTE
) {
1778 static bool alreadyWarned
= false;
1779 if ( (sym
->n_type
& N_TYPE
) != N_UNDF
) {
1780 // The indirect table parallels the (non)lazy pointer sections. For
1781 // instance, to find info about the fifth lazy pointer you look at the
1782 // fifth entry in the indirect table. (try otool -Iv on a file).
1783 // The entry in the indirect table contains an index into the symbol table.
1785 // The bug in ld caused the entry in the indirect table to be zero
1786 // (instead of a magic value that means a local symbol). So, if the
1787 // symbolIndex == 0, we may be encountering the bug, or 0 may be a valid
1788 // symbol table index. The check I put in place is to see if the zero'th
1789 // symbol table entry is an import entry (usually it is a local symbol
1791 if ( context
.verboseWarnings
&& !alreadyWarned
) {
1792 dyld::log("dyld: malformed executable '%s', skipping indirect symbol to %s\n",
1793 this->getPath(), &fStrings
[sym
->n_un
.n_strx
]);
1794 alreadyWarned
= true;
1800 const ImageLoader
* image
= NULL
;
1801 // let weak definitions resolve to themselves, later coalescing may overwrite them
1802 bool dontCoalesce
= true;
1803 if ( bindLazys
&& isLazySymbol
) {
1804 // if this is something normally lazy bound, but we are forcing
1805 // it to be bound now, do coalescing
1806 dontCoalesce
= false;
1808 if ( symbolIsWeakReference(sym
) ) {
1809 // when weakbind() is run on a classic mach-o encoding, it won't try
1810 // to coalesce N_REF_TO_WEAK symbols because they are not in the sorted
1811 // range of global symbols. To handle that case we do the coalesing now.
1812 dontCoalesce
= false;
1814 uintptr_t symbolAddr
= resolveUndefined(context
, sym
, twoLevel
, dontCoalesce
, &image
);
1816 symbolAddr
= this->bindIndirectSymbol((uintptr_t*)ptrToBind
, sect
, &fStrings
[sym
->n_un
.n_strx
], symbolAddr
, image
, context
);
1818 ++fgTotalBindFixups
;
1825 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1832 void ImageLoaderMachOClassic::initializeLazyStubs(const LinkContext
& context
)
1834 if ( ! this->usablePrebinding(context
) ) {
1835 // reset all "fast" stubs
1836 const macho_header
* mh
= (macho_header
*)fMachOData
;
1837 const uint32_t cmd_count
= mh
->ncmds
;
1838 const struct load_command
* const cmds
= (struct load_command
*)&fMachOData
[sizeof(macho_header
)];
1839 const struct load_command
* cmd
= cmds
;
1840 for (uint32_t i
= 0; i
< cmd_count
; ++i
) {
1842 case LC_SEGMENT_COMMAND
:
1844 const struct macho_segment_command
* seg
= (struct macho_segment_command
*)cmd
;
1845 const struct macho_section
* const sectionsStart
= (struct macho_section
*)((char*)seg
+ sizeof(struct macho_segment_command
));
1846 const struct macho_section
* const sectionsEnd
= §ionsStart
[seg
->nsects
];
1847 for (const struct macho_section
* sect
=sectionsStart
; sect
< sectionsEnd
; ++sect
) {
1848 const uint8_t type
= sect
->flags
& SECTION_TYPE
;
1849 if ( (type
== S_SYMBOL_STUBS
) && (sect
->flags
& S_ATTR_SELF_MODIFYING_CODE
) && (sect
->reserved2
== 5) ) {
1850 // reset each jmp entry in this section
1851 const uint32_t indirectTableOffset
= sect
->reserved1
;
1852 const uint32_t* const indirectTable
= (uint32_t*)&fLinkEditBase
[fDynamicInfo
->indirectsymoff
];
1853 uint8_t* start
= (uint8_t*)(sect
->addr
+ this->fSlide
);
1854 uint8_t* end
= start
+ sect
->size
;
1855 uintptr_t dyldHandler
= (uintptr_t)&fast_stub_binding_helper_interface
;
1856 uint32_t entryIndex
= 0;
1857 for (uint8_t* entry
= start
; entry
< end
; entry
+= 5, ++entryIndex
) {
1858 bool installLazyHandler
= true;
1859 // jump table entries that cross a (64-byte) cache line boundary have the potential to cause crashes
1860 // if the instruction is updated by one thread while being executed by another
1861 if ( ((uint32_t)entry
& 0xFFFFFFC0) != ((uint32_t)entry
+4 & 0xFFFFFFC0) ) {
1862 // need to bind this now to avoid a potential problem if bound lazily
1863 uint32_t symbolIndex
= indirectTable
[indirectTableOffset
+ entryIndex
];
1864 // the latest linker marks 64-byte crossing stubs with INDIRECT_SYMBOL_ABS so they are not used
1865 if ( symbolIndex
!= INDIRECT_SYMBOL_ABS
) {
1866 const char* symbolName
= &fStrings
[fSymbolTable
[symbolIndex
].n_un
.n_strx
];
1867 const ImageLoader
* image
= NULL
;
1869 uintptr_t symbolAddr
= this->resolveUndefined(context
, &fSymbolTable
[symbolIndex
], this->usesTwoLevelNameSpace(), false, &image
);
1870 symbolAddr
= this->bindIndirectSymbol((uintptr_t*)entry
, sect
, symbolName
, symbolAddr
, image
, context
);
1871 ++fgTotalBindFixups
;
1872 uint32_t rel32
= symbolAddr
- (((uint32_t)entry
)+5);
1873 entry
[0] = 0xE9; // JMP rel32
1874 entry
[1] = rel32
& 0xFF;
1875 entry
[2] = (rel32
>> 8) & 0xFF;
1876 entry
[3] = (rel32
>> 16) & 0xFF;
1877 entry
[4] = (rel32
>> 24) & 0xFF;
1878 installLazyHandler
= false;
1880 catch (const char* msg
) {
1881 // ignore errors when binding symbols early
1882 // maybe the function is never called, and therefore erroring out now would be a regression
1886 if ( installLazyHandler
) {
1887 uint32_t rel32
= dyldHandler
- (((uint32_t)entry
)+5);
1888 entry
[0] = 0xE8; // CALL rel32
1889 entry
[1] = rel32
& 0xFF;
1890 entry
[2] = (rel32
>> 8) & 0xFF;
1891 entry
[3] = (rel32
>> 16) & 0xFF;
1892 entry
[4] = (rel32
>> 24) & 0xFF;
1899 cmd
= (const struct load_command
*)(((char*)cmd
)+cmd
->cmdsize
);
1906 void ImageLoaderMachOClassic::doBind(const LinkContext
& context
, bool forceLazysBound
)
1909 this->initializeLazyStubs(context
);
1912 // if prebound and loaded at prebound address, and all libraries are same as when this was prebound, then no need to bind
1913 // note: flat-namespace binaries need to have imports rebound (even if correctly prebound)
1914 if ( this->usablePrebinding(context
) ) {
1915 // binding already up to date
1918 // no valid prebinding, so bind symbols.
1919 // values bound by name are stored two different ways in classic mach-o:
1921 // 1) external relocations are used for data initialized to external symbols
1922 this->doBindExternalRelocations(context
);
1924 // 2) "indirect symbols" are used for code references to external symbols
1925 // if this image is in the shared cache, there is no way to reset the lazy pointers, so bind them now
1926 this->bindIndirectSymbolPointers(context
, true, forceLazysBound
|| fInSharedCache
);
1930 // set up dyld entry points in image
1931 this->setupLazyPointerHandler(context
);
1934 void ImageLoaderMachOClassic::doBindJustLazies(const LinkContext
& context
)
1936 // some API called requested that all lazy pointers in this image be force bound
1937 this->bindIndirectSymbolPointers(context
, false, true);
1940 const char* ImageLoaderMachOClassic::findClosestSymbol(const void* addr
, const void** closestAddr
) const
1942 uintptr_t targetAddress
= (uintptr_t)addr
- fSlide
;
1943 const struct macho_nlist
* bestSymbol
= NULL
;
1944 // first walk all global symbols
1945 const struct macho_nlist
* const globalsStart
= &fSymbolTable
[fDynamicInfo
->iextdefsym
];
1946 const struct macho_nlist
* const globalsEnd
= &globalsStart
[fDynamicInfo
->nextdefsym
];
1947 for (const struct macho_nlist
* s
= globalsStart
; s
< globalsEnd
; ++s
) {
1948 if ( (s
->n_type
& N_TYPE
) == N_SECT
) {
1949 if ( bestSymbol
== NULL
) {
1950 if ( s
->n_value
<= targetAddress
)
1953 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
1958 // next walk all local symbols
1959 const struct macho_nlist
* const localsStart
= &fSymbolTable
[fDynamicInfo
->ilocalsym
];
1960 const struct macho_nlist
* const localsEnd
= &localsStart
[fDynamicInfo
->nlocalsym
];
1961 for (const struct macho_nlist
* s
= localsStart
; s
< localsEnd
; ++s
) {
1962 if ( ((s
->n_type
& N_TYPE
) == N_SECT
) && ((s
->n_type
& N_STAB
) == 0) ) {
1963 if ( bestSymbol
== NULL
) {
1964 if ( s
->n_value
<= targetAddress
)
1967 else if ( (s
->n_value
<= targetAddress
) && (bestSymbol
->n_value
< s
->n_value
) ) {
1972 if ( bestSymbol
!= NULL
) {
1973 *closestAddr
= (void*)(bestSymbol
->n_value
+ fSlide
);
1974 return &fStrings
[bestSymbol
->n_un
.n_strx
];