blob: 9997ca0245caeb7a057ed99083562e40f4c1c607 [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"
Nick Kledzik2458bec2014-07-16 19:49:02 +000025
26#include "ArchHandler.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000027#include "MachONormalizedFileBinaryUtils.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000028
Nick Kledzike34182f2013-11-06 21:36:55 +000029#include "lld/Core/Error.h"
30#include "lld/Core/LLVM.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000031#include "lld/Core/SharedLibraryFile.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000032#include "llvm/ADT/SmallString.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/StringSwitch.h"
35#include "llvm/ADT/Twine.h"
Nick Kledzik141330a2014-09-03 19:52:50 +000036#include "llvm/Object/MachO.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000037#include "llvm/Support/Casting.h"
Rafael Espindola372bc702014-06-13 17:20:48 +000038#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000039#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/FileOutputBuffer.h"
41#include "llvm/Support/Host.h"
42#include "llvm/Support/MachO.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/raw_ostream.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000045#include <functional>
Rafael Espindola54427cc2014-06-12 17:15:58 +000046#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000047
48using namespace llvm::MachO;
Nick Kledzik141330a2014-09-03 19:52:50 +000049using llvm::object::ExportEntry;
50using llvm::object::MachOObjectFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000051
52namespace lld {
53namespace mach_o {
54namespace normalized {
55
56// Utility to call a lambda expression on each load command.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000057static std::error_code forEachLoadCommand(
58 StringRef lcRange, unsigned lcCount, bool swap, bool is64,
59 std::function<bool(uint32_t cmd, uint32_t size, const char *lc)> func) {
Nick Kledzike34182f2013-11-06 21:36:55 +000060 const char* p = lcRange.begin();
61 for (unsigned i=0; i < lcCount; ++i) {
62 const load_command *lc = reinterpret_cast<const load_command*>(p);
63 load_command lcCopy;
64 const load_command *slc = lc;
65 if (swap) {
66 memcpy(&lcCopy, lc, sizeof(load_command));
67 swapStruct(lcCopy);
68 slc = &lcCopy;
69 }
70 if ( (p + slc->cmdsize) > lcRange.end() )
Rafael Espindola372bc702014-06-13 17:20:48 +000071 return make_error_code(llvm::errc::executable_format_error);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000072
Nick Kledzike34182f2013-11-06 21:36:55 +000073 if (func(slc->cmd, slc->cmdsize, p))
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000074 return std::error_code();
Shankar Easwaran3d8de472014-01-27 03:09:26 +000075
Nick Kledzike34182f2013-11-06 21:36:55 +000076 p += slc->cmdsize;
Shankar Easwaran3d8de472014-01-27 03:09:26 +000077 }
78
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000079 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +000080}
81
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000082static std::error_code appendRelocations(Relocations &relocs, StringRef buffer,
83 bool swap, bool bigEndian,
84 uint32_t reloff, uint32_t nreloc) {
Nick Kledzike34182f2013-11-06 21:36:55 +000085 if ((reloff + nreloc*8) > buffer.size())
Rafael Espindola372bc702014-06-13 17:20:48 +000086 return make_error_code(llvm::errc::executable_format_error);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000087 const any_relocation_info* relocsArray =
Joey Gouly010b3762014-01-14 22:32:38 +000088 reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000089
Nick Kledzike34182f2013-11-06 21:36:55 +000090 for(uint32_t i=0; i < nreloc; ++i) {
91 relocs.push_back(unpackRelocation(relocsArray[i], swap, bigEndian));
92 }
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000093 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +000094}
95
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000096static std::error_code
Nick Kledzik388f3d02014-05-28 01:16:35 +000097appendIndirectSymbols(IndirectSymbols &isyms, StringRef buffer, bool swap,
98 bool bigEndian, uint32_t istOffset, uint32_t istCount,
99 uint32_t startIndex, uint32_t count) {
100 if ((istOffset + istCount*4) > buffer.size())
Rafael Espindola372bc702014-06-13 17:20:48 +0000101 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzik388f3d02014-05-28 01:16:35 +0000102 if (startIndex+count > istCount)
Rafael Espindola372bc702014-06-13 17:20:48 +0000103 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzik388f3d02014-05-28 01:16:35 +0000104 const uint32_t *indirectSymbolArray =
105 reinterpret_cast<const uint32_t*>(buffer.begin()+istOffset);
106
107 for(uint32_t i=0; i < count; ++i) {
108 isyms.push_back(read32(swap, indirectSymbolArray[startIndex+i]));
109 }
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000110 return std::error_code();
Nick Kledzik388f3d02014-05-28 01:16:35 +0000111}
112
113
Joey Gouly010b3762014-01-14 22:32:38 +0000114template <typename T> static T readBigEndian(T t) {
115 if (llvm::sys::IsLittleEndianHost)
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000116 llvm::sys::swapByteOrder(t);
Joey Gouly010b3762014-01-14 22:32:38 +0000117 return t;
118}
Nick Kledzike34182f2013-11-06 21:36:55 +0000119
Nick Kledzik635f9c72014-09-04 20:08:30 +0000120
121static bool isMachOHeader(const mach_header *mh, bool &is64, bool &swap) {
122 switch (mh->magic) {
123 case llvm::MachO::MH_MAGIC:
124 is64 = false;
125 swap = false;
126 return true;
127 case llvm::MachO::MH_MAGIC_64:
128 is64 = true;
129 swap = false;
130 return true;
131 case llvm::MachO::MH_CIGAM:
132 is64 = false;
133 swap = true;
134 return true;
135 case llvm::MachO::MH_CIGAM_64:
136 is64 = true;
137 swap = true;
138 return true;
139 default:
140 return false;
141 }
142}
143
144
145bool isThinObjectFile(StringRef path, MachOLinkingContext::Arch &arch) {
146 // Try opening and mapping file at path.
147 ErrorOr<std::unique_ptr<MemoryBuffer>> b = MemoryBuffer::getFileOrSTDIN(path);
148 if (b.getError())
149 return false;
150
151 // If file length < 32 it is too small to be mach-o object file.
152 StringRef fileBuffer = b->get()->getBuffer();
153 if (fileBuffer.size() < 32)
154 return false;
155
156 // If file buffer does not start with MH_MAGIC (and variants), not obj file.
157 const mach_header *mh = reinterpret_cast<const mach_header *>(
158 fileBuffer.begin());
159 bool is64, swap;
160 if (!isMachOHeader(mh, is64, swap))
161 return false;
162
163 // If not MH_OBJECT, not object file.
164 if (read32(swap, mh->filetype) != MH_OBJECT)
165 return false;
166
167 // Lookup up arch from cpu/subtype pair.
168 arch = MachOLinkingContext::archFromCpuType(read32(swap, mh->cputype),
169 read32(swap, mh->cpusubtype));
170 return true;
171}
172
Nick Kledzike34182f2013-11-06 21:36:55 +0000173/// Reads a mach-o file and produces an in-memory normalized view.
Joey Gouly010b3762014-01-14 22:32:38 +0000174ErrorOr<std::unique_ptr<NormalizedFile>>
175readBinary(std::unique_ptr<MemoryBuffer> &mb,
176 const MachOLinkingContext::Arch arch) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000177 // Make empty NormalizedFile.
178 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
179
Joey Gouly010b3762014-01-14 22:32:38 +0000180 const char *start = mb->getBufferStart();
181 size_t objSize = mb->getBufferSize();
182
Nick Kledzike34182f2013-11-06 21:36:55 +0000183 // Determine endianness and pointer size for mach-o file.
Joey Gouly010b3762014-01-14 22:32:38 +0000184 const mach_header *mh = reinterpret_cast<const mach_header *>(start);
185 bool isFat = mh->magic == llvm::MachO::FAT_CIGAM ||
186 mh->magic == llvm::MachO::FAT_MAGIC;
187 if (isFat) {
188 uint32_t cputype = MachOLinkingContext::cpuTypeFromArch(arch);
189 uint32_t cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(arch);
190 const fat_header *fh = reinterpret_cast<const fat_header *>(start);
191 uint32_t nfat_arch = readBigEndian(fh->nfat_arch);
192 const fat_arch *fa =
193 reinterpret_cast<const fat_arch *>(start + sizeof(fat_header));
194 bool foundArch = false;
195 while (nfat_arch-- > 0) {
196 if (readBigEndian(fa->cputype) == cputype &&
197 readBigEndian(fa->cpusubtype) == cpusubtype) {
198 foundArch = true;
199 break;
200 }
201 fa++;
202 }
203 if (!foundArch) {
Nick Kledzik378066c2014-06-30 22:57:33 +0000204 return make_dynamic_error_code(Twine("file does not contain required"
205 " architecture ("
206 + MachOLinkingContext::nameFromArch(arch)
207 + ")" ));
Joey Gouly010b3762014-01-14 22:32:38 +0000208 }
209 objSize = readBigEndian(fa->size);
210 uint32_t offset = readBigEndian(fa->offset);
211 if ((offset + objSize) > mb->getBufferSize())
Rafael Espindola372bc702014-06-13 17:20:48 +0000212 return make_error_code(llvm::errc::executable_format_error);
Joey Gouly010b3762014-01-14 22:32:38 +0000213 start += offset;
214 mh = reinterpret_cast<const mach_header *>(start);
215 }
216
Nick Kledzike34182f2013-11-06 21:36:55 +0000217 bool is64, swap;
Nick Kledzik635f9c72014-09-04 20:08:30 +0000218 if (!isMachOHeader(mh, is64, swap))
Rafael Espindola372bc702014-06-13 17:20:48 +0000219 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000220
221 // Endian swap header, if needed.
222 mach_header headerCopy;
223 const mach_header *smh = mh;
224 if (swap) {
225 memcpy(&headerCopy, mh, sizeof(mach_header));
226 swapStruct(headerCopy);
227 smh = &headerCopy;
228 }
229
230 // Validate head and load commands fit in buffer.
231 const uint32_t lcCount = smh->ncmds;
Joey Gouly010b3762014-01-14 22:32:38 +0000232 const char *lcStart =
233 start + (is64 ? sizeof(mach_header_64) : sizeof(mach_header));
Nick Kledzike34182f2013-11-06 21:36:55 +0000234 StringRef lcRange(lcStart, smh->sizeofcmds);
Joey Gouly010b3762014-01-14 22:32:38 +0000235 if (lcRange.end() > (start + objSize))
Rafael Espindola372bc702014-06-13 17:20:48 +0000236 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000237
Nick Kledzik378066c2014-06-30 22:57:33 +0000238 // Get architecture from mach_header.
Nick Kledzike34182f2013-11-06 21:36:55 +0000239 f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
Nick Kledzik378066c2014-06-30 22:57:33 +0000240 if (f->arch != arch) {
241 return make_dynamic_error_code(Twine("file is wrong architecture. Expected "
242 "(" + MachOLinkingContext::nameFromArch(arch)
243 + ") found ("
244 + MachOLinkingContext::nameFromArch(f->arch)
245 + ")" ));
246 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000247 bool isBigEndianArch = MachOLinkingContext::isBigEndian(f->arch);
248 // Copy file type and flags
249 f->fileType = HeaderFileType(smh->filetype);
250 f->flags = smh->flags;
251
252
Nick Kledzik388f3d02014-05-28 01:16:35 +0000253 // Pre-scan load commands looking for indirect symbol table.
254 uint32_t indirectSymbolTableOffset = 0;
255 uint32_t indirectSymbolTableCount = 0;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000256 std::error_code ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
257 [&](uint32_t cmd, uint32_t size,
258 const char *lc) -> bool {
Nick Kledzik388f3d02014-05-28 01:16:35 +0000259 if (cmd == LC_DYSYMTAB) {
260 const dysymtab_command *d = reinterpret_cast<const dysymtab_command*>(lc);
261 indirectSymbolTableOffset = read32(swap, d->indirectsymoff);
262 indirectSymbolTableCount = read32(swap, d->nindirectsyms);
263 return true;
264 }
265 return false;
266 });
267 if (ec)
268 return ec;
269
270 // Walk load commands looking for segments/sections and the symbol table.
Nick Kledzik21921372014-07-24 23:06:56 +0000271 const data_in_code_entry *dataInCode = nullptr;
Nick Kledzik141330a2014-09-03 19:52:50 +0000272 const dyld_info_command *dyldInfo = nullptr;
Nick Kledzik21921372014-07-24 23:06:56 +0000273 uint32_t dataInCodeSize = 0;
Nick Kledzik388f3d02014-05-28 01:16:35 +0000274 ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
275 [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000276 switch(cmd) {
277 case LC_SEGMENT_64:
278 if (is64) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000279 const segment_command_64 *seg =
Nick Kledzike34182f2013-11-06 21:36:55 +0000280 reinterpret_cast<const segment_command_64*>(lc);
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000281 const unsigned sectionCount = (swap
282 ? llvm::sys::getSwappedBytes(seg->nsects)
283 : seg->nsects);
Nick Kledzike34182f2013-11-06 21:36:55 +0000284 const section_64 *sects = reinterpret_cast<const section_64*>
285 (lc + sizeof(segment_command_64));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000286 const unsigned lcSize = sizeof(segment_command_64)
Nick Kledzike34182f2013-11-06 21:36:55 +0000287 + sectionCount*sizeof(section_64);
288 // Verify sections don't extend beyond end of segment load command.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000289 if (lcSize > size)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000290 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000291 for (unsigned i=0; i < sectionCount; ++i) {
292 const section_64 *sect = &sects[i];
293 Section section;
294 section.segmentName = getString16(sect->segname);
295 section.sectionName = getString16(sect->sectname);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000296 section.type = (SectionType)(read32(swap, sect->flags)
Nick Kledzike34182f2013-11-06 21:36:55 +0000297 & SECTION_TYPE);
298 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
299 section.alignment = read32(swap, sect->align);
300 section.address = read64(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000301 const uint8_t *content =
302 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000303 size_t contentSize = read64(swap, sect->size);
304 // Note: this assign() is copying the content bytes. Ideally,
305 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000306 section.content = llvm::makeArrayRef(content, contentSize);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000307 appendRelocations(section.relocations, mb->getBuffer(),
308 swap, isBigEndianArch, read32(swap, sect->reloff),
Nick Kledzike34182f2013-11-06 21:36:55 +0000309 read32(swap, sect->nreloc));
Nick Kledzik388f3d02014-05-28 01:16:35 +0000310 if (section.type == S_NON_LAZY_SYMBOL_POINTERS) {
311 appendIndirectSymbols(section.indirectSymbols, mb->getBuffer(),
312 swap, isBigEndianArch,
313 indirectSymbolTableOffset,
314 indirectSymbolTableCount,
315 read32(swap, sect->reserved1), contentSize/4);
316 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000317 f->sections.push_back(section);
318 }
319 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000320 break;
321 case LC_SEGMENT:
322 if (!is64) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000323 const segment_command *seg =
Nick Kledzike34182f2013-11-06 21:36:55 +0000324 reinterpret_cast<const segment_command*>(lc);
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000325 const unsigned sectionCount = (swap
326 ? llvm::sys::getSwappedBytes(seg->nsects)
327 : seg->nsects);
Nick Kledzike34182f2013-11-06 21:36:55 +0000328 const section *sects = reinterpret_cast<const section*>
329 (lc + sizeof(segment_command));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000330 const unsigned lcSize = sizeof(segment_command)
Nick Kledzike34182f2013-11-06 21:36:55 +0000331 + sectionCount*sizeof(section);
332 // Verify sections don't extend beyond end of segment load command.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000333 if (lcSize > size)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000334 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000335 for (unsigned i=0; i < sectionCount; ++i) {
336 const section *sect = &sects[i];
337 Section section;
338 section.segmentName = getString16(sect->segname);
339 section.sectionName = getString16(sect->sectname);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000340 section.type = (SectionType)(read32(swap, sect->flags)
Nick Kledzike34182f2013-11-06 21:36:55 +0000341 & SECTION_TYPE);
342 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
343 section.alignment = read32(swap, sect->align);
344 section.address = read32(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000345 const uint8_t *content =
346 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000347 size_t contentSize = read32(swap, sect->size);
348 // Note: this assign() is copying the content bytes. Ideally,
349 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000350 section.content = llvm::makeArrayRef(content, contentSize);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000351 appendRelocations(section.relocations, mb->getBuffer(),
352 swap, isBigEndianArch, read32(swap, sect->reloff),
Nick Kledzike34182f2013-11-06 21:36:55 +0000353 read32(swap, sect->nreloc));
Nick Kledzik388f3d02014-05-28 01:16:35 +0000354 if (section.type == S_NON_LAZY_SYMBOL_POINTERS) {
355 appendIndirectSymbols(section.indirectSymbols, mb->getBuffer(),
356 swap, isBigEndianArch,
357 indirectSymbolTableOffset,
358 indirectSymbolTableCount,
359 read32(swap, sect->reserved1), contentSize/4);
360 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000361 f->sections.push_back(section);
362 }
363 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000364 break;
365 case LC_SYMTAB: {
Nick Kledzike34182f2013-11-06 21:36:55 +0000366 const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
Joey Gouly010b3762014-01-14 22:32:38 +0000367 const char *strings = start + read32(swap, st->stroff);
Nick Kledzike34182f2013-11-06 21:36:55 +0000368 const uint32_t strSize = read32(swap, st->strsize);
369 // Validate string pool and symbol table all in buffer.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000370 if ( read32(swap, st->stroff)+read32(swap, st->strsize)
Joey Gouly010b3762014-01-14 22:32:38 +0000371 > objSize )
Rafael Espindola1d364c12014-06-03 04:41:30 +0000372 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000373 if (is64) {
374 const uint32_t symOffset = read32(swap, st->symoff);
375 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000376 if ( symOffset+(symCount*sizeof(nlist_64)) > objSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000377 return true;
Joey Gouly010b3762014-01-14 22:32:38 +0000378 const nlist_64 *symbols =
379 reinterpret_cast<const nlist_64 *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000380 // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
381 for(uint32_t i=0; i < symCount; ++i) {
382 const nlist_64 *sin = &symbols[i];
383 nlist_64 tempSym;
384 if (swap) {
385 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
386 }
387 Symbol sout;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000388 if (sin->n_strx > strSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000389 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000390 sout.name = &strings[sin->n_strx];
391 sout.type = (NListType)(sin->n_type & N_TYPE);
392 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
393 sout.sect = sin->n_sect;
394 sout.desc = sin->n_desc;
395 sout.value = sin->n_value;
396 if (sout.type == N_UNDF)
397 f->undefinedSymbols.push_back(sout);
Nick Kledzik3f690762014-06-27 18:25:01 +0000398 else if (sin->n_type & N_EXT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000399 f->globalSymbols.push_back(sout);
400 else
401 f->localSymbols.push_back(sout);
402 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000403 } else {
Nick Kledzike34182f2013-11-06 21:36:55 +0000404 const uint32_t symOffset = read32(swap, st->symoff);
405 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000406 if ( symOffset+(symCount*sizeof(nlist)) > objSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000407 return true;
Joey Gouly010b3762014-01-14 22:32:38 +0000408 const nlist *symbols =
409 reinterpret_cast<const nlist *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000410 // Convert each nlist to a lld::mach_o::normalized::Symbol.
411 for(uint32_t i=0; i < symCount; ++i) {
412 const nlist *sin = &symbols[i];
413 nlist tempSym;
414 if (swap) {
415 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
416 }
417 Symbol sout;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000418 if (sin->n_strx > strSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000419 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000420 sout.name = &strings[sin->n_strx];
421 sout.type = (NListType)(sin->n_type & N_TYPE);
422 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
423 sout.sect = sin->n_sect;
424 sout.desc = sin->n_desc;
425 sout.value = sin->n_value;
426 if (sout.type == N_UNDF)
427 f->undefinedSymbols.push_back(sout);
428 else if (sout.scope == (SymbolScope)N_EXT)
429 f->globalSymbols.push_back(sout);
430 else
431 f->localSymbols.push_back(sout);
432 }
433 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000434 }
435 break;
436 case LC_ID_DYLIB: {
Tim Northover301c4e62014-07-01 08:15:41 +0000437 const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
Nick Kledzik21921372014-07-24 23:06:56 +0000438 f->installName = lc + read32(swap, dl->dylib.name);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000439 }
440 break;
441 case LC_DATA_IN_CODE: {
Nick Kledzik21921372014-07-24 23:06:56 +0000442 const linkedit_data_command *ldc =
443 reinterpret_cast<const linkedit_data_command*>(lc);
444 dataInCode = reinterpret_cast<const data_in_code_entry*>(
445 start + read32(swap, ldc->dataoff));
446 dataInCodeSize = read32(swap, ldc->datasize);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000447 }
Nick Kledzik141330a2014-09-03 19:52:50 +0000448 break;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000449 case LC_LOAD_DYLIB:
450 case LC_LOAD_WEAK_DYLIB:
451 case LC_REEXPORT_DYLIB:
452 case LC_LOAD_UPWARD_DYLIB: {
453 const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
454 DependentDylib entry;
455 entry.path = lc + read32(swap, dl->dylib.name);
456 entry.kind = LoadCommandType(cmd);
457 f->dependentDylibs.push_back(entry);
458 }
459 break;
Nick Kledzik141330a2014-09-03 19:52:50 +0000460 case LC_DYLD_INFO:
461 case LC_DYLD_INFO_ONLY:
462 dyldInfo = reinterpret_cast<const dyld_info_command*>(lc);
463 break;
Tim Northover301c4e62014-07-01 08:15:41 +0000464 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000465 return false;
466 });
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000467 if (ec)
Nick Kledzike34182f2013-11-06 21:36:55 +0000468 return ec;
469
Nick Kledzik21921372014-07-24 23:06:56 +0000470 if (dataInCode) {
471 // Convert on-disk data_in_code_entry array to DataInCode vector.
472 for (unsigned i=0; i < dataInCodeSize/sizeof(data_in_code_entry); ++i) {
473 DataInCode entry;
474 entry.offset = read32(swap, dataInCode[i].offset);
475 entry.length = read16(swap, dataInCode[i].length);
476 entry.kind = (DataRegionType)read16(swap, dataInCode[i].kind);
477 f->dataInCode.push_back(entry);
478 }
479 }
480
Nick Kledzik141330a2014-09-03 19:52:50 +0000481 if (dyldInfo) {
482 // If any exports, extract and add to normalized exportInfo vector.
483 if (dyldInfo->export_size) {
484 const uint8_t *trieStart = reinterpret_cast<const uint8_t*>(start +
485 dyldInfo->export_off);
486 ArrayRef<uint8_t> trie(trieStart, dyldInfo->export_size);
487 for (const ExportEntry &trieExport : MachOObjectFile::exports(trie)) {
488 Export normExport;
489 normExport.name = trieExport.name().copy(f->ownedAllocations);
490 normExport.offset = trieExport.address();
491 normExport.kind = ExportSymbolKind(trieExport.flags() & EXPORT_SYMBOL_FLAGS_KIND_MASK);
492 normExport.flags = trieExport.flags() & ~EXPORT_SYMBOL_FLAGS_KIND_MASK;
493 normExport.otherOffset = trieExport.other();
494 if (!trieExport.otherName().empty())
495 normExport.otherName = trieExport.otherName().copy(f->ownedAllocations);
496 f->exportInfo.push_back(normExport);
497 }
498 }
499 }
500
Nick Kledzike34182f2013-11-06 21:36:55 +0000501 return std::move(f);
502}
503
504
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000505class MachOReader : public Reader {
506public:
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000507 MachOReader(MachOLinkingContext &ctx) : _ctx(ctx) {}
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000508
509 bool canParse(file_magic magic, StringRef ext,
510 const MemoryBuffer &mb) const override {
Tim Northoverf9b13d62014-06-30 09:11:38 +0000511 if (magic != llvm::sys::fs::file_magic::macho_object &&
Nick Kledzik378066c2014-06-30 22:57:33 +0000512 magic != llvm::sys::fs::file_magic::macho_universal_binary &&
Tim Northoverf9b13d62014-06-30 09:11:38 +0000513 magic != llvm::sys::fs::file_magic::macho_dynamically_linked_shared_lib)
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000514 return false;
Nick Kledzik378066c2014-06-30 22:57:33 +0000515 return (mb.getBufferSize() > 32);
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000516 }
517
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000518 std::error_code
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000519 parseFile(std::unique_ptr<MemoryBuffer> &mb, const Registry &registry,
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000520 std::vector<std::unique_ptr<File>> &result) const override {
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000521 // Convert binary file to normalized mach-o.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000522 auto normFile = readBinary(mb, _ctx.arch());
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000523 if (std::error_code ec = normFile.getError())
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000524 return ec;
525 // Convert normalized mach-o to atoms.
526 auto file = normalizedToAtoms(**normFile, mb->getBufferIdentifier(), false);
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000527 if (std::error_code ec = file.getError())
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000528 return ec;
529
530 result.push_back(std::move(*file));
531
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000532 return std::error_code();
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000533 }
534private:
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000535 MachOLinkingContext &_ctx;
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000536};
537
538
Nick Kledzike34182f2013-11-06 21:36:55 +0000539} // namespace normalized
540} // namespace mach_o
Nick Kledzike5552772013-12-19 21:58:00 +0000541
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000542void Registry::addSupportMachOObjects(MachOLinkingContext &ctx) {
Nick Kledzik2458bec2014-07-16 19:49:02 +0000543 MachOLinkingContext::Arch arch = ctx.arch();
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000544 add(std::unique_ptr<Reader>(new mach_o::normalized::MachOReader(ctx)));
Nick Kledzik2458bec2014-07-16 19:49:02 +0000545 addKindTable(Reference::KindNamespace::mach_o, ctx.archHandler().kindArch(),
546 ctx.archHandler().kindStrings());
Nick Kledzik6edd7222014-01-11 01:07:43 +0000547 add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
Nick Kledzik378066c2014-06-30 22:57:33 +0000548 new mach_o::MachOYamlIOTaggedDocumentHandler(arch)));
Nick Kledzike5552772013-12-19 21:58:00 +0000549}
550
Nick Kledzike34182f2013-11-06 21:36:55 +0000551} // namespace lld
552