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_LAYOUT__
26 #define __MACHO_LAYOUT__
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"
48 void throwf(const char* format, ...) __attribute__((format(printf, 1, 2)));
50 __attribute__((noreturn))
51 void throwf(const char* format, ...)
55 va_start(list, format);
56 vasprintf(&p, format, list);
64 class MachOLayoutAbstraction
70 Segment(uint64_t addr, uint64_t vmsize, uint64_t offset, uint64_t file_size,
71 uint32_t prot, const char* segName) : fAddress(addr), fSize(vmsize),
72 fFileOffset(offset), fFileSize(file_size), fPermissions(prot),
73 fNewAddress(0), fMappedAddress(NULL) {
74 strlcpy(fName, segName, 16);
77 uint64_t address() const { return fAddress; }
78 uint64_t size() const { return fSize; }
79 uint64_t fileOffset() const { return fFileOffset; }
80 uint64_t fileSize() const { return fFileSize; }
81 uint32_t permissions() const { return fPermissions; }
82 bool readable() const { return fPermissions & VM_PROT_READ; }
83 bool writable() const { return fPermissions & VM_PROT_WRITE; }
84 bool executable() const { return fPermissions & VM_PROT_EXECUTE; }
85 const char* name() const { return fName; }
86 uint64_t newAddress() const { return fNewAddress; }
87 void* mappedAddress() const { return fMappedAddress; }
88 void setNewAddress(uint64_t addr) { fNewAddress = addr; }
89 void setMappedAddress(void* addr) { fMappedAddress = addr; }
90 void setSize(uint64_t new_size) { fSize = new_size; }
91 void setFileOffset(uint64_t new_off) { fFileOffset = new_off; }
92 void setFileSize(uint64_t new_size) { fFileSize = new_size; }
93 void setWritable(bool writable) { if (writable) fPermissions |= VM_PROT_WRITE; else fPermissions &= ~VM_PROT_WRITE; }
100 void* fMappedAddress;
101 uint32_t fPermissions;
108 uint32_t currentVersion;
109 uint32_t compatibilityVersion;
113 virtual cpu_type_t getArchitecture() const = 0;
114 virtual const char* getFilePath() const = 0;
115 virtual uint64_t getOffsetInUniversalFile() const = 0;
116 virtual uint32_t getFileType() const = 0;
117 virtual uint32_t getFlags() const = 0;
118 virtual Library getID() const = 0;
119 virtual bool isSplitSeg() const = 0;
120 virtual bool hasSplitSegInfo() const = 0;
121 virtual uint32_t getNameFileOffset() const = 0;
122 virtual time_t getLastModTime() const = 0;
123 virtual ino_t getInode() const = 0;
124 virtual std::vector<Segment>& getSegments() = 0;
125 virtual const std::vector<Segment>& getSegments() const = 0;
126 virtual const std::vector<Library>& getLibraries() const = 0;
127 virtual uint64_t getBaseAddress() const = 0;
128 virtual uint64_t getVMSize() const = 0;
129 virtual uint64_t getBaseExecutableAddress() const = 0;
130 virtual uint64_t getBaseWritableAddress() const = 0;
131 virtual uint64_t getBaseReadOnlyAddress() const = 0;
132 virtual uint64_t getExecutableVMSize() const = 0;
133 virtual uint64_t getWritableVMSize() const = 0;
134 virtual uint64_t getReadOnlyVMSize() const = 0;
140 template <typename A>
141 class MachOLayout : public MachOLayoutAbstraction
144 MachOLayout(const void* machHeader, uint64_t offset, const char* path, ino_t inode, time_t modTime);
145 virtual ~MachOLayout() {}
147 virtual cpu_type_t getArchitecture() const;
148 virtual const char* getFilePath() const { return fPath; }
149 virtual uint64_t getOffsetInUniversalFile() const { return fOffset; }
150 virtual uint32_t getFileType() const { return fFileType; }
151 virtual uint32_t getFlags() const { return fFlags; }
152 virtual Library getID() const { return fDylibID; }
153 virtual bool isSplitSeg() const;
154 virtual bool hasSplitSegInfo() const { return fHasSplitSegInfo; }
155 virtual uint32_t getNameFileOffset() const{ return fNameFileOffset; }
156 virtual time_t getLastModTime() const { return fMTime; }
157 virtual ino_t getInode() const { return fInode; }
158 virtual std::vector<Segment>& getSegments() { return fSegments; }
159 virtual const std::vector<Segment>& getSegments() const { return fSegments; }
160 virtual const std::vector<Library>& getLibraries() const { return fLibraries; }
161 virtual uint64_t getBaseAddress() const { return fLowSegment->address(); }
162 virtual uint64_t getVMSize() const { return fVMSize; }
163 virtual uint64_t getBaseExecutableAddress() const { return fLowExecutableSegment->address(); }
164 virtual uint64_t getBaseWritableAddress() const { return fLowWritableSegment->address(); }
165 virtual uint64_t getBaseReadOnlyAddress() const { return fLowReadOnlySegment->address(); }
166 virtual uint64_t getExecutableVMSize() const { return fVMExecutableSize; }
167 virtual uint64_t getWritableVMSize() const { return fVMWritablSize; }
168 virtual uint64_t getReadOnlyVMSize() const { return fVMReadOnlySize; }
171 typedef typename A::P P;
172 typedef typename A::P::E E;
173 typedef typename A::P::uint_t pint_t;
179 std::vector<Segment> fSegments;
180 std::vector<Library> fLibraries;
181 const Segment* fLowSegment;
182 const Segment* fLowExecutableSegment;
183 const Segment* fLowWritableSegment;
184 const Segment* fLowReadOnlySegment;
186 uint32_t fNameFileOffset;
190 uint64_t fVMExecutableSize;
191 uint64_t fVMWritablSize;
192 uint64_t fVMReadOnlySize;
193 bool fHasSplitSegInfo;
198 class UniversalMachOLayout
201 UniversalMachOLayout(const char* path, const std::set<cpu_type_t>* onlyArchs=NULL);
202 ~UniversalMachOLayout() {}
204 static const UniversalMachOLayout* find(const char* path, const std::set<cpu_type_t>* onlyArchs=NULL);
205 const MachOLayoutAbstraction* getArch(cpu_type_t) const;
206 const std::vector<MachOLayoutAbstraction*>& getArchs() const { return fLayouts; }
209 struct CStringEquals {
210 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
212 typedef __gnu_cxx::hash_map<const char*, const UniversalMachOLayout*, __gnu_cxx::hash<const char*>, CStringEquals> PathToNode;
214 static PathToNode fgLayoutCache;
216 std::vector<MachOLayoutAbstraction*> fLayouts;
219 UniversalMachOLayout::PathToNode UniversalMachOLayout::fgLayoutCache;
222 const MachOLayoutAbstraction* UniversalMachOLayout::getArch(cpu_type_t arch) const
224 for(std::vector<MachOLayoutAbstraction*>::const_iterator it=fLayouts.begin(); it != fLayouts.end(); ++it) {
225 const MachOLayoutAbstraction* layout = *it;
226 if ( layout->getArchitecture() == arch )
233 const UniversalMachOLayout* UniversalMachOLayout::find(const char* path, const std::set<cpu_type_t>* onlyArchs)
236 PathToNode::iterator pos = fgLayoutCache.find(path);
237 if ( pos != fgLayoutCache.end() )
240 // create UniversalMachOLayout
241 const UniversalMachOLayout* result = new UniversalMachOLayout(path, onlyArchs);
244 fgLayoutCache[result->fPath] = result;
250 UniversalMachOLayout::UniversalMachOLayout(const char* path, const std::set<cpu_type_t>* onlyArchs)
251 : fPath(strdup(path))
254 int fd = ::open(path, O_RDONLY, 0);
256 throwf("can't open file, errno=%d", errno);
257 struct stat stat_buf;
258 if ( fstat(fd, &stat_buf) == -1)
259 throwf("can't stat open file %s, errno=%d", path, errno);
260 if ( stat_buf.st_size < 20 )
261 throwf("file too small %s", path);
262 uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
263 if ( p == (uint8_t*)(-1) )
264 throwf("can't map file %s, errno=%d", path, errno);
268 // if fat file, process each architecture
269 const fat_header* fh = (fat_header*)p;
270 const mach_header* mh = (mach_header*)p;
271 if ( fh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
272 // Fat header is always big-endian
273 const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header));
274 for (unsigned long i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
275 uint32_t fileOffset = OSSwapBigToHostInt32(archs[i].offset);
276 cpu_type_t curArch = OSSwapBigToHostInt32(archs[i].cputype);
278 if ( (onlyArchs == NULL) || (onlyArchs->count(curArch) != 0) ) {
280 case CPU_TYPE_POWERPC:
281 fLayouts.push_back(new MachOLayout<ppc>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
283 case CPU_TYPE_POWERPC64:
284 fLayouts.push_back(new MachOLayout<ppc64>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
287 fLayouts.push_back(new MachOLayout<x86>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
289 case CPU_TYPE_X86_64:
290 fLayouts.push_back(new MachOLayout<x86_64>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
293 throw "unknown file format";
297 catch (const char* msg) {
298 fprintf(stderr, "warning: %s for %s\n", msg, path);
304 if ( (OSSwapBigToHostInt32(mh->magic) == MH_MAGIC) && (OSSwapBigToHostInt32(mh->cputype) == CPU_TYPE_POWERPC)) {
305 if ( (onlyArchs == NULL) || (onlyArchs->count(CPU_TYPE_POWERPC) != 0) )
306 fLayouts.push_back(new MachOLayout<ppc>(mh, 0, fPath, stat_buf.st_ino, stat_buf.st_mtime));
308 else if ( (OSSwapBigToHostInt32(mh->magic) == MH_MAGIC_64) && (OSSwapBigToHostInt32(mh->cputype) == CPU_TYPE_POWERPC64)) {
309 if ( (onlyArchs == NULL) || (onlyArchs->count(CPU_TYPE_POWERPC64) != 0) )
310 fLayouts.push_back(new MachOLayout<ppc64>(mh, 0, fPath, stat_buf.st_ino, stat_buf.st_mtime));
312 else if ( (OSSwapLittleToHostInt32(mh->magic) == MH_MAGIC) && (OSSwapLittleToHostInt32(mh->cputype) == CPU_TYPE_I386)) {
313 if ( (onlyArchs == NULL) || (onlyArchs->count(CPU_TYPE_I386) != 0) )
314 fLayouts.push_back(new MachOLayout<x86>(mh, 0, fPath, stat_buf.st_ino, stat_buf.st_mtime));
316 else if ( (OSSwapLittleToHostInt32(mh->magic) == MH_MAGIC_64) && (OSSwapLittleToHostInt32(mh->cputype) == CPU_TYPE_X86_64)) {
317 if ( (onlyArchs == NULL) || (onlyArchs->count(CPU_TYPE_X86_64) != 0) )
318 fLayouts.push_back(new MachOLayout<x86_64>(mh, 0, fPath, stat_buf.st_ino, stat_buf.st_mtime));
321 throw "unknown file format";
324 catch (const char* msg) {
325 fprintf(stderr, "warning: %s for %s\n", msg, path);
330 ::munmap(p, stat_buf.st_size);
337 template <typename A>
338 MachOLayout<A>::MachOLayout(const void* machHeader, uint64_t offset, const char* path, ino_t inode, time_t modTime)
339 : fPath(path), fOffset(offset), fMTime(modTime), fInode(inode), fHasSplitSegInfo(false)
341 fDylibID.name = NULL;
342 fDylibID.currentVersion = 0;
343 fDylibID.compatibilityVersion = 0;
345 const macho_header<P>* mh = (const macho_header<P>*)machHeader;
346 if ( mh->cputype() != getArchitecture() )
347 throw "wrong architecture";
348 switch ( mh->filetype() ) {
356 throw "file is not a mach-o final linked image";
358 fFlags = mh->flags();
359 fFileType = mh->filetype();
361 const macho_load_command<P>* const cmds = (macho_load_command<P>*)((uint8_t*)mh + sizeof(macho_header<P>));
362 const uint32_t cmd_count = mh->ncmds();
363 const macho_load_command<P>* cmd = cmds;
364 for (uint32_t i = 0; i < cmd_count; ++i) {
365 switch ( cmd->cmd() ) {
368 macho_dylib_command<P>* dylib = (macho_dylib_command<P>*)cmd;
369 fDylibID.name = strdup(dylib->name());
370 fDylibID.currentVersion = dylib->current_version();
371 fDylibID.compatibilityVersion = dylib->compatibility_version();
372 fNameFileOffset = dylib->name() - (char*)machHeader;
376 case LC_LOAD_WEAK_DYLIB:
377 case LC_REEXPORT_DYLIB:
379 macho_dylib_command<P>* dylib = (macho_dylib_command<P>*)cmd;
381 lib.name = strdup(dylib->name());
382 lib.currentVersion = dylib->current_version();
383 lib.compatibilityVersion = dylib->compatibility_version();
384 fLibraries.push_back(lib);
387 case LC_SEGMENT_SPLIT_INFO:
388 fHasSplitSegInfo = true;
390 case macho_segment_command<P>::CMD:
392 macho_segment_command<P>* segCmd = (macho_segment_command<P>*)cmd;
393 fSegments.push_back(Segment(segCmd->vmaddr(), segCmd->vmsize(), segCmd->fileoff(),
394 segCmd->filesize(), segCmd->initprot(), segCmd->segname()));
398 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
402 fLowExecutableSegment = NULL;
403 fLowWritableSegment = NULL;
404 fLowReadOnlySegment = NULL;
405 fVMExecutableSize = 0;
409 const Segment* highSegment = NULL;
410 for(std::vector<Segment>::const_iterator it = fSegments.begin(); it != fSegments.end(); ++it) {
411 const Segment& seg = *it;
412 if ( (fLowSegment == NULL) || (seg.address() < fLowSegment->address()) )
414 if ( (highSegment == NULL) || (seg.address() > highSegment->address()) )
416 if ( seg.executable() ) {
417 if ( (fLowExecutableSegment == NULL) || (seg.address() < fLowExecutableSegment->address()) )
418 fLowExecutableSegment = &seg;
419 fVMExecutableSize += seg.size();
421 else if ( seg.writable()) {
422 if ( (fLowWritableSegment == NULL) || (seg.address() < fLowWritableSegment->address()) )
423 fLowWritableSegment = &seg;
424 fVMWritablSize += seg.size();
427 if ( (fLowReadOnlySegment == NULL) || (seg.address() < fLowReadOnlySegment->address()) )
428 fLowReadOnlySegment = &seg;
429 fVMReadOnlySize += seg.size();
432 if ( (highSegment != NULL) && (fLowSegment != NULL) )
433 fVMSize = (highSegment->address() + highSegment->size() - fLowSegment->address() + 4095) & (-4096);
436 template <> cpu_type_t MachOLayout<ppc>::getArchitecture() const { return CPU_TYPE_POWERPC; }
437 template <> cpu_type_t MachOLayout<ppc64>::getArchitecture() const { return CPU_TYPE_POWERPC64; }
438 template <> cpu_type_t MachOLayout<x86>::getArchitecture() const { return CPU_TYPE_I386; }
439 template <> cpu_type_t MachOLayout<x86_64>::getArchitecture() const { return CPU_TYPE_X86_64; }
442 bool MachOLayout<ppc>::isSplitSeg() const
444 return ( (this->getFlags() & MH_SPLIT_SEGS) != 0 );
448 bool MachOLayout<x86>::isSplitSeg() const
450 return ( (this->getFlags() & MH_SPLIT_SEGS) != 0 );
453 template <typename A>
454 bool MachOLayout<A>::isSplitSeg() const
460 #endif // __MACHO_LAYOUT__