1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2006 Apple Computer, 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 #ifndef __MACHO_BINDER__
26 #define __MACHO_BINDER__
28 #include <sys/types.h>
31 #include <mach/mach.h>
38 #include <mach-o/loader.h>
39 #include <mach-o/fat.h>
44 #include "MachOFileAbstraction.hpp"
45 #include "Architectures.hpp"
46 #include "MachOLayout.hpp"
47 #include "MachORebaser.hpp"
53 class Binder : public Rebaser<A>
56 struct CStringEquals {
57 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
59 typedef __gnu_cxx::hash_map<const char*, class Binder<A>*, __gnu_cxx::hash<const char*>, CStringEquals> Map;
62 Binder(const MachOLayoutAbstraction&, uint64_t dyldBaseAddress);
65 const char* getDylibID() const;
66 void setDependentBinders(const Map& map);
70 typedef typename A::P P;
71 typedef typename A::P::E E;
72 typedef typename A::P::uint_t pint_t;
73 struct BinderAndReExportFlag { Binder<A>* binder; bool reExport; };
74 typedef __gnu_cxx::hash_map<const char*, const macho_nlist<P>*, __gnu_cxx::hash<const char*>, CStringEquals> NameToSymbolMap;
76 void doBindExternalRelocations();
77 void doBindIndirectSymbols();
78 void doSetUpDyldSection();
79 void doSetPreboundUndefines();
80 pint_t resolveUndefined(const macho_nlist<P>* undefinedSymbol);
81 const macho_nlist<P>* findExportedSymbol(const char* name);
82 void bindStub(uint8_t elementSize, uint8_t* location, pint_t vmlocation, pint_t value);
83 const char* parentUmbrella();
85 static uint8_t pointerRelocSize();
86 static uint8_t pointerRelocType();
88 std::vector<BinderAndReExportFlag> fDependentDylibs;
89 NameToSymbolMap fHashTable;
90 uint64_t fDyldBaseAddress;
91 const macho_nlist<P>* fSymbolTable;
93 const macho_dysymtab_command<P>* fDynamicInfo;
94 const macho_segment_command<P>* fFristWritableSegment;
95 const macho_dylib_command<P>* fDylibID;
96 const macho_dylib_command<P>* fParentUmbrella;
97 bool fOriginallyPrebound;
101 template <typename A>
102 Binder<A>::Binder(const MachOLayoutAbstraction& layout, uint64_t dyldBaseAddress)
103 : Rebaser<A>(layout), fDyldBaseAddress(dyldBaseAddress),
104 fSymbolTable(NULL), fStrings(NULL), fDynamicInfo(NULL),
105 fFristWritableSegment(NULL), fDylibID(NULL),
106 fParentUmbrella(NULL)
108 fOriginallyPrebound = ((this->fHeader->flags() & MH_PREBOUND) != 0);
109 // update header flags so the cache looks prebound split-seg (0x80000000 is in-shared-cache bit)
110 ((macho_header<P>*)this->fHeader)->set_flags(this->fHeader->flags() | MH_PREBOUND | MH_SPLIT_SEGS | 0x80000000);
112 // calculate fDynamicInfo, fStrings, fSymbolTable
113 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)this->fHeader + sizeof(macho_header<P>));
114 const uint32_t cmd_count = this->fHeader->ncmds();
115 const macho_load_command<P>* cmd = cmds;
116 for (uint32_t i = 0; i < cmd_count; ++i) {
117 switch (cmd->cmd()) {
119 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
120 fSymbolTable = (macho_nlist<P>*)(&this->fLinkEditBase[symtab->symoff()]);
121 fStrings = (const char*)&this->fLinkEditBase[symtab->stroff()];
124 fDynamicInfo = (macho_dysymtab_command<P>*)cmd;
127 ((macho_dylib_command<P>*)cmd)->set_timestamp(0);
128 fDylibID = (macho_dylib_command<P>*)cmd;
131 case LC_LOAD_WEAK_DYLIB:
132 case LC_REEXPORT_DYLIB:
133 ((macho_dylib_command<P>*)cmd)->set_timestamp(0);
135 case LC_SUB_FRAMEWORK:
136 fParentUmbrella = (macho_dylib_command<P>*)cmd;
139 if ( cmd->cmd() & LC_REQ_DYLD )
140 throwf("unknown required load command %d", cmd->cmd());
142 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
144 if ( fDynamicInfo == NULL )
145 throw "no LC_DYSYMTAB";
146 if ( fSymbolTable == NULL )
147 throw "no LC_SYMTAB";
149 if ( fDynamicInfo->tocoff() == 0 ) {
150 const macho_nlist<P>* start = &fSymbolTable[fDynamicInfo->iextdefsym()];
151 const macho_nlist<P>* end = &start[fDynamicInfo->nextdefsym()];
152 fHashTable.resize(fDynamicInfo->nextdefsym()); // set initial bucket count
153 for (const macho_nlist<P>* sym=start; sym < end; ++sym) {
154 const char* name = &fStrings[sym->n_strx()];
155 fHashTable[name] = sym;
159 int32_t count = fDynamicInfo->ntoc();
160 fHashTable.resize(count); // set initial bucket count
161 const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)&this->fLinkEditBase[fDynamicInfo->tocoff()];
162 for (int32_t i = 0; i < count; ++i) {
163 const uint32_t index = E::get32(toc[i].symbol_index);
164 const macho_nlist<P>* sym = &fSymbolTable[index];
165 const char* name = &fStrings[sym->n_strx()];
166 fHashTable[name] = sym;
172 template <> uint8_t Binder<ppc>::pointerRelocSize() { return 2; }
173 template <> uint8_t Binder<ppc64>::pointerRelocSize() { return 3; }
174 template <> uint8_t Binder<x86>::pointerRelocSize() { return 2; }
175 template <> uint8_t Binder<x86_64>::pointerRelocSize() { return 3; }
177 template <> uint8_t Binder<ppc>::pointerRelocType() { return GENERIC_RELOC_VANILLA; }
178 template <> uint8_t Binder<ppc64>::pointerRelocType() { return GENERIC_RELOC_VANILLA; }
179 template <> uint8_t Binder<x86>::pointerRelocType() { return GENERIC_RELOC_VANILLA; }
180 template <> uint8_t Binder<x86_64>::pointerRelocType() { return X86_64_RELOC_UNSIGNED; }
183 template <typename A>
184 const char* Binder<A>::getDylibID() const
186 if ( fDylibID != NULL )
187 return fDylibID->name();
192 template <typename A>
193 const char* Binder<A>::parentUmbrella()
195 if ( fParentUmbrella != NULL )
196 return fParentUmbrella->name();
203 template <typename A>
204 void Binder<A>::setDependentBinders(const Map& map)
206 // first pass to build vector of dylibs
207 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)this->fHeader + sizeof(macho_header<P>));
208 const uint32_t cmd_count = this->fHeader->ncmds();
209 const macho_load_command<P>* cmd = cmds;
210 for (uint32_t i = 0; i < cmd_count; ++i) {
211 switch (cmd->cmd()) {
213 case LC_LOAD_WEAK_DYLIB:
214 case LC_REEXPORT_DYLIB:
215 const char* path = ((struct macho_dylib_command<P>*)cmd)->name();
216 typename Map::const_iterator pos = map.find(path);
217 if ( pos != map.end() ) {
218 BinderAndReExportFlag entry;
219 entry.binder = pos->second;
220 entry.reExport = ( cmd->cmd() == LC_REEXPORT_DYLIB );
221 fDependentDylibs.push_back(entry);
224 // the load command string does not match the install name of any loaded dylib
225 // this could happen if there was not a world build and some dylib changed its
226 // install path to be some symlinked path
228 // use realpath() and walk map looking for a realpath match
230 char targetPath[PATH_MAX];
231 if ( realpath(path, targetPath) != NULL ) {
232 for(typename Map::const_iterator it=map.begin(); it != map.end(); ++it) {
233 char aPath[PATH_MAX];
234 if ( realpath(it->first, aPath) != NULL ) {
235 if ( strcmp(targetPath, aPath) == 0 ) {
236 BinderAndReExportFlag entry;
237 entry.binder = it->second;
238 entry.reExport = ( cmd->cmd() == LC_REEXPORT_DYLIB );
239 fDependentDylibs.push_back(entry);
241 fprintf(stderr, "update_dyld_shared_cache: warning mismatched install path in %s for %s\n",
242 this->getDylibID(), path);
249 throwf("in %s can't find dylib %s", this->getDylibID(), path);
253 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
255 // handle pre-10.5 re-exports
256 if ( (this->fHeader->flags() & MH_NO_REEXPORTED_DYLIBS) == 0 ) {
258 // LC_SUB_LIBRARY means re-export one with matching leaf name
259 for (uint32_t i = 0; i < cmd_count; ++i) {
260 switch ( cmd->cmd() ) {
262 const char* dylibBaseName = ((macho_sub_library_command<P>*)cmd)->sub_library();
263 for (typename std::vector<BinderAndReExportFlag>::iterator it = fDependentDylibs.begin(); it != fDependentDylibs.end(); ++it) {
264 const char* dylibName = it->binder->getDylibID();
265 const char* lastSlash = strrchr(dylibName, '/');
266 const char* leafStart = &lastSlash[1];
267 if ( lastSlash == NULL )
268 leafStart = dylibName;
269 const char* firstDot = strchr(leafStart, '.');
270 int len = strlen(leafStart);
271 if ( firstDot != NULL )
272 len = firstDot - leafStart;
273 if ( strncmp(leafStart, dylibBaseName, len) == 0 )
277 case LC_SUB_UMBRELLA:
278 const char* frameworkLeafName = ((macho_sub_umbrella_command<P>*)cmd)->sub_umbrella();
279 for (typename std::vector<BinderAndReExportFlag>::iterator it = fDependentDylibs.begin(); it != fDependentDylibs.end(); ++it) {
280 const char* dylibName = it->binder->getDylibID();
281 const char* lastSlash = strrchr(dylibName, '/');
282 if ( (lastSlash != NULL) && (strcmp(&lastSlash[1], frameworkLeafName) == 0) )
287 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
289 // ask dependents if they re-export through me
290 const char* thisName = this->getDylibID();
291 if ( thisName != NULL ) {
292 const char* thisLeafName = strrchr(thisName, '/');
293 if ( thisLeafName != NULL )
295 for (typename std::vector<BinderAndReExportFlag>::iterator it = fDependentDylibs.begin(); it != fDependentDylibs.end(); ++it) {
296 if ( ! it->reExport ) {
297 const char* parentUmbrellaName = it->binder->parentUmbrella();
298 if ( parentUmbrellaName != NULL ) {
299 if ( strcmp(parentUmbrellaName, thisLeafName) == 0 )
308 template <typename A>
309 void Binder<A>::bind()
311 this->doSetUpDyldSection();
312 this->doBindExternalRelocations();
313 this->doBindIndirectSymbols();
314 this->doSetPreboundUndefines();
318 template <typename A>
319 void Binder<A>::doSetUpDyldSection()
321 // find __DATA __dyld section
322 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)this->fHeader + sizeof(macho_header<P>));
323 const uint32_t cmd_count = this->fHeader->ncmds();
324 const macho_load_command<P>* cmd = cmds;
325 for (uint32_t i = 0; i < cmd_count; ++i) {
326 if ( cmd->cmd() == macho_segment_command<P>::CMD ) {
327 const macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd;
328 if ( strcmp(seg->segname(), "__DATA") == 0 ) {
329 const macho_section<P>* const sectionsStart = (macho_section<P>*)((uint8_t*)seg + sizeof(macho_segment_command<P>));
330 const macho_section<P>* const sectionsEnd = §ionsStart[seg->nsects()];
331 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
332 if ( (strcmp(sect->sectname(), "__dyld") == 0) && (sect->size() >= 2*sizeof(pint_t)) ) {
333 // set two values in __dyld section to point into dyld
334 pint_t* lazyBinder = this->mappedAddressForNewAddress(sect->addr());
335 pint_t* dyldFuncLookup = this->mappedAddressForNewAddress(sect->addr()+sizeof(pint_t));
336 A::P::setP(*lazyBinder, fDyldBaseAddress + 0x1000);
337 A::P::setP(*dyldFuncLookup, fDyldBaseAddress + 0x1008);
342 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
347 template <typename A>
348 void Binder<A>::doSetPreboundUndefines()
350 const macho_dysymtab_command<P>* dysymtab = NULL;
351 macho_nlist<P>* symbolTable = NULL;
353 // get symbol table info
354 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)this->fHeader + sizeof(macho_header<P>));
355 const uint32_t cmd_count = this->fHeader->ncmds();
356 const macho_load_command<P>* cmd = cmds;
357 for (uint32_t i = 0; i < cmd_count; ++i) {
358 switch (cmd->cmd()) {
361 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
362 symbolTable = (macho_nlist<P>*)(&this->fLinkEditBase[symtab->symoff()]);
366 dysymtab = (macho_dysymtab_command<P>*)cmd;
369 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
372 // walk all undefines and set their prebound n_value
373 macho_nlist<P>* const lastUndefine = &symbolTable[dysymtab->iundefsym()+dysymtab->nundefsym()];
374 for (macho_nlist<P>* entry = &symbolTable[dysymtab->iundefsym()]; entry < lastUndefine; ++entry) {
375 if ( entry->n_type() & N_EXT ) {
376 pint_t pbaddr = this->resolveUndefined(entry);
377 //fprintf(stderr, "doSetPreboundUndefines: r_sym=%s, pbaddr=0x%08X, in %s\n",
378 // &fStrings[entry->n_strx()], pbaddr, this->getDylibID());
379 entry->set_n_value(pbaddr);
385 template <typename A>
386 void Binder<A>::doBindExternalRelocations()
388 // get where reloc addresses start
389 // these address are always relative to first writable segment because they are in cache which always
390 // has writable segments far from read-only segments
391 pint_t firstWritableSegmentBaseAddress = 0;
392 const std::vector<MachOLayoutAbstraction::Segment>& segments = this->fLayout.getSegments();
393 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
394 const MachOLayoutAbstraction::Segment& seg = *it;
395 if ( seg.writable() ) {
396 firstWritableSegmentBaseAddress = seg.newAddress();
401 // loop through all external relocation records and bind each
402 const macho_relocation_info<P>* const relocsStart = (macho_relocation_info<P>*)(&this->fLinkEditBase[fDynamicInfo->extreloff()]);
403 const macho_relocation_info<P>* const relocsEnd = &relocsStart[fDynamicInfo->nextrel()];
404 for (const macho_relocation_info<P>* reloc=relocsStart; reloc < relocsEnd; ++reloc) {
405 if ( reloc->r_length() != pointerRelocSize() )
406 throw "bad external relocation length";
407 if ( reloc->r_type() != pointerRelocType() )
408 throw "unknown external relocation type";
409 if ( reloc->r_pcrel() )
410 throw "r_pcrel external relocaiton not supported";
412 const macho_nlist<P>* undefinedSymbol = &fSymbolTable[reloc->r_symbolnum()];
415 location = mappedAddressForNewAddress(reloc->r_address() + firstWritableSegmentBaseAddress);
417 catch (const char* msg) {
418 throwf("%s processesing external relocation r_address 0x%08X", msg, reloc->r_address());
420 pint_t addend = P::getP(*location);
421 if ( fOriginallyPrebound ) {
422 // in a prebound binary, the n_value field of an undefined symbol is set to the address where the symbol was found when prebound
423 // so, subtracting that gives the initial displacement which we need to add to the newly found symbol address
424 // if mach-o relocation structs had an "addend" field this complication would not be necessary.
425 addend -= undefinedSymbol->n_value();
426 // To further complicate things, if this is defined symbol, then its n_value has already been adjust to the
427 // new base address, so we need to back off the slide too..
428 if ( (undefinedSymbol->n_type() & N_TYPE) == N_SECT ) {
429 addend += this->getSlideForNewAddress(undefinedSymbol->n_value());
432 pint_t symbolAddr = this->resolveUndefined(undefinedSymbol);
433 //fprintf(stderr, "external reloc: r_address=0x%08X, r_sym=%s, symAddr=0x%08llX, addend=0x%08llX in %s\n",
434 // reloc->r_address(), &fStrings[undefinedSymbol->n_strx()], (uint64_t)symbolAddr, (uint64_t)addend, this->getDylibID());
435 P::setP(*location, symbolAddr + addend);
440 // most architectures use pure code, unmodifiable stubs
441 template <typename A>
442 void Binder<A>::bindStub(uint8_t elementSize, uint8_t* location, pint_t vmlocation, pint_t value)
447 // x86 supports fast stubs
449 void Binder<x86>::bindStub(uint8_t elementSize, uint8_t* location, pint_t vmlocation, pint_t value)
451 // if the stub is not 5-bytes, it is an old slow stub
452 if ( elementSize == 5 ) {
453 uint32_t rel32 = value - (vmlocation + 5);
454 location[0] = 0xE9; // JMP rel32
455 location[1] = rel32 & 0xFF;
456 location[2] = (rel32 >> 8) & 0xFF;
457 location[3] = (rel32 >> 16) & 0xFF;
458 location[4] = (rel32 >> 24) & 0xFF;
462 template <typename A>
463 void Binder<A>::doBindIndirectSymbols()
465 const uint32_t* const indirectTable = (uint32_t*)&this->fLinkEditBase[fDynamicInfo->indirectsymoff()];
466 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)this->fHeader + sizeof(macho_header<P>));
467 const uint32_t cmd_count = this->fHeader->ncmds();
468 const macho_load_command<P>* cmd = cmds;
469 for (uint32_t i = 0; i < cmd_count; ++i) {
470 if ( cmd->cmd() == macho_segment_command<P>::CMD ) {
471 const macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd;
472 const macho_section<P>* const sectionsStart = (macho_section<P>*)((uint8_t*)seg + sizeof(macho_segment_command<P>));
473 const macho_section<P>* const sectionsEnd = §ionsStart[seg->nsects()];
474 for (const macho_section<P>* sect=sectionsStart; sect < sectionsEnd; ++sect) {
475 uint8_t elementSize = 0;
476 uint8_t sectionType = sect->flags() & SECTION_TYPE;
477 switch ( sectionType ) {
479 elementSize = sect->reserved2();
481 case S_NON_LAZY_SYMBOL_POINTERS:
482 case S_LAZY_SYMBOL_POINTERS:
483 elementSize = sizeof(pint_t);
486 if ( elementSize != 0 ) {
487 uint32_t elementCount = sect->size() / elementSize;
488 const uint32_t indirectTableOffset = sect->reserved1();
489 uint8_t* location = NULL;
490 if ( sect->size() != 0 )
491 location = (uint8_t*)this->mappedAddressForNewAddress(sect->addr());
492 pint_t vmlocation = sect->addr();
493 for (uint32_t j=0; j < elementCount; ++j, location += elementSize, vmlocation += elementSize) {
494 uint32_t symbolIndex = E::get32(indirectTable[indirectTableOffset + j]);
495 switch ( symbolIndex ) {
496 case INDIRECT_SYMBOL_ABS:
497 case INDIRECT_SYMBOL_LOCAL:
500 const macho_nlist<P>* undefinedSymbol = &fSymbolTable[symbolIndex];
501 pint_t symbolAddr = this->resolveUndefined(undefinedSymbol);
502 switch ( sectionType ) {
503 case S_NON_LAZY_SYMBOL_POINTERS:
504 case S_LAZY_SYMBOL_POINTERS:
505 P::setP(*((pint_t*)location), symbolAddr);
508 this->bindStub(elementSize, location, vmlocation, symbolAddr);
517 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
524 template <typename A>
525 typename A::P::uint_t Binder<A>::resolveUndefined(const macho_nlist<P>* undefinedSymbol)
527 if ( (undefinedSymbol->n_type() & N_TYPE) == N_SECT ) {
528 if ( (undefinedSymbol->n_type() & N_PEXT) != 0 ) {
529 // is a multi-module private_extern internal reference that the linker did not optimize away
530 return undefinedSymbol->n_value();
532 if ( (undefinedSymbol->n_desc() & N_WEAK_DEF) != 0 ) {
533 // is a weak definition, we should prebind to this one in the same linkage unit
534 return undefinedSymbol->n_value();
537 const char* symbolName = &fStrings[undefinedSymbol->n_strx()];
538 if ( (this->fHeader->flags() & MH_TWOLEVEL) == 0 ) {
539 // flat namespace binding
540 throw "flat namespace not supported";
543 uint8_t ordinal = GET_LIBRARY_ORDINAL(undefinedSymbol->n_desc());
544 Binder<A>* binder = NULL;
546 case EXECUTABLE_ORDINAL:
547 case DYNAMIC_LOOKUP_ORDINAL:
548 throw "magic ordineal not supported";
549 case SELF_LIBRARY_ORDINAL:
553 if ( ordinal > fDependentDylibs.size() )
554 throw "two-level ordinal out of range";
555 binder = fDependentDylibs[ordinal-1].binder;
557 const macho_nlist<P>* sym = binder->findExportedSymbol(symbolName);
559 throwf("could not resolve %s from %s", symbolName, this->getDylibID());
560 return sym->n_value();
564 template <typename A>
565 const macho_nlist<typename A::P>* Binder<A>::findExportedSymbol(const char* name)
567 //fprintf(stderr, "findExportedSymbol(%s) in %s\n", name, this->getDylibID());
568 const macho_nlist<P>* sym = NULL;
569 typename NameToSymbolMap::iterator pos = fHashTable.find(name);
570 if ( pos != fHashTable.end() )
574 for (typename std::vector<BinderAndReExportFlag>::iterator it = fDependentDylibs.begin(); it != fDependentDylibs.end(); ++it) {
575 if ( it->reExport ) {
576 sym = it->binder->findExportedSymbol(name);
586 #endif // __MACHO_BINDER__