blob: 91e3aa71611838413bc625aacf283d08e0173c9c [file] [log] [blame]
Nick Kledzike34182f2013-11-06 21:36:55 +00001//===- lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp ---------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10///
11/// \file For mach-o object files, this implementation converts from
12/// mach-o on-disk binary format to in-memory normalized mach-o.
13///
14/// +---------------+
15/// | binary mach-o |
16/// +---------------+
17/// |
18/// |
19/// v
20/// +------------+
21/// | normalized |
22/// +------------+
23
24#include "MachONormalizedFile.h"
25#include "MachONormalizedFileBinaryUtils.h"
26
27#include "lld/Core/Error.h"
28#include "lld/Core/LLVM.h"
29
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/StringSwitch.h"
33#include "llvm/ADT/Twine.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/FileOutputBuffer.h"
37#include "llvm/Support/Host.h"
38#include "llvm/Support/MachO.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Support/system_error.h"
42
43#include <functional>
44
45using namespace llvm::MachO;
46
47namespace lld {
48namespace mach_o {
49namespace normalized {
50
51// Utility to call a lambda expression on each load command.
52static error_code
53forEachLoadCommand(StringRef lcRange, unsigned lcCount, bool swap, bool is64,
54 std::function<bool (uint32_t cmd, uint32_t size,
55 const char* lc)> func) {
56 const char* p = lcRange.begin();
57 for (unsigned i=0; i < lcCount; ++i) {
58 const load_command *lc = reinterpret_cast<const load_command*>(p);
59 load_command lcCopy;
60 const load_command *slc = lc;
61 if (swap) {
62 memcpy(&lcCopy, lc, sizeof(load_command));
63 swapStruct(lcCopy);
64 slc = &lcCopy;
65 }
66 if ( (p + slc->cmdsize) > lcRange.end() )
67 return llvm::make_error_code(llvm::errc::executable_format_error);
68
69 if (func(slc->cmd, slc->cmdsize, p))
70 return error_code::success();
71
72 p += slc->cmdsize;
73 }
74
75 return error_code::success();
76}
77
78
79static error_code
80appendRelocations(Relocations &relocs, StringRef buffer, bool swap,
81 bool bigEndian, uint32_t reloff, uint32_t nreloc) {
82 if ((reloff + nreloc*8) > buffer.size())
83 return llvm::make_error_code(llvm::errc::executable_format_error);
84 const any_relocation_info* relocsArray =
85 reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
86
87 for(uint32_t i=0; i < nreloc; ++i) {
88 relocs.push_back(unpackRelocation(relocsArray[i], swap, bigEndian));
89 }
90 return error_code::success();
91}
92
93
94
95/// Reads a mach-o file and produces an in-memory normalized view.
96ErrorOr<std::unique_ptr<NormalizedFile>>
97readBinary(std::unique_ptr<MemoryBuffer> &mb) {
98 // Make empty NormalizedFile.
99 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
100
101 // Determine endianness and pointer size for mach-o file.
102 const mach_header *mh = reinterpret_cast<const mach_header*>
103 (mb->getBufferStart());
104 bool is64, swap;
105 switch (mh->magic) {
106 case llvm::MachO::MH_MAGIC:
107 is64 = false;
108 swap = false;
109 break;
110 case llvm::MachO::MH_MAGIC_64:
111 is64 = true;
112 swap = false;
113 break;
114 case llvm::MachO::MH_CIGAM:
115 is64 = false;
116 swap = true;
117 break;
118 case llvm::MachO::MH_CIGAM_64:
119 is64 = true;
120 swap = true;
121 break;
122 default:
123 return llvm::make_error_code(llvm::errc::executable_format_error);
124 }
125
126 // Endian swap header, if needed.
127 mach_header headerCopy;
128 const mach_header *smh = mh;
129 if (swap) {
130 memcpy(&headerCopy, mh, sizeof(mach_header));
131 swapStruct(headerCopy);
132 smh = &headerCopy;
133 }
134
135 // Validate head and load commands fit in buffer.
136 const uint32_t lcCount = smh->ncmds;
137 const char* lcStart = mb->getBufferStart() + (is64 ? sizeof(mach_header_64)
138 : sizeof(mach_header));
139 StringRef lcRange(lcStart, smh->sizeofcmds);
140 if (lcRange.end() > mb->getBufferEnd())
141 return llvm::make_error_code(llvm::errc::executable_format_error);
142
143 // Normalize architecture
144 f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
145 bool isBigEndianArch = MachOLinkingContext::isBigEndian(f->arch);
146 // Copy file type and flags
147 f->fileType = HeaderFileType(smh->filetype);
148 f->flags = smh->flags;
149
150
151 // Walk load commands looking for segments/sections and the symbol table.
152 error_code ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
153 [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
154 if (is64) {
155 if (cmd == LC_SEGMENT_64) {
156 const segment_command_64 *seg =
157 reinterpret_cast<const segment_command_64*>(lc);
158 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
159 : seg->nsects);
160 const section_64 *sects = reinterpret_cast<const section_64*>
161 (lc + sizeof(segment_command_64));
162 const unsigned lcSize = sizeof(segment_command_64)
163 + sectionCount*sizeof(section_64);
164 // Verify sections don't extend beyond end of segment load command.
165 if (lcSize > size)
166 return llvm::make_error_code(llvm::errc::executable_format_error);
167 for (unsigned i=0; i < sectionCount; ++i) {
168 const section_64 *sect = &sects[i];
169 Section section;
170 section.segmentName = getString16(sect->segname);
171 section.sectionName = getString16(sect->sectname);
172 section.type = (SectionType)(read32(swap, sect->flags)
173 & SECTION_TYPE);
174 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
175 section.alignment = read32(swap, sect->align);
176 section.address = read64(swap, sect->addr);
177 const char *content = mb->getBufferStart()
178 + read32(swap, sect->offset);
179 size_t contentSize = read64(swap, sect->size);
180 // Note: this assign() is copying the content bytes. Ideally,
181 // we can use a custom allocator for vector to avoid the copy.
182 section.content.assign(content, content+contentSize);
183 appendRelocations(section.relocations, mb->getBuffer(),
184 swap, isBigEndianArch, read32(swap, sect->reloff),
185 read32(swap, sect->nreloc));
186 f->sections.push_back(section);
187 }
188 }
189 } else {
190 if (cmd == LC_SEGMENT) {
191 const segment_command *seg =
192 reinterpret_cast<const segment_command*>(lc);
193 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
194 : seg->nsects);
195 const section *sects = reinterpret_cast<const section*>
196 (lc + sizeof(segment_command));
197 const unsigned lcSize = sizeof(segment_command)
198 + sectionCount*sizeof(section);
199 // Verify sections don't extend beyond end of segment load command.
200 if (lcSize > size)
201 return llvm::make_error_code(llvm::errc::executable_format_error);
202 for (unsigned i=0; i < sectionCount; ++i) {
203 const section *sect = &sects[i];
204 Section section;
205 section.segmentName = getString16(sect->segname);
206 section.sectionName = getString16(sect->sectname);
207 section.type = (SectionType)(read32(swap, sect->flags)
208 & SECTION_TYPE);
209 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
210 section.alignment = read32(swap, sect->align);
211 section.address = read32(swap, sect->addr);
212 const char *content = mb->getBufferStart()
213 + read32(swap, sect->offset);
214 size_t contentSize = read32(swap, sect->size);
215 // Note: this assign() is copying the content bytes. Ideally,
216 // we can use a custom allocator for vector to avoid the copy.
217 section.content.assign(content, content+contentSize);
218 appendRelocations(section.relocations, mb->getBuffer(),
219 swap, isBigEndianArch, read32(swap, sect->reloff),
220 read32(swap, sect->nreloc));
221 f->sections.push_back(section);
222 }
223 }
224 }
225 if (cmd == LC_SYMTAB) {
226 const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
227 const char* strings = mb->getBufferStart() + read32(swap, st->stroff);
228 const uint32_t strSize = read32(swap, st->strsize);
229 // Validate string pool and symbol table all in buffer.
230 if ( read32(swap, st->stroff)+read32(swap, st->strsize)
231 > mb->getBufferSize() )
232 return llvm::make_error_code(llvm::errc::executable_format_error);
233 if (is64) {
234 const uint32_t symOffset = read32(swap, st->symoff);
235 const uint32_t symCount = read32(swap, st->nsyms);
236 if ( symOffset+(symCount*sizeof(nlist_64)) > mb->getBufferSize())
237 return llvm::make_error_code(llvm::errc::executable_format_error);
238 const nlist_64* symbols = reinterpret_cast<const nlist_64*>
239 (mb->getBufferStart() + symOffset);
240 // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
241 for(uint32_t i=0; i < symCount; ++i) {
242 const nlist_64 *sin = &symbols[i];
243 nlist_64 tempSym;
244 if (swap) {
245 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
246 }
247 Symbol sout;
248 if (sin->n_strx > strSize)
249 return llvm::make_error_code(llvm::errc::executable_format_error);
250 sout.name = &strings[sin->n_strx];
251 sout.type = (NListType)(sin->n_type & N_TYPE);
252 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
253 sout.sect = sin->n_sect;
254 sout.desc = sin->n_desc;
255 sout.value = sin->n_value;
256 if (sout.type == N_UNDF)
257 f->undefinedSymbols.push_back(sout);
258 else if (sout.scope == (SymbolScope)N_EXT)
259 f->globalSymbols.push_back(sout);
260 else
261 f->localSymbols.push_back(sout);
262 }
263 } else {
264 const uint32_t symOffset = read32(swap, st->symoff);
265 const uint32_t symCount = read32(swap, st->nsyms);
266 if ( symOffset+(symCount*sizeof(nlist)) > mb->getBufferSize())
267 return llvm::make_error_code(llvm::errc::executable_format_error);
268 const nlist* symbols = reinterpret_cast<const nlist*>
269 (mb->getBufferStart() + symOffset);
270 // Convert each nlist to a lld::mach_o::normalized::Symbol.
271 for(uint32_t i=0; i < symCount; ++i) {
272 const nlist *sin = &symbols[i];
273 nlist tempSym;
274 if (swap) {
275 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
276 }
277 Symbol sout;
278 if (sin->n_strx > strSize)
279 return llvm::make_error_code(llvm::errc::executable_format_error);
280 sout.name = &strings[sin->n_strx];
281 sout.type = (NListType)(sin->n_type & N_TYPE);
282 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
283 sout.sect = sin->n_sect;
284 sout.desc = sin->n_desc;
285 sout.value = sin->n_value;
286 if (sout.type == N_UNDF)
287 f->undefinedSymbols.push_back(sout);
288 else if (sout.scope == (SymbolScope)N_EXT)
289 f->globalSymbols.push_back(sout);
290 else
291 f->localSymbols.push_back(sout);
292 }
293 }
294 } else if (cmd == LC_DYSYMTAB) {
295 // TODO: indirect symbols
296 }
297
298 return false;
299 });
300 if (ec)
301 return ec;
302
303 return std::move(f);
304}
305
306
307} // namespace normalized
308} // namespace mach_o
309} // namespace lld
310