blob: 5fb280242838c472e97cc2d9657485c5a5027445 [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 =
86 reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
87
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
94
95
96/// Reads a mach-o file and produces an in-memory normalized view.
97ErrorOr<std::unique_ptr<NormalizedFile>>
98readBinary(std::unique_ptr<MemoryBuffer> &mb) {
99 // Make empty NormalizedFile.
100 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
101
102 // Determine endianness and pointer size for mach-o file.
103 const mach_header *mh = reinterpret_cast<const mach_header*>
104 (mb->getBufferStart());
105 bool is64, swap;
106 switch (mh->magic) {
107 case llvm::MachO::MH_MAGIC:
108 is64 = false;
109 swap = false;
110 break;
111 case llvm::MachO::MH_MAGIC_64:
112 is64 = true;
113 swap = false;
114 break;
115 case llvm::MachO::MH_CIGAM:
116 is64 = false;
117 swap = true;
118 break;
119 case llvm::MachO::MH_CIGAM_64:
120 is64 = true;
121 swap = true;
122 break;
123 default:
124 return llvm::make_error_code(llvm::errc::executable_format_error);
125 }
126
127 // Endian swap header, if needed.
128 mach_header headerCopy;
129 const mach_header *smh = mh;
130 if (swap) {
131 memcpy(&headerCopy, mh, sizeof(mach_header));
132 swapStruct(headerCopy);
133 smh = &headerCopy;
134 }
135
136 // Validate head and load commands fit in buffer.
137 const uint32_t lcCount = smh->ncmds;
138 const char* lcStart = mb->getBufferStart() + (is64 ? sizeof(mach_header_64)
139 : sizeof(mach_header));
140 StringRef lcRange(lcStart, smh->sizeofcmds);
141 if (lcRange.end() > mb->getBufferEnd())
142 return llvm::make_error_code(llvm::errc::executable_format_error);
143
144 // Normalize architecture
145 f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
146 bool isBigEndianArch = MachOLinkingContext::isBigEndian(f->arch);
147 // Copy file type and flags
148 f->fileType = HeaderFileType(smh->filetype);
149 f->flags = smh->flags;
150
151
152 // Walk load commands looking for segments/sections and the symbol table.
153 error_code ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
154 [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
155 if (is64) {
156 if (cmd == LC_SEGMENT_64) {
157 const segment_command_64 *seg =
158 reinterpret_cast<const segment_command_64*>(lc);
159 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
160 : seg->nsects);
161 const section_64 *sects = reinterpret_cast<const section_64*>
162 (lc + sizeof(segment_command_64));
163 const unsigned lcSize = sizeof(segment_command_64)
164 + sectionCount*sizeof(section_64);
165 // Verify sections don't extend beyond end of segment load command.
166 if (lcSize > size)
167 return llvm::make_error_code(llvm::errc::executable_format_error);
168 for (unsigned i=0; i < sectionCount; ++i) {
169 const section_64 *sect = &sects[i];
170 Section section;
171 section.segmentName = getString16(sect->segname);
172 section.sectionName = getString16(sect->sectname);
173 section.type = (SectionType)(read32(swap, sect->flags)
174 & SECTION_TYPE);
175 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
176 section.alignment = read32(swap, sect->align);
177 section.address = read64(swap, sect->addr);
178 const char *content = mb->getBufferStart()
179 + read32(swap, sect->offset);
180 size_t contentSize = read64(swap, sect->size);
181 // Note: this assign() is copying the content bytes. Ideally,
182 // we can use a custom allocator for vector to avoid the copy.
183 section.content.assign(content, content+contentSize);
184 appendRelocations(section.relocations, mb->getBuffer(),
185 swap, isBigEndianArch, read32(swap, sect->reloff),
186 read32(swap, sect->nreloc));
187 f->sections.push_back(section);
188 }
189 }
190 } else {
191 if (cmd == LC_SEGMENT) {
192 const segment_command *seg =
193 reinterpret_cast<const segment_command*>(lc);
194 const unsigned sectionCount = (swap ? SwapByteOrder(seg->nsects)
195 : seg->nsects);
196 const section *sects = reinterpret_cast<const section*>
197 (lc + sizeof(segment_command));
198 const unsigned lcSize = sizeof(segment_command)
199 + sectionCount*sizeof(section);
200 // Verify sections don't extend beyond end of segment load command.
201 if (lcSize > size)
202 return llvm::make_error_code(llvm::errc::executable_format_error);
203 for (unsigned i=0; i < sectionCount; ++i) {
204 const section *sect = &sects[i];
205 Section section;
206 section.segmentName = getString16(sect->segname);
207 section.sectionName = getString16(sect->sectname);
208 section.type = (SectionType)(read32(swap, sect->flags)
209 & SECTION_TYPE);
210 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
211 section.alignment = read32(swap, sect->align);
212 section.address = read32(swap, sect->addr);
213 const char *content = mb->getBufferStart()
214 + read32(swap, sect->offset);
215 size_t contentSize = read32(swap, sect->size);
216 // Note: this assign() is copying the content bytes. Ideally,
217 // we can use a custom allocator for vector to avoid the copy.
218 section.content.assign(content, content+contentSize);
219 appendRelocations(section.relocations, mb->getBuffer(),
220 swap, isBigEndianArch, read32(swap, sect->reloff),
221 read32(swap, sect->nreloc));
222 f->sections.push_back(section);
223 }
224 }
225 }
226 if (cmd == LC_SYMTAB) {
227 const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
228 const char* strings = mb->getBufferStart() + read32(swap, st->stroff);
229 const uint32_t strSize = read32(swap, st->strsize);
230 // Validate string pool and symbol table all in buffer.
231 if ( read32(swap, st->stroff)+read32(swap, st->strsize)
232 > mb->getBufferSize() )
233 return llvm::make_error_code(llvm::errc::executable_format_error);
234 if (is64) {
235 const uint32_t symOffset = read32(swap, st->symoff);
236 const uint32_t symCount = read32(swap, st->nsyms);
237 if ( symOffset+(symCount*sizeof(nlist_64)) > mb->getBufferSize())
238 return llvm::make_error_code(llvm::errc::executable_format_error);
239 const nlist_64* symbols = reinterpret_cast<const nlist_64*>
240 (mb->getBufferStart() + symOffset);
241 // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
242 for(uint32_t i=0; i < symCount; ++i) {
243 const nlist_64 *sin = &symbols[i];
244 nlist_64 tempSym;
245 if (swap) {
246 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
247 }
248 Symbol sout;
249 if (sin->n_strx > strSize)
250 return llvm::make_error_code(llvm::errc::executable_format_error);
251 sout.name = &strings[sin->n_strx];
252 sout.type = (NListType)(sin->n_type & N_TYPE);
253 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
254 sout.sect = sin->n_sect;
255 sout.desc = sin->n_desc;
256 sout.value = sin->n_value;
257 if (sout.type == N_UNDF)
258 f->undefinedSymbols.push_back(sout);
259 else if (sout.scope == (SymbolScope)N_EXT)
260 f->globalSymbols.push_back(sout);
261 else
262 f->localSymbols.push_back(sout);
263 }
264 } else {
265 const uint32_t symOffset = read32(swap, st->symoff);
266 const uint32_t symCount = read32(swap, st->nsyms);
267 if ( symOffset+(symCount*sizeof(nlist)) > mb->getBufferSize())
268 return llvm::make_error_code(llvm::errc::executable_format_error);
269 const nlist* symbols = reinterpret_cast<const nlist*>
270 (mb->getBufferStart() + symOffset);
271 // Convert each nlist to a lld::mach_o::normalized::Symbol.
272 for(uint32_t i=0; i < symCount; ++i) {
273 const nlist *sin = &symbols[i];
274 nlist tempSym;
275 if (swap) {
276 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
277 }
278 Symbol sout;
279 if (sin->n_strx > strSize)
280 return llvm::make_error_code(llvm::errc::executable_format_error);
281 sout.name = &strings[sin->n_strx];
282 sout.type = (NListType)(sin->n_type & N_TYPE);
283 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
284 sout.sect = sin->n_sect;
285 sout.desc = sin->n_desc;
286 sout.value = sin->n_value;
287 if (sout.type == N_UNDF)
288 f->undefinedSymbols.push_back(sout);
289 else if (sout.scope == (SymbolScope)N_EXT)
290 f->globalSymbols.push_back(sout);
291 else
292 f->localSymbols.push_back(sout);
293 }
294 }
295 } else if (cmd == LC_DYSYMTAB) {
296 // TODO: indirect symbols
297 }
298
299 return false;
300 });
301 if (ec)
302 return ec;
303
304 return std::move(f);
305}
306
307
308} // namespace normalized
309} // namespace mach_o
Nick Kledzike5552772013-12-19 21:58:00 +0000310
311void Registry::addSupportMachOObjects(StringRef archName) {
312 MachOLinkingContext::Arch arch = MachOLinkingContext::archFromName(archName);
313 switch (arch) {
314 case MachOLinkingContext::arch_x86_64:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000315 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::x86_64,
Nick Kledzike5552772013-12-19 21:58:00 +0000316 mach_o::KindHandler_x86_64::kindStrings);
317 break;
318 case MachOLinkingContext::arch_x86:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000319 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::x86,
Nick Kledzike5552772013-12-19 21:58:00 +0000320 mach_o::KindHandler_x86::kindStrings);
321 break;
322 case MachOLinkingContext::arch_armv6:
323 case MachOLinkingContext::arch_armv7:
324 case MachOLinkingContext::arch_armv7s:
Rui Ueyama170a1a82013-12-20 07:48:29 +0000325 addKindTable(Reference::KindNamespace::mach_o, Reference::KindArch::ARM,
Nick Kledzike5552772013-12-19 21:58:00 +0000326 mach_o::KindHandler_arm::kindStrings);
327 break;
328 default:
329 llvm_unreachable("mach-o arch not supported");
330 }
331}
332
Nick Kledzike34182f2013-11-06 21:36:55 +0000333} // namespace lld
334