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_REBASER__
26 #define __MACHO_REBASER__
28 #include <sys/types.h>
31 #include <mach/mach.h>
38 #include <mach-o/loader.h>
39 #include <mach-o/fat.h>
40 #include <mach-o/reloc.h>
41 #include <mach-o/ppc/reloc.h>
42 #include <mach-o/x86_64/reloc.h>
46 #include "MachOFileAbstraction.hpp"
47 #include "Architectures.hpp"
48 #include "MachOLayout.hpp"
55 virtual cpu_type_t getArchitecture() const = 0;
56 virtual uint64_t getBaseAddress() const = 0;
57 virtual uint64_t getVMSize() const = 0;
58 virtual void rebase() = 0;
63 class Rebaser : public AbstractRebaser
66 Rebaser(const MachOLayoutAbstraction&);
69 virtual cpu_type_t getArchitecture() const;
70 virtual uint64_t getBaseAddress() const;
71 virtual uint64_t getVMSize() const;
72 virtual void rebase();
75 typedef typename A::P P;
76 typedef typename A::P::E E;
77 typedef typename A::P::uint_t pint_t;
79 pint_t* mappedAddressForNewAddress(pint_t vmaddress);
80 pint_t getSlideForNewAddress(pint_t newAddress);
83 pint_t calculateRelocBase();
84 void adjustLoadCommands();
85 void adjustSymbolTable();
88 void adjustSegmentLoadCommand(macho_segment_command<P>* seg);
89 pint_t getSlideForVMAddress(pint_t vmaddress);
90 pint_t* mappedAddressForVMAddress(pint_t vmaddress);
91 pint_t* mappedAddressForRelocAddress(pint_t r_address);
92 void adjustRelocBaseAddresses();
93 const uint8_t* doCodeUpdateForEachULEB128Address(const uint8_t* p, uint8_t kind, uint64_t orgBaseAddress, int64_t codeToDataDelta, int64_t codeToImportDelta);
94 void doCodeUpdate(uint8_t kind, uint64_t address, int64_t codeToDataDelta, int64_t codeToImportDelta);
95 void doLocalRelocation(const macho_relocation_info<P>* reloc);
96 bool unequalSlides() const;
99 const macho_header<P>* fHeader;
100 uint8_t* fLinkEditBase; // add file offset to this to get linkedit content
101 const MachOLayoutAbstraction& fLayout;
103 pint_t fOrignalVMRelocBaseAddress; // add reloc address to this to get original address reloc referred to
104 bool fSplittingSegments;
109 template <typename A>
110 Rebaser<A>::Rebaser(const MachOLayoutAbstraction& layout)
111 : fLayout(layout), fOrignalVMRelocBaseAddress(NULL), fLinkEditBase(NULL), fSplittingSegments(false)
113 fHeader = (const macho_header<P>*)fLayout.getSegments()[0].mappedAddress();
114 switch ( fHeader->filetype() ) {
119 throw "file is not a dylib or bundle";
122 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
123 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
124 const MachOLayoutAbstraction::Segment& seg = *it;
125 if ( strcmp(seg.name(), "__LINKEDIT") == 0 ) {
126 fLinkEditBase = (uint8_t*)seg.mappedAddress() - seg.fileOffset();
130 if ( fLinkEditBase == NULL )
131 throw "no __LINKEDIT segment";
133 fOrignalVMRelocBaseAddress = calculateRelocBase();
135 fSplittingSegments = layout.hasSplitSegInfo() && this->unequalSlides();
138 template <> cpu_type_t Rebaser<ppc>::getArchitecture() const { return CPU_TYPE_POWERPC; }
139 template <> cpu_type_t Rebaser<ppc64>::getArchitecture() const { return CPU_TYPE_POWERPC64; }
140 template <> cpu_type_t Rebaser<x86>::getArchitecture() const { return CPU_TYPE_I386; }
141 template <> cpu_type_t Rebaser<x86_64>::getArchitecture() const { return CPU_TYPE_X86_64; }
143 template <typename A>
144 bool Rebaser<A>::unequalSlides() const
146 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
147 uint64_t slide = segments[0].newAddress() - segments[0].address();
148 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
149 const MachOLayoutAbstraction::Segment& seg = *it;
150 if ( (seg.newAddress() - seg.address()) != slide )
156 template <typename A>
157 uint64_t Rebaser<A>::getBaseAddress() const
159 return fLayout.getSegments()[0].address();
162 template <typename A>
163 uint64_t Rebaser<A>::getVMSize() const
165 uint64_t highestVMAddress = 0;
166 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
167 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
168 const MachOLayoutAbstraction::Segment& seg = *it;
169 if ( seg.address() > highestVMAddress )
170 highestVMAddress = seg.address();
172 return (((highestVMAddress - getBaseAddress()) + 4095) & (-4096));
177 template <typename A>
178 void Rebaser<A>::rebase()
180 // update writable segments that have internal pointers
183 // if splitting segments, update code-to-data references
186 // change address on relocs now that segments are split
187 this->adjustRelocBaseAddresses();
189 // update load commands
190 this->adjustLoadCommands();
192 // update symbol table
193 this->adjustSymbolTable();
197 void Rebaser<x86>::adjustSegmentLoadCommand(macho_segment_command<P>* seg)
199 // __IMPORT segments are not-writable in shared cache
200 if ( strcmp(seg->segname(), "__IMPORT") == 0 )
201 seg->set_initprot(VM_PROT_READ|VM_PROT_EXECUTE);
204 template <typename A>
205 void Rebaser<A>::adjustSegmentLoadCommand(macho_segment_command<P>* seg)
210 template <typename A>
211 void Rebaser<A>::adjustLoadCommands()
213 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)fHeader + sizeof(macho_header<P>));
214 const uint32_t cmd_count = fHeader->ncmds();
215 const macho_load_command<P>* cmd = cmds;
216 for (uint32_t i = 0; i < cmd_count; ++i) {
217 switch ( cmd->cmd() ) {
219 if ( (fHeader->flags() & MH_PREBOUND) != 0 ) {
220 // clear timestamp so that any prebound clients are invalidated
221 macho_dylib_command<P>* dylib = (macho_dylib_command<P>*)cmd;
222 dylib->set_timestamp(1);
226 case LC_LOAD_WEAK_DYLIB:
227 case LC_REEXPORT_DYLIB:
228 if ( (fHeader->flags() & MH_PREBOUND) != 0 ) {
229 // clear expected timestamps so that this image will load with invalid prebinding
230 macho_dylib_command<P>* dylib = (macho_dylib_command<P>*)cmd;
231 dylib->set_timestamp(2);
234 case macho_routines_command<P>::CMD:
235 // update -init command
237 struct macho_routines_command<P>* routines = (struct macho_routines_command<P>*)cmd;
238 routines->set_init_address(routines->init_address() + this->getSlideForVMAddress(routines->init_address()));
241 case macho_segment_command<P>::CMD:
242 // update segment commands
244 macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd;
245 this->adjustSegmentLoadCommand(seg);
246 pint_t slide = this->getSlideForVMAddress(seg->vmaddr());
247 seg->set_vmaddr(seg->vmaddr() + slide);
248 macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)seg + sizeof(macho_segment_command<P>));
249 macho_section<P>* const sectionsEnd = §ionsStart[seg->nsects()];
250 for(macho_section<P>* sect = sectionsStart; sect < sectionsEnd; ++sect) {
251 sect->set_addr(sect->addr() + slide);
256 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
262 template <typename A>
263 typename A::P::uint_t Rebaser<A>::getSlideForVMAddress(pint_t vmaddress)
265 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
266 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
267 const MachOLayoutAbstraction::Segment& seg = *it;
268 if ( (seg.address() <= vmaddress) && (seg.size() != 0) && ((vmaddress < (seg.address()+seg.size())) || (seg.address() == vmaddress)) ) {
269 return seg.newAddress() - seg.address();
272 throwf("vm address 0x%08llX not found", (uint64_t)vmaddress);
276 template <typename A>
277 typename A::P::uint_t* Rebaser<A>::mappedAddressForVMAddress(pint_t vmaddress)
279 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
280 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
281 const MachOLayoutAbstraction::Segment& seg = *it;
282 if ( (seg.address() <= vmaddress) && (vmaddress < (seg.address()+seg.size())) ) {
283 return (pint_t*)((vmaddress - seg.address()) + (uint8_t*)seg.mappedAddress());
286 throwf("mappedAddressForVMAddress(0x%08llX) not found", (uint64_t)vmaddress);
289 template <typename A>
290 typename A::P::uint_t* Rebaser<A>::mappedAddressForNewAddress(pint_t vmaddress)
292 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
293 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
294 const MachOLayoutAbstraction::Segment& seg = *it;
295 if ( (seg.newAddress() <= vmaddress) && (vmaddress < (seg.newAddress()+seg.size())) ) {
296 return (pint_t*)((vmaddress - seg.newAddress()) + (uint8_t*)seg.mappedAddress());
299 throwf("mappedAddressForNewAddress(0x%08llX) not found", (uint64_t)vmaddress);
302 template <typename A>
303 typename A::P::uint_t Rebaser<A>::getSlideForNewAddress(pint_t newAddress)
305 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
306 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
307 const MachOLayoutAbstraction::Segment& seg = *it;
308 if ( (seg.newAddress() <= newAddress) && (newAddress < (seg.newAddress()+seg.size())) ) {
309 return seg.newAddress() - seg.address();
312 throwf("new address 0x%08llX not found", (uint64_t)newAddress);
315 template <typename A>
316 typename A::P::uint_t* Rebaser<A>::mappedAddressForRelocAddress(pint_t r_address)
318 return this->mappedAddressForVMAddress(r_address + fOrignalVMRelocBaseAddress);
322 template <typename A>
323 void Rebaser<A>::adjustSymbolTable()
325 const macho_dysymtab_command<P>* dysymtab = NULL;
326 macho_nlist<P>* symbolTable = NULL;
328 // get symbol table info
329 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)fHeader + sizeof(macho_header<P>));
330 const uint32_t cmd_count = fHeader->ncmds();
331 const macho_load_command<P>* cmd = cmds;
332 for (uint32_t i = 0; i < cmd_count; ++i) {
333 switch (cmd->cmd()) {
336 const macho_symtab_command<P>* symtab = (macho_symtab_command<P>*)cmd;
337 symbolTable = (macho_nlist<P>*)(&fLinkEditBase[symtab->symoff()]);
341 dysymtab = (macho_dysymtab_command<P>*)cmd;
344 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
347 // walk all exports and slide their n_value
348 macho_nlist<P>* lastExport = &symbolTable[dysymtab->iextdefsym()+dysymtab->nextdefsym()];
349 for (macho_nlist<P>* entry = &symbolTable[dysymtab->iextdefsym()]; entry < lastExport; ++entry) {
350 if ( (entry->n_type() & N_TYPE) == N_SECT )
351 entry->set_n_value(entry->n_value() + this->getSlideForVMAddress(entry->n_value()));
354 // walk all local symbols and slide their n_value (don't adjust and stabs)
355 macho_nlist<P>* lastLocal = &symbolTable[dysymtab->ilocalsym()+dysymtab->nlocalsym()];
356 for (macho_nlist<P>* entry = &symbolTable[dysymtab->ilocalsym()]; entry < lastLocal; ++entry) {
357 if ( (entry->n_sect() != NO_SECT) && ((entry->n_type() & N_STAB) == 0) )
358 entry->set_n_value(entry->n_value() + this->getSlideForVMAddress(entry->n_value()));
365 template <typename A>
366 void Rebaser<A>::doCodeUpdate(uint8_t kind, uint64_t address, int64_t codeToDataDelta, int64_t codeToImportDelta)
368 //fprintf(stderr, "doCodeUpdate(kind=%d, address=0x%0llX, dataDelta=0x%08llX, importDelta=0x%08llX)\n", kind, address, codeToDataDelta, codeToImportDelta);
370 uint32_t instruction;
374 case 1: // 32-bit pointer
375 p = (uint32_t*)mappedAddressForVMAddress(address);
376 value = A::P::E::get32(*p);
377 value += codeToDataDelta;
378 A::P::E::set32(*p, value);
380 case 2: // 64-bit pointer
381 p = (uint32_t*)mappedAddressForVMAddress(address);
382 value64 = A::P::E::get64(*(uint64_t*)p);
383 value64 += codeToDataDelta;
384 A::P::E::set64(*(uint64_t*)p, value64);
386 case 3: // used only for ppc/ppc64, an instruction that sets the hi16 of a register
387 // adjust low 16 bits of instruction which contain hi16 of distance to something in DATA
388 if ( (codeToDataDelta & 0xFFFF) != 0 )
389 throwf("codeToDataDelta=0x%0llX is not a multiple of 64K", codeToDataDelta);
390 p = (uint32_t*)mappedAddressForVMAddress(address);
391 instruction = BigEndian::get32(*p);
392 uint16_t originalLo16 = instruction & 0x0000FFFF;
393 uint16_t delta64Ks = codeToDataDelta >> 16;
394 instruction = (instruction & 0xFFFF0000) | ((originalLo16+delta64Ks) & 0x0000FFFF);
395 BigEndian::set32(*p, instruction);
397 case 4: // only used for i386, a reference to something in the IMPORT segment
398 p = (uint32_t*)mappedAddressForVMAddress(address);
399 value = A::P::E::get32(*p);
400 value += codeToImportDelta;
401 A::P::E::set32(*p, value);
404 throwf("invalid kind=%d in split seg info", kind);
408 template <typename A>
409 const uint8_t* Rebaser<A>::doCodeUpdateForEachULEB128Address(const uint8_t* p, uint8_t kind, uint64_t orgBaseAddress, int64_t codeToDataDelta, int64_t codeToImportDelta)
411 uint64_t address = 0;
417 delta |= ((byte & 0x7F) << shift);
422 doCodeUpdate(kind, address+orgBaseAddress, codeToDataDelta, codeToImportDelta);
434 template <typename A>
435 void Rebaser<A>::adjustCode()
437 if ( fSplittingSegments ) {
438 // get uleb128 compressed runs of code addresses to update
439 const uint8_t* infoStart = NULL;
440 const uint8_t* infoEnd = NULL;
441 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)fHeader + sizeof(macho_header<P>));
442 const uint32_t cmd_count = fHeader->ncmds();
443 const macho_load_command<P>* cmd = cmds;
444 for (uint32_t i = 0; i < cmd_count; ++i) {
445 switch (cmd->cmd()) {
446 case LC_SEGMENT_SPLIT_INFO:
448 const macho_linkedit_data_command<P>* segInfo = (macho_linkedit_data_command<P>*)cmd;
449 infoStart = &fLinkEditBase[segInfo->dataoff()];
450 infoEnd = &infoStart[segInfo->datasize()];
454 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
456 // calculate how much we need to slide writable segments
457 const uint64_t orgBaseAddress = this->getBaseAddress();
458 int64_t codeToDataDelta = 0;
459 int64_t codeToImportDelta = 0;
460 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
461 const MachOLayoutAbstraction::Segment& codeSeg = segments[0];
462 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
463 const MachOLayoutAbstraction::Segment& dataSeg = *it;
464 if ( strcmp(dataSeg.name(), "__IMPORT") == 0 )
465 codeToImportDelta = (dataSeg.newAddress() - codeSeg.newAddress()) - (dataSeg.address() - codeSeg.address());
466 else if ( dataSeg.writable() )
467 codeToDataDelta = (dataSeg.newAddress() - codeSeg.newAddress()) - (dataSeg.address() - codeSeg.address());
469 // decompress and call doCodeUpdate() on each address
470 for(const uint8_t* p = infoStart; *p != 0;) {
472 p = this->doCodeUpdateForEachULEB128Address(p, kind, orgBaseAddress, codeToDataDelta, codeToImportDelta);
478 template <typename A>
479 void Rebaser<A>::adjustDATA()
481 const macho_dysymtab_command<P>* dysymtab = NULL;
483 // get symbol table info
484 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)fHeader + sizeof(macho_header<P>));
485 const uint32_t cmd_count = fHeader->ncmds();
486 const macho_load_command<P>* cmd = cmds;
487 for (uint32_t i = 0; i < cmd_count; ++i) {
488 switch (cmd->cmd()) {
490 dysymtab = (macho_dysymtab_command<P>*)cmd;
493 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
497 // walk all local relocations and slide every pointer
498 const macho_relocation_info<P>* const relocsStart = (macho_relocation_info<P>*)(&fLinkEditBase[dysymtab->locreloff()]);
499 const macho_relocation_info<P>* const relocsEnd = &relocsStart[dysymtab->nlocrel()];
500 for (const macho_relocation_info<P>* reloc=relocsStart; reloc < relocsEnd; ++reloc) {
501 this->doLocalRelocation(reloc);
504 // walk non-lazy-pointers and slide the ones that are LOCAL
506 for (uint32_t i = 0; i < cmd_count; ++i) {
507 if ( cmd->cmd() == macho_segment_command<P>::CMD ) {
508 const macho_segment_command<P>* seg = (macho_segment_command<P>*)cmd;
509 const macho_section<P>* const sectionsStart = (macho_section<P>*)((char*)seg + sizeof(macho_segment_command<P>));
510 const macho_section<P>* const sectionsEnd = §ionsStart[seg->nsects()];
511 const uint32_t* const indirectTable = (uint32_t*)(&fLinkEditBase[dysymtab->indirectsymoff()]);
512 for(const macho_section<P>* sect = sectionsStart; sect < sectionsEnd; ++sect) {
513 if ( (sect->flags() & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS ) {
514 const uint32_t indirectTableOffset = sect->reserved1();
515 uint32_t pointerCount = sect->size() / sizeof(pint_t);
516 pint_t* nonLazyPointerAddr = this->mappedAddressForVMAddress(sect->addr());
517 for (uint32_t j=0; j < pointerCount; ++j, ++nonLazyPointerAddr) {
518 if ( E::get32(indirectTable[indirectTableOffset + j]) == INDIRECT_SYMBOL_LOCAL ) {
519 pint_t value = A::P::getP(*nonLazyPointerAddr);
520 P::setP(*nonLazyPointerAddr, value + this->getSlideForVMAddress(value));
526 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
531 template <typename A>
532 void Rebaser<A>::adjustRelocBaseAddresses()
534 // split seg file alreday have reloc base of first writable segment
535 // only non-split-segs that are being split need this adjusted
536 if ( (fHeader->flags() & MH_SPLIT_SEGS) == 0 ) {
538 // get symbol table to find relocation records
539 const macho_dysymtab_command<P>* dysymtab = NULL;
540 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)fHeader + sizeof(macho_header<P>));
541 const uint32_t cmd_count = fHeader->ncmds();
542 const macho_load_command<P>* cmd = cmds;
543 for (uint32_t i = 0; i < cmd_count; ++i) {
544 switch (cmd->cmd()) {
546 dysymtab = (macho_dysymtab_command<P>*)cmd;
549 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
552 // get amount to adjust reloc address
553 int32_t relocAddressAdjust = 0;
554 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
555 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
556 const MachOLayoutAbstraction::Segment& seg = *it;
557 if ( seg.writable() ) {
558 relocAddressAdjust = seg.address() - segments[0].address();
563 // walk all local relocations and adjust every address
564 macho_relocation_info<P>* const relocsStart = (macho_relocation_info<P>*)(&fLinkEditBase[dysymtab->locreloff()]);
565 macho_relocation_info<P>* const relocsEnd = &relocsStart[dysymtab->nlocrel()];
566 for (macho_relocation_info<P>* reloc=relocsStart; reloc < relocsEnd; ++reloc) {
567 reloc->set_r_address(reloc->r_address()-relocAddressAdjust);
570 // walk all external relocations and adjust every address
571 macho_relocation_info<P>* const externRelocsStart = (macho_relocation_info<P>*)(&fLinkEditBase[dysymtab->extreloff()]);
572 macho_relocation_info<P>* const externRelocsEnd = &externRelocsStart[dysymtab->nextrel()];
573 for (macho_relocation_info<P>* reloc=externRelocsStart; reloc < externRelocsEnd; ++reloc) {
574 reloc->set_r_address(reloc->r_address()-relocAddressAdjust);
580 void Rebaser<x86_64>::adjustRelocBaseAddresses()
582 // x86_64 already have reloc base of first writable segment
587 void Rebaser<x86_64>::doLocalRelocation(const macho_relocation_info<x86_64::P>* reloc)
589 if ( reloc->r_type() == X86_64_RELOC_UNSIGNED ) {
590 pint_t* addr = this->mappedAddressForRelocAddress(reloc->r_address());
591 pint_t value = P::getP(*addr);
592 P::setP(*addr, value + this->getSlideForVMAddress(value));
595 throw "invalid relocation type";
600 void Rebaser<ppc>::doLocalRelocation(const macho_relocation_info<P>* reloc)
602 if ( (reloc->r_address() & R_SCATTERED) == 0 ) {
603 if ( reloc->r_type() == GENERIC_RELOC_VANILLA ) {
604 pint_t* addr = this->mappedAddressForRelocAddress(reloc->r_address());
605 pint_t value = P::getP(*addr);
606 P::setP(*addr, value + this->getSlideForVMAddress(value));
610 macho_scattered_relocation_info<P>* sreloc = (macho_scattered_relocation_info<P>*)reloc;
611 if ( sreloc->r_type() == PPC_RELOC_PB_LA_PTR ) {
612 sreloc->set_r_value( sreloc->r_value() + this->getSlideForVMAddress(sreloc->r_value()) );
615 throw "cannot rebase final linked image with scattered relocations";
621 void Rebaser<x86>::doLocalRelocation(const macho_relocation_info<P>* reloc)
623 if ( (reloc->r_address() & R_SCATTERED) == 0 ) {
624 if ( reloc->r_type() == GENERIC_RELOC_VANILLA ) {
625 pint_t* addr = this->mappedAddressForRelocAddress(reloc->r_address());
626 pint_t value = P::getP(*addr);
627 P::setP(*addr, value + this->getSlideForVMAddress(value));
631 macho_scattered_relocation_info<P>* sreloc = (macho_scattered_relocation_info<P>*)reloc;
632 if ( sreloc->r_type() == GENERIC_RELOC_PB_LA_PTR ) {
633 sreloc->set_r_value( sreloc->r_value() + this->getSlideForVMAddress(sreloc->r_value()) );
636 throw "cannot rebase final linked image with scattered relocations";
641 template <typename A>
642 void Rebaser<A>::doLocalRelocation(const macho_relocation_info<P>* reloc)
644 if ( (reloc->r_address() & R_SCATTERED) == 0 ) {
645 if ( reloc->r_type() == GENERIC_RELOC_VANILLA ) {
646 pint_t* addr = this->mappedAddressForRelocAddress(reloc->r_address());
647 pint_t value = P::getP(*addr);
648 P::setP(*addr, value + this->getSlideForVMAddress(value));
652 throw "cannot rebase final linked image with scattered relocations";
657 template <typename A>
658 typename A::P::uint_t Rebaser<A>::calculateRelocBase()
660 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
661 if ( fHeader->flags() & MH_SPLIT_SEGS ) {
662 // reloc addresses are from the start of the first writable segment
663 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
664 const MachOLayoutAbstraction::Segment& seg = *it;
665 if ( seg.writable() ) {
666 // found first writable segment
667 return seg.address();
670 throw "no writable segment";
673 // reloc addresses are from the start of the mapped file (base address)
674 return segments[0].address();
679 ppc64::P::uint_t Rebaser<ppc64>::calculateRelocBase()
681 // reloc addresses either:
682 // 1) from the first segment vmaddr if no writable segment is > 4GB from first segment vmaddr
683 // 2) from start of first writable segment
684 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
685 uint64_t threshold = segments[0].address() + 0x100000000ULL;
686 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
687 const MachOLayoutAbstraction::Segment& seg = *it;
688 if ( seg.writable() && (seg.address()+seg.size()) > threshold ) {
689 // found writable segment with address > 4GB past base address
690 return seg.address();
693 // just use base address
694 return segments[0].address();
698 x86_64::P::uint_t Rebaser<x86_64>::calculateRelocBase()
700 // reloc addresses are always based from the start of the first writable segment
701 const std::vector<MachOLayoutAbstraction::Segment>& segments = fLayout.getSegments();
702 for(std::vector<MachOLayoutAbstraction::Segment>::const_iterator it = segments.begin(); it != segments.end(); ++it) {
703 const MachOLayoutAbstraction::Segment& seg = *it;
704 if ( seg.writable() ) {
705 // found first writable segment
706 return seg.address();
709 throw "no writable segment";
714 class MultiArchRebaser
717 MultiArchRebaser::MultiArchRebaser(const char* path, bool writable=false)
718 : fMappingAddress(0), fFileSize(0)
721 int fd = ::open(path, (writable ? O_RDWR : O_RDONLY), 0);
723 throwf("can't open file, errno=%d", errno);
724 struct stat stat_buf;
725 if ( fstat(fd, &stat_buf) == -1)
726 throwf("can't stat open file %s, errno=%d", path, errno);
727 if ( stat_buf.st_size < 20 )
728 throwf("file too small %s", path);
729 const int prot = writable ? (PROT_READ | PROT_WRITE) : PROT_READ;
730 const int flags = writable ? (MAP_FILE | MAP_SHARED) : (MAP_FILE | MAP_PRIVATE);
731 uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, prot, flags, fd, 0);
732 if ( p == (uint8_t*)(-1) )
733 throwf("can't map file %s, errno=%d", path, errno);
736 // if fat file, process each architecture
737 const fat_header* fh = (fat_header*)p;
738 const mach_header* mh = (mach_header*)p;
739 if ( fh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
740 // Fat header is always big-endian
741 const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header));
742 for (unsigned long i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
743 uint32_t fileOffset = OSSwapBigToHostInt32(archs[i].offset);
745 switch ( OSSwapBigToHostInt32(archs[i].cputype) ) {
746 case CPU_TYPE_POWERPC:
747 fRebasers.push_back(new Rebaser<ppc>(&p[fileOffset]));
749 case CPU_TYPE_POWERPC64:
750 fRebasers.push_back(new Rebaser<ppc64>(&p[fileOffset]));
753 fRebasers.push_back(new Rebaser<x86>(&p[fileOffset]));
755 case CPU_TYPE_X86_64:
756 fRebasers.push_back(new Rebaser<x86_64>(&p[fileOffset]));
759 throw "unknown file format";
762 catch (const char* msg) {
763 fprintf(stderr, "rebase warning: %s for %s\n", msg, path);
769 if ( (OSSwapBigToHostInt32(mh->magic) == MH_MAGIC) && (OSSwapBigToHostInt32(mh->cputype) == CPU_TYPE_POWERPC)) {
770 fRebasers.push_back(new Rebaser<ppc>(mh));
772 else if ( (OSSwapBigToHostInt32(mh->magic) == MH_MAGIC_64) && (OSSwapBigToHostInt32(mh->cputype) == CPU_TYPE_POWERPC64)) {
773 fRebasers.push_back(new Rebaser<ppc64>(mh));
775 else if ( (OSSwapLittleToHostInt32(mh->magic) == MH_MAGIC) && (OSSwapLittleToHostInt32(mh->cputype) == CPU_TYPE_I386)) {
776 fRebasers.push_back(new Rebaser<x86>(mh));
778 else if ( (OSSwapLittleToHostInt32(mh->magic) == MH_MAGIC_64) && (OSSwapLittleToHostInt32(mh->cputype) == CPU_TYPE_X86_64)) {
779 fRebasers.push_back(new Rebaser<x86_64>(mh));
782 throw "unknown file format";
785 catch (const char* msg) {
786 fprintf(stderr, "rebase warning: %s for %s\n", msg, path);
791 fFileSize = stat_buf.st_size;
795 ~MultiArchRebaser() {::munmap(fMappingAddress, fFileSize); }
797 const std::vector<AbstractRebaser*>& getArchs() const { return fRebasers; }
798 void commit() { ::msync(fMappingAddress, fFileSize, MS_ASYNC); }
801 std::vector<AbstractRebaser*> fRebasers;
802 void* fMappingAddress;
808 #endif // __MACHO_REBASER__