blob: 7b3b36de3581f40e55a4ad304d00ccdba7c6dd18 [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"
Nick Kledzike5552772013-12-19 21:58:00 +000026#include "ReferenceKinds.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000027
28#include "lld/Core/Error.h"
29#include "lld/Core/LLVM.h"
30
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/StringSwitch.h"
34#include "llvm/ADT/Twine.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/FileOutputBuffer.h"
38#include "llvm/Support/Host.h"
39#include "llvm/Support/MachO.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/system_error.h"
43
44#include <functional>
45
46using namespace llvm::MachO;
47
48namespace lld {
49namespace mach_o {
50namespace normalized {
51
52// Utility to call a lambda expression on each load command.
53static error_code
54forEachLoadCommand(StringRef lcRange, unsigned lcCount, bool swap, bool is64,
55 std::function<bool (uint32_t cmd, uint32_t size,
56 const char* lc)> func) {
57 const char* p = lcRange.begin();
58 for (unsigned i=0; i < lcCount; ++i) {
59 const load_command *lc = reinterpret_cast<const load_command*>(p);
60 load_command lcCopy;
61 const load_command *slc = lc;
62 if (swap) {
63 memcpy(&lcCopy, lc, sizeof(load_command));
64 swapStruct(lcCopy);
65 slc = &lcCopy;
66 }
67 if ( (p + slc->cmdsize) > lcRange.end() )
68 return llvm::make_error_code(llvm::errc::executable_format_error);
69
70 if (func(slc->cmd, slc->cmdsize, p))
71 return error_code::success();
72
73 p += slc->cmdsize;
74 }
75
76 return error_code::success();
77}
78
79
80static error_code
81appendRelocations(Relocations &relocs, StringRef buffer, bool swap,
82 bool bigEndian, uint32_t reloff, uint32_t nreloc) {
83 if ((reloff + nreloc*8) > buffer.size())
84 return llvm::make_error_code(llvm::errc::executable_format_error);
85 const any_relocation_info* relocsArray =
Joey Gouly010b3762014-01-14 22:32:38 +000086 reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
Nick Kledzike34182f2013-11-06 21:36:55 +000087
88 for(uint32_t i=0; i < nreloc; ++i) {
89 relocs.push_back(unpackRelocation(relocsArray[i], swap, bigEndian));
90 }
91 return error_code::success();
92}
93
Joey Gouly010b3762014-01-14 22:32:38 +000094template <typename T> static T readBigEndian(T t) {
95 if (llvm::sys::IsLittleEndianHost)
96 return SwapByteOrder(t);
97 return t;
98}
Nick Kledzike34182f2013-11-06 21:36:55 +000099
100/// Reads a mach-o file and produces an in-memory normalized view.
Joey Gouly010b3762014-01-14 22:32:38 +0000101ErrorOr<std::unique_ptr<NormalizedFile>>
102readBinary(std::unique_ptr<MemoryBuffer> &mb,
103 const MachOLinkingContext::Arch arch) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000104 // Make empty NormalizedFile.
105 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
106
Joey Gouly010b3762014-01-14 22:32:38 +0000107 const char *start = mb->getBufferStart();
108 size_t objSize = mb->getBufferSize();
109
Nick Kledzike34182f2013-11-06 21:36:55 +0000110 // Determine endianness and pointer size for mach-o file.
Joey Gouly010b3762014-01-14 22:32:38 +0000111 const mach_header *mh = reinterpret_cast<const mach_header *>(start);
112 bool isFat = mh->magic == llvm::MachO::FAT_CIGAM ||
113 mh->magic == llvm::MachO::FAT_MAGIC;
114 if (isFat) {
115 uint32_t cputype = MachOLinkingContext::cpuTypeFromArch(arch);
116 uint32_t cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(arch);
117 const fat_header *fh = reinterpret_cast<const fat_header *>(start);
118 uint32_t nfat_arch = readBigEndian(fh->nfat_arch);
119 const fat_arch *fa =
120 reinterpret_cast<const fat_arch *>(start + sizeof(fat_header));
121 bool foundArch = false;
122 while (nfat_arch-- > 0) {
123 if (readBigEndian(fa->cputype) == cputype &&
124 readBigEndian(fa->cpusubtype) == cpusubtype) {
125 foundArch = true;
126 break;
127 }
128 fa++;
129 }
130 if (!foundArch) {
131 return llvm::make_error_code(llvm::errc::executable_format_error);
132 }
133 objSize = readBigEndian(fa->size);
134 uint32_t offset = readBigEndian(fa->offset);
135 if ((offset + objSize) > mb->getBufferSize())
136 return llvm::make_error_code(llvm::errc::executable_format_error);
137 start += offset;
138 mh = reinterpret_cast<const mach_header *>(start);
139 }
140
Nick Kledzike34182f2013-11-06 21:36:55 +0000141 bool is64, swap;
142 switch (mh->magic) {
143 case llvm::MachO::MH_MAGIC:
144 is64 = false;
145 swap = false;
146 break;
147 case llvm::MachO::MH_MAGIC_64:
148 is64 = true;
149 swap = false;
150 break;
151 case llvm::MachO::MH_CIGAM:
152 is64 = false;
153 swap = true;
154 break;
155 case llvm::MachO::MH_CIGAM_64:
156 is64 = true;
157 swap = true;
158 break;
159 default:
160 return llvm::make_error_code(llvm::errc::executable_format_error);
161 }
162
163 // Endian swap header, if needed.
164 mach_header headerCopy;
165 const mach_header *smh = mh;
166 if (swap) {
167 memcpy(&headerCopy, mh, sizeof(mach_header));
168 swapStruct(headerCopy);
169 smh = &headerCopy;
170 }
171
172 // Validate head and load commands fit in buffer.
173 const uint32_t lcCount = smh->ncmds;
Joey Gouly010b3762014-01-14 22:32:38 +0000174 const char *lcStart =
175 start + (is64 ? sizeof(mach_header_64) : sizeof(mach_header));
Nick Kledzike34182f2013-11-06 21:36:55 +0000176 StringRef lcRange(lcStart, smh->sizeofcmds);
Joey Gouly010b3762014-01-14 22:32:38 +0000177 if (lcRange.end() > (start + objSize))
Nick Kledzike34182f2013-11-06 21:36:55 +0000178 return llvm::make_error_code(llvm::errc::executable_format_error);
179
180 // Normalize architecture
181 f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
182 bool isBigEndianArch = MachOLinkingContext::isBigEndian(f->arch);
183 // Copy file type and flags
184 f->fileType = HeaderFileType(smh->filetype);
185 f->flags = smh->flags;
186
187
188 // Walk load commands looking for segments/sections and the symbol table.
189 error_code ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
190 [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
191 if (is64) {
192 if (cmd == LC_SEGMENT_64) {
193 const segment_command_64 *seg =
194 reinterpret_cast<const segment_command_64*>(lc);
195 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
196 : seg->nsects);
197 const section_64 *sects = reinterpret_cast<const section_64*>
198 (lc + sizeof(segment_command_64));
199 const unsigned lcSize = sizeof(segment_command_64)
200 + sectionCount*sizeof(section_64);
201 // Verify sections don't extend beyond end of segment load command.
202 if (lcSize > size)
203 return llvm::make_error_code(llvm::errc::executable_format_error);
204 for (unsigned i=0; i < sectionCount; ++i) {
205 const section_64 *sect = &sects[i];
206 Section section;
207 section.segmentName = getString16(sect->segname);
208 section.sectionName = getString16(sect->sectname);
209 section.type = (SectionType)(read32(swap, sect->flags)
210 & SECTION_TYPE);
211 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
212 section.alignment = read32(swap, sect->align);
213 section.address = read64(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000214 const uint8_t *content =
215 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000216 size_t contentSize = read64(swap, sect->size);
217 // Note: this assign() is copying the content bytes. Ideally,
218 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000219 section.content = llvm::makeArrayRef(content, contentSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000220 appendRelocations(section.relocations, mb->getBuffer(),
221 swap, isBigEndianArch, read32(swap, sect->reloff),
222 read32(swap, sect->nreloc));
223 f->sections.push_back(section);
224 }
225 }
226 } else {
227 if (cmd == LC_SEGMENT) {
228 const segment_command *seg =
229 reinterpret_cast<const segment_command*>(lc);
230 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
231 : seg->nsects);
232 const section *sects = reinterpret_cast<const section*>
233 (lc + sizeof(segment_command));
234 const unsigned lcSize = sizeof(segment_command)
235 + sectionCount*sizeof(section);
236 // Verify sections don't extend beyond end of segment load command.
237 if (lcSize > size)
238 return llvm::make_error_code(llvm::errc::executable_format_error);
239 for (unsigned i=0; i < sectionCount; ++i) {
240 const section *sect = &sects[i];
241 Section section;
242 section.segmentName = getString16(sect->segname);
243 section.sectionName = getString16(sect->sectname);
244 section.type = (SectionType)(read32(swap, sect->flags)
245 & SECTION_TYPE);
246 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
247 section.alignment = read32(swap, sect->align);
248 section.address = read32(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000249 const uint8_t *content =
250 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000251 size_t contentSize = read32(swap, sect->size);
252 // Note: this assign() is copying the content bytes. Ideally,
253 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000254 section.content = llvm::makeArrayRef(content, contentSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000255 appendRelocations(section.relocations, mb->getBuffer(),
256 swap, isBigEndianArch, read32(swap, sect->reloff),
257 read32(swap, sect->nreloc));
258 f->sections.push_back(section);
259 }
260 }
261 }
262 if (cmd == LC_SYMTAB) {
263 const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
Joey Gouly010b3762014-01-14 22:32:38 +0000264 const char *strings = start + read32(swap, st->stroff);
Nick Kledzike34182f2013-11-06 21:36:55 +0000265 const uint32_t strSize = read32(swap, st->strsize);
266 // Validate string pool and symbol table all in buffer.
267 if ( read32(swap, st->stroff)+read32(swap, st->strsize)
Joey Gouly010b3762014-01-14 22:32:38 +0000268 > objSize )
Nick Kledzike34182f2013-11-06 21:36:55 +0000269 return llvm::make_error_code(llvm::errc::executable_format_error);
270 if (is64) {
271 const uint32_t symOffset = read32(swap, st->symoff);
272 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000273 if ( symOffset+(symCount*sizeof(nlist_64)) > objSize)
Nick Kledzike34182f2013-11-06 21:36:55 +0000274 return llvm::make_error_code(llvm::errc::executable_format_error);
Joey Gouly010b3762014-01-14 22:32:38 +0000275 const nlist_64 *symbols =
276 reinterpret_cast<const nlist_64 *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000277 // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
278 for(uint32_t i=0; i < symCount; ++i) {
279 const nlist_64 *sin = &symbols[i];
280 nlist_64 tempSym;
281 if (swap) {
282 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
283 }
284 Symbol sout;
285 if (sin->n_strx > strSize)
286 return llvm::make_error_code(llvm::errc::executable_format_error);
287 sout.name = &strings[sin->n_strx];
288 sout.type = (NListType)(sin->n_type & N_TYPE);
289 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
290 sout.sect = sin->n_sect;
291 sout.desc = sin->n_desc;
292 sout.value = sin->n_value;
293 if (sout.type == N_UNDF)
294 f->undefinedSymbols.push_back(sout);
295 else if (sout.scope == (SymbolScope)N_EXT)
296 f->globalSymbols.push_back(sout);
297 else
298 f->localSymbols.push_back(sout);
299 }
300 } else {
301 const uint32_t symOffset = read32(swap, st->symoff);
302 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000303 if ( symOffset+(symCount*sizeof(nlist)) > objSize)
Nick Kledzike34182f2013-11-06 21:36:55 +0000304 return llvm::make_error_code(llvm::errc::executable_format_error);
Joey Gouly010b3762014-01-14 22:32:38 +0000305 const nlist *symbols =
306 reinterpret_cast<const nlist *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000307 // Convert each nlist to a lld::mach_o::normalized::Symbol.
308 for(uint32_t i=0; i < symCount; ++i) {
309 const nlist *sin = &symbols[i];
310 nlist tempSym;
311 if (swap) {
312 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
313 }
314 Symbol sout;
315 if (sin->n_strx > strSize)
316 return llvm::make_error_code(llvm::errc::executable_format_error);
317 sout.name = &strings[sin->n_strx];
318 sout.type = (NListType)(sin->n_type & N_TYPE);
319 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
320 sout.sect = sin->n_sect;
321 sout.desc = sin->n_desc;
322 sout.value = sin->n_value;
323 if (sout.type == N_UNDF)
324 f->undefinedSymbols.push_back(sout);
325 else if (sout.scope == (SymbolScope)N_EXT)
326 f->globalSymbols.push_back(sout);
327 else
328 f->localSymbols.push_back(sout);
329 }
330 }
331 } else if (cmd == LC_DYSYMTAB) {
332 // TODO: indirect symbols
333 }
334
335 return false;
336 });
337 if (ec)
338 return ec;
339
340 return std::move(f);
341}
342
343
344} // namespace normalized
345} // namespace mach_o
Nick Kledzike5552772013-12-19 21:58:00 +0000346
347void Registry::addSupportMachOObjects(StringRef archName) {
348 MachOLinkingContext::Arch arch = MachOLinkingContext::archFromName(archName);
349 switch (arch) {
350 case MachOLinkingContext::arch_x86_64:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000351 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::x86_64,
Nick Kledzike5552772013-12-19 21:58:00 +0000352 mach_o::KindHandler_x86_64::kindStrings);
353 break;
354 case MachOLinkingContext::arch_x86:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000355 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::x86,
Nick Kledzike5552772013-12-19 21:58:00 +0000356 mach_o::KindHandler_x86::kindStrings);
357 break;
358 case MachOLinkingContext::arch_armv6:
359 case MachOLinkingContext::arch_armv7:
360 case MachOLinkingContext::arch_armv7s:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000361 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::ARM,
Nick Kledzike5552772013-12-19 21:58:00 +0000362 mach_o::KindHandler_arm::kindStrings);
363 break;
364 default:
365 llvm_unreachable("mach-o arch not supported");
366 }
Nick Kledzik6edd7222014-01-11 01:07:43 +0000367 add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
368 new mach_o::MachOYamlIOTaggedDocumentHandler()));
Nick Kledzike5552772013-12-19 21:58:00 +0000369}
370
Nick Kledzike34182f2013-11-06 21:36:55 +0000371} // namespace lld
372