]> git.saurik.com Git - apple/dyld.git/blob - launch-cache/MachOLayout.hpp
dyld-95.3.tar.gz
[apple/dyld.git] / launch-cache / MachOLayout.hpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #ifndef __MACHO_LAYOUT__
26 #define __MACHO_LAYOUT__
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/mman.h>
31 #include <mach/mach.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <mach-o/loader.h>
39 #include <mach-o/fat.h>
40
41 #include <vector>
42 #include <set>
43
44 #include "MachOFileAbstraction.hpp"
45 #include "Architectures.hpp"
46
47
48 void throwf(const char* format, ...) __attribute__((format(printf, 1, 2)));
49
50 __attribute__((noreturn))
51 void throwf(const char* format, ...)
52 {
53 va_list list;
54 char* p;
55 va_start(list, format);
56 vasprintf(&p, format, list);
57 va_end(list);
58
59 const char* t = p;
60 throw t;
61 }
62
63
64 class MachOLayoutAbstraction
65 {
66 public:
67 struct Segment
68 {
69 public:
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);
75 }
76
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; }
94 private:
95 uint64_t fAddress;
96 uint64_t fSize;
97 uint64_t fFileOffset;
98 uint64_t fFileSize;
99 uint64_t fNewAddress;
100 void* fMappedAddress;
101 uint32_t fPermissions;
102 char fName[16];
103 };
104
105 struct Library
106 {
107 const char* name;
108 uint32_t currentVersion;
109 uint32_t compatibilityVersion;
110 };
111
112
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;
135 };
136
137
138
139
140 template <typename A>
141 class MachOLayout : public MachOLayoutAbstraction
142 {
143 public:
144 MachOLayout(const void* machHeader, uint64_t offset, const char* path, ino_t inode, time_t modTime);
145 virtual ~MachOLayout() {}
146
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; }
169
170 private:
171 typedef typename A::P P;
172 typedef typename A::P::E E;
173 typedef typename A::P::uint_t pint_t;
174
175 const char* fPath;
176 uint64_t fOffset;
177 uint32_t fFileType;
178 uint32_t fFlags;
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;
185 Library fDylibID;
186 uint32_t fNameFileOffset;
187 time_t fMTime;
188 ino_t fInode;
189 uint64_t fVMSize;
190 uint64_t fVMExecutableSize;
191 uint64_t fVMWritablSize;
192 uint64_t fVMReadOnlySize;
193 bool fHasSplitSegInfo;
194 };
195
196
197
198 class UniversalMachOLayout
199 {
200 public:
201 UniversalMachOLayout(const char* path, const std::set<cpu_type_t>* onlyArchs=NULL);
202 ~UniversalMachOLayout() {}
203
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; }
207
208 private:
209 struct CStringEquals {
210 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
211 };
212 typedef __gnu_cxx::hash_map<const char*, const UniversalMachOLayout*, __gnu_cxx::hash<const char*>, CStringEquals> PathToNode;
213
214 static PathToNode fgLayoutCache;
215 const char* fPath;
216 std::vector<MachOLayoutAbstraction*> fLayouts;
217 };
218
219 UniversalMachOLayout::PathToNode UniversalMachOLayout::fgLayoutCache;
220
221
222 const MachOLayoutAbstraction* UniversalMachOLayout::getArch(cpu_type_t arch) const
223 {
224 for(std::vector<MachOLayoutAbstraction*>::const_iterator it=fLayouts.begin(); it != fLayouts.end(); ++it) {
225 const MachOLayoutAbstraction* layout = *it;
226 if ( layout->getArchitecture() == arch )
227 return layout;
228 }
229 return NULL;
230 }
231
232
233 const UniversalMachOLayout* UniversalMachOLayout::find(const char* path, const std::set<cpu_type_t>* onlyArchs)
234 {
235 // look in cache
236 PathToNode::iterator pos = fgLayoutCache.find(path);
237 if ( pos != fgLayoutCache.end() )
238 return pos->second;
239
240 // create UniversalMachOLayout
241 const UniversalMachOLayout* result = new UniversalMachOLayout(path, onlyArchs);
242
243 // add it to cache
244 fgLayoutCache[result->fPath] = result;
245
246 return result;
247 }
248
249
250 UniversalMachOLayout::UniversalMachOLayout(const char* path, const std::set<cpu_type_t>* onlyArchs)
251 : fPath(strdup(path))
252 {
253 // map in whole file
254 int fd = ::open(path, O_RDONLY, 0);
255 if ( fd == -1 )
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);
265 ::close(fd);
266
267 try {
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);
277 try {
278 if ( (onlyArchs == NULL) || (onlyArchs->count(curArch) != 0) ) {
279 switch ( curArch ) {
280 case CPU_TYPE_POWERPC:
281 fLayouts.push_back(new MachOLayout<ppc>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
282 break;
283 case CPU_TYPE_POWERPC64:
284 fLayouts.push_back(new MachOLayout<ppc64>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
285 break;
286 case CPU_TYPE_I386:
287 fLayouts.push_back(new MachOLayout<x86>(&p[fileOffset], fileOffset, fPath, stat_buf.st_ino, stat_buf.st_mtime));
288 break;
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));
291 break;
292 default:
293 throw "unknown file format";
294 }
295 }
296 }
297 catch (const char* msg) {
298 fprintf(stderr, "warning: %s for %s\n", msg, path);
299 }
300 }
301 }
302 else {
303 try {
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));
307 }
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));
311 }
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));
315 }
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));
319 }
320 else {
321 throw "unknown file format";
322 }
323 }
324 catch (const char* msg) {
325 fprintf(stderr, "warning: %s for %s\n", msg, path);
326 }
327 }
328 }
329 catch (...) {
330 ::munmap(p, stat_buf.st_size);
331 throw;
332 }
333 }
334
335
336
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)
340 {
341 fDylibID.name = NULL;
342 fDylibID.currentVersion = 0;
343 fDylibID.compatibilityVersion = 0;
344
345 const macho_header<P>* mh = (const macho_header<P>*)machHeader;
346 if ( mh->cputype() != getArchitecture() )
347 throw "wrong architecture";
348 switch ( mh->filetype() ) {
349 case MH_DYLIB:
350 case MH_BUNDLE:
351 case MH_EXECUTE:
352 case MH_DYLIB_STUB:
353 case MH_DYLINKER:
354 break;
355 default:
356 throw "file is not a mach-o final linked image";
357 }
358 fFlags = mh->flags();
359 fFileType = mh->filetype();
360
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() ) {
366 case LC_ID_DYLIB:
367 {
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;
373 }
374 break;
375 case LC_LOAD_DYLIB:
376 case LC_LOAD_WEAK_DYLIB:
377 case LC_REEXPORT_DYLIB:
378 {
379 macho_dylib_command<P>* dylib = (macho_dylib_command<P>*)cmd;
380 Library lib;
381 lib.name = strdup(dylib->name());
382 lib.currentVersion = dylib->current_version();
383 lib.compatibilityVersion = dylib->compatibility_version();
384 fLibraries.push_back(lib);
385 }
386 break;
387 case LC_SEGMENT_SPLIT_INFO:
388 fHasSplitSegInfo = true;
389 break;
390 case macho_segment_command<P>::CMD:
391 {
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()));
395 }
396 break;
397 }
398 cmd = (const macho_load_command<P>*)(((uint8_t*)cmd)+cmd->cmdsize());
399 }
400
401 fLowSegment = NULL;
402 fLowExecutableSegment = NULL;
403 fLowWritableSegment = NULL;
404 fLowReadOnlySegment = NULL;
405 fVMExecutableSize = 0;
406 fVMWritablSize = 0;
407 fVMReadOnlySize = 0;
408 fVMSize = 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()) )
413 fLowSegment = &seg;
414 if ( (highSegment == NULL) || (seg.address() > highSegment->address()) )
415 highSegment = &seg;
416 if ( seg.executable() ) {
417 if ( (fLowExecutableSegment == NULL) || (seg.address() < fLowExecutableSegment->address()) )
418 fLowExecutableSegment = &seg;
419 fVMExecutableSize += seg.size();
420 }
421 else if ( seg.writable()) {
422 if ( (fLowWritableSegment == NULL) || (seg.address() < fLowWritableSegment->address()) )
423 fLowWritableSegment = &seg;
424 fVMWritablSize += seg.size();
425 }
426 else {
427 if ( (fLowReadOnlySegment == NULL) || (seg.address() < fLowReadOnlySegment->address()) )
428 fLowReadOnlySegment = &seg;
429 fVMReadOnlySize += seg.size();
430 }
431 }
432 if ( (highSegment != NULL) && (fLowSegment != NULL) )
433 fVMSize = (highSegment->address() + highSegment->size() - fLowSegment->address() + 4095) & (-4096);
434 }
435
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; }
440
441 template <>
442 bool MachOLayout<ppc>::isSplitSeg() const
443 {
444 return ( (this->getFlags() & MH_SPLIT_SEGS) != 0 );
445 }
446
447 template <>
448 bool MachOLayout<x86>::isSplitSeg() const
449 {
450 return ( (this->getFlags() & MH_SPLIT_SEGS) != 0 );
451 }
452
453 template <typename A>
454 bool MachOLayout<A>::isSplitSeg() const
455 {
456 return false;
457 }
458
459
460 #endif // __MACHO_LAYOUT__
461
462
463