blob: efd507f9f486069cd1f6108e67cabed4d850d93d [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#include "ArchHandler.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000026#include "MachONormalizedFileBinaryUtils.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000027#include "lld/Core/Error.h"
28#include "lld/Core/LLVM.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000029#include "lld/Core/SharedLibraryFile.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000030#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/StringSwitch.h"
33#include "llvm/ADT/Twine.h"
Nick Kledzik141330a2014-09-03 19:52:50 +000034#include "llvm/Object/MachO.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000035#include "llvm/Support/Casting.h"
Rafael Espindola372bc702014-06-13 17:20:48 +000036#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000037#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FileOutputBuffer.h"
39#include "llvm/Support/Host.h"
40#include "llvm/Support/MachO.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/raw_ostream.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000043#include <functional>
Rafael Espindola54427cc2014-06-12 17:15:58 +000044#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000045
46using namespace llvm::MachO;
Nick Kledzik141330a2014-09-03 19:52:50 +000047using llvm::object::ExportEntry;
48using llvm::object::MachOObjectFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000049
50namespace lld {
51namespace mach_o {
52namespace normalized {
53
54// Utility to call a lambda expression on each load command.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000055static std::error_code forEachLoadCommand(
56 StringRef lcRange, unsigned lcCount, bool swap, bool is64,
57 std::function<bool(uint32_t cmd, uint32_t size, const char *lc)> func) {
Nick Kledzike34182f2013-11-06 21:36:55 +000058 const char* p = lcRange.begin();
59 for (unsigned i=0; i < lcCount; ++i) {
60 const load_command *lc = reinterpret_cast<const load_command*>(p);
61 load_command lcCopy;
62 const load_command *slc = lc;
63 if (swap) {
64 memcpy(&lcCopy, lc, sizeof(load_command));
65 swapStruct(lcCopy);
66 slc = &lcCopy;
67 }
68 if ( (p + slc->cmdsize) > lcRange.end() )
Rafael Espindola372bc702014-06-13 17:20:48 +000069 return make_error_code(llvm::errc::executable_format_error);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000070
Nick Kledzike34182f2013-11-06 21:36:55 +000071 if (func(slc->cmd, slc->cmdsize, p))
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000072 return std::error_code();
Shankar Easwaran3d8de472014-01-27 03:09:26 +000073
Nick Kledzike34182f2013-11-06 21:36:55 +000074 p += slc->cmdsize;
Shankar Easwaran3d8de472014-01-27 03:09:26 +000075 }
76
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000077 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +000078}
79
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000080static std::error_code appendRelocations(Relocations &relocs, StringRef buffer,
81 bool swap, bool bigEndian,
82 uint32_t reloff, uint32_t nreloc) {
Nick Kledzike34182f2013-11-06 21:36:55 +000083 if ((reloff + nreloc*8) > buffer.size())
Rafael Espindola372bc702014-06-13 17:20:48 +000084 return make_error_code(llvm::errc::executable_format_error);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000085 const any_relocation_info* relocsArray =
Joey Gouly010b3762014-01-14 22:32:38 +000086 reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000087
Nick Kledzike34182f2013-11-06 21:36:55 +000088 for(uint32_t i=0; i < nreloc; ++i) {
89 relocs.push_back(unpackRelocation(relocsArray[i], swap, bigEndian));
90 }
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000091 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +000092}
93
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000094static std::error_code
Nick Kledzik388f3d02014-05-28 01:16:35 +000095appendIndirectSymbols(IndirectSymbols &isyms, StringRef buffer, bool swap,
96 bool bigEndian, uint32_t istOffset, uint32_t istCount,
97 uint32_t startIndex, uint32_t count) {
98 if ((istOffset + istCount*4) > buffer.size())
Rafael Espindola372bc702014-06-13 17:20:48 +000099 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzik388f3d02014-05-28 01:16:35 +0000100 if (startIndex+count > istCount)
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 const uint32_t *indirectSymbolArray =
103 reinterpret_cast<const uint32_t*>(buffer.begin()+istOffset);
104
105 for(uint32_t i=0; i < count; ++i) {
106 isyms.push_back(read32(swap, indirectSymbolArray[startIndex+i]));
107 }
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000108 return std::error_code();
Nick Kledzik388f3d02014-05-28 01:16:35 +0000109}
110
111
Joey Gouly010b3762014-01-14 22:32:38 +0000112template <typename T> static T readBigEndian(T t) {
113 if (llvm::sys::IsLittleEndianHost)
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000114 llvm::sys::swapByteOrder(t);
Joey Gouly010b3762014-01-14 22:32:38 +0000115 return t;
116}
Nick Kledzike34182f2013-11-06 21:36:55 +0000117
Nick Kledzik635f9c72014-09-04 20:08:30 +0000118
119static bool isMachOHeader(const mach_header *mh, bool &is64, bool &swap) {
120 switch (mh->magic) {
121 case llvm::MachO::MH_MAGIC:
122 is64 = false;
123 swap = false;
124 return true;
125 case llvm::MachO::MH_MAGIC_64:
126 is64 = true;
127 swap = false;
128 return true;
129 case llvm::MachO::MH_CIGAM:
130 is64 = false;
131 swap = true;
132 return true;
133 case llvm::MachO::MH_CIGAM_64:
134 is64 = true;
135 swap = true;
136 return true;
137 default:
138 return false;
139 }
140}
141
142
143bool isThinObjectFile(StringRef path, MachOLinkingContext::Arch &arch) {
144 // Try opening and mapping file at path.
145 ErrorOr<std::unique_ptr<MemoryBuffer>> b = MemoryBuffer::getFileOrSTDIN(path);
146 if (b.getError())
147 return false;
148
149 // If file length < 32 it is too small to be mach-o object file.
150 StringRef fileBuffer = b->get()->getBuffer();
151 if (fileBuffer.size() < 32)
152 return false;
153
154 // If file buffer does not start with MH_MAGIC (and variants), not obj file.
155 const mach_header *mh = reinterpret_cast<const mach_header *>(
156 fileBuffer.begin());
157 bool is64, swap;
158 if (!isMachOHeader(mh, is64, swap))
159 return false;
160
161 // If not MH_OBJECT, not object file.
162 if (read32(swap, mh->filetype) != MH_OBJECT)
163 return false;
164
165 // Lookup up arch from cpu/subtype pair.
166 arch = MachOLinkingContext::archFromCpuType(read32(swap, mh->cputype),
167 read32(swap, mh->cpusubtype));
168 return true;
169}
170
Nick Kledzik14b5d202014-10-08 01:48:10 +0000171
172bool sliceFromFatFile(const MemoryBuffer &mb, MachOLinkingContext::Arch arch,
173 uint32_t &offset, uint32_t &size) {
174 const char *start = mb.getBufferStart();
175 const llvm::MachO::fat_header *fh =
176 reinterpret_cast<const llvm::MachO::fat_header *>(start);
177 if (readBigEndian(fh->magic) != llvm::MachO::FAT_MAGIC)
178 return false;
179 uint32_t nfat_arch = readBigEndian(fh->nfat_arch);
180 const fat_arch *fstart =
181 reinterpret_cast<const fat_arch *>(start + sizeof(fat_header));
182 const fat_arch *fend =
183 reinterpret_cast<const fat_arch *>(start + sizeof(fat_header) +
184 sizeof(fat_arch) * nfat_arch);
185 const uint32_t reqCpuType = MachOLinkingContext::cpuTypeFromArch(arch);
186 const uint32_t reqCpuSubtype = MachOLinkingContext::cpuSubtypeFromArch(arch);
187 for (const fat_arch *fa = fstart; fa < fend; ++fa) {
188 if ((readBigEndian(fa->cputype) == reqCpuType) &&
189 (readBigEndian(fa->cpusubtype) == reqCpuSubtype)) {
190 offset = readBigEndian(fa->offset);
191 size = readBigEndian(fa->size);
192 if ((offset + size) > mb.getBufferSize())
193 return false;
194 return true;
195 }
196 }
197 return false;
198}
199
Nick Kledzike34182f2013-11-06 21:36:55 +0000200/// Reads a mach-o file and produces an in-memory normalized view.
Joey Gouly010b3762014-01-14 22:32:38 +0000201ErrorOr<std::unique_ptr<NormalizedFile>>
202readBinary(std::unique_ptr<MemoryBuffer> &mb,
203 const MachOLinkingContext::Arch arch) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000204 // Make empty NormalizedFile.
205 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
206
Joey Gouly010b3762014-01-14 22:32:38 +0000207 const char *start = mb->getBufferStart();
208 size_t objSize = mb->getBufferSize();
Joey Gouly010b3762014-01-14 22:32:38 +0000209 const mach_header *mh = reinterpret_cast<const mach_header *>(start);
Nick Kledzik14b5d202014-10-08 01:48:10 +0000210
211 uint32_t sliceOffset;
212 uint32_t sliceSize;
213 if (sliceFromFatFile(*mb, arch, sliceOffset, sliceSize)) {
214 start = &start[sliceOffset];
215 objSize = sliceSize;
Joey Gouly010b3762014-01-14 22:32:38 +0000216 mh = reinterpret_cast<const mach_header *>(start);
217 }
218
Nick Kledzik14b5d202014-10-08 01:48:10 +0000219 // Determine endianness and pointer size for mach-o file.
Nick Kledzike34182f2013-11-06 21:36:55 +0000220 bool is64, swap;
Nick Kledzik635f9c72014-09-04 20:08:30 +0000221 if (!isMachOHeader(mh, is64, swap))
Rafael Espindola372bc702014-06-13 17:20:48 +0000222 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000223
224 // Endian swap header, if needed.
225 mach_header headerCopy;
226 const mach_header *smh = mh;
227 if (swap) {
228 memcpy(&headerCopy, mh, sizeof(mach_header));
229 swapStruct(headerCopy);
230 smh = &headerCopy;
231 }
232
233 // Validate head and load commands fit in buffer.
234 const uint32_t lcCount = smh->ncmds;
Joey Gouly010b3762014-01-14 22:32:38 +0000235 const char *lcStart =
236 start + (is64 ? sizeof(mach_header_64) : sizeof(mach_header));
Nick Kledzike34182f2013-11-06 21:36:55 +0000237 StringRef lcRange(lcStart, smh->sizeofcmds);
Joey Gouly010b3762014-01-14 22:32:38 +0000238 if (lcRange.end() > (start + objSize))
Rafael Espindola372bc702014-06-13 17:20:48 +0000239 return make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000240
Nick Kledzik378066c2014-06-30 22:57:33 +0000241 // Get architecture from mach_header.
Nick Kledzike34182f2013-11-06 21:36:55 +0000242 f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
Nick Kledzik378066c2014-06-30 22:57:33 +0000243 if (f->arch != arch) {
244 return make_dynamic_error_code(Twine("file is wrong architecture. Expected "
245 "(" + MachOLinkingContext::nameFromArch(arch)
246 + ") found ("
247 + MachOLinkingContext::nameFromArch(f->arch)
248 + ")" ));
249 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000250 bool isBigEndianArch = MachOLinkingContext::isBigEndian(f->arch);
251 // Copy file type and flags
252 f->fileType = HeaderFileType(smh->filetype);
253 f->flags = smh->flags;
254
255
Nick Kledzik388f3d02014-05-28 01:16:35 +0000256 // Pre-scan load commands looking for indirect symbol table.
257 uint32_t indirectSymbolTableOffset = 0;
258 uint32_t indirectSymbolTableCount = 0;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000259 std::error_code ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
260 [&](uint32_t cmd, uint32_t size,
261 const char *lc) -> bool {
Nick Kledzik388f3d02014-05-28 01:16:35 +0000262 if (cmd == LC_DYSYMTAB) {
263 const dysymtab_command *d = reinterpret_cast<const dysymtab_command*>(lc);
264 indirectSymbolTableOffset = read32(swap, d->indirectsymoff);
265 indirectSymbolTableCount = read32(swap, d->nindirectsyms);
266 return true;
267 }
268 return false;
269 });
270 if (ec)
271 return ec;
272
273 // Walk load commands looking for segments/sections and the symbol table.
Nick Kledzik21921372014-07-24 23:06:56 +0000274 const data_in_code_entry *dataInCode = nullptr;
Nick Kledzik141330a2014-09-03 19:52:50 +0000275 const dyld_info_command *dyldInfo = nullptr;
Nick Kledzik21921372014-07-24 23:06:56 +0000276 uint32_t dataInCodeSize = 0;
Nick Kledzik388f3d02014-05-28 01:16:35 +0000277 ec = forEachLoadCommand(lcRange, lcCount, swap, is64,
278 [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000279 switch(cmd) {
280 case LC_SEGMENT_64:
281 if (is64) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000282 const segment_command_64 *seg =
Nick Kledzike34182f2013-11-06 21:36:55 +0000283 reinterpret_cast<const segment_command_64*>(lc);
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000284 const unsigned sectionCount = (swap
285 ? llvm::sys::getSwappedBytes(seg->nsects)
286 : seg->nsects);
Nick Kledzike34182f2013-11-06 21:36:55 +0000287 const section_64 *sects = reinterpret_cast<const section_64*>
288 (lc + sizeof(segment_command_64));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000289 const unsigned lcSize = sizeof(segment_command_64)
Nick Kledzike34182f2013-11-06 21:36:55 +0000290 + sectionCount*sizeof(section_64);
291 // Verify sections don't extend beyond end of segment load command.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000292 if (lcSize > size)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000293 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000294 for (unsigned i=0; i < sectionCount; ++i) {
295 const section_64 *sect = &sects[i];
296 Section section;
297 section.segmentName = getString16(sect->segname);
298 section.sectionName = getString16(sect->sectname);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000299 section.type = (SectionType)(read32(swap, sect->flags)
Nick Kledzike34182f2013-11-06 21:36:55 +0000300 & SECTION_TYPE);
301 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
302 section.alignment = read32(swap, sect->align);
303 section.address = read64(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000304 const uint8_t *content =
305 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000306 size_t contentSize = read64(swap, sect->size);
307 // Note: this assign() is copying the content bytes. Ideally,
308 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000309 section.content = llvm::makeArrayRef(content, contentSize);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000310 appendRelocations(section.relocations, mb->getBuffer(),
311 swap, isBigEndianArch, read32(swap, sect->reloff),
Nick Kledzike34182f2013-11-06 21:36:55 +0000312 read32(swap, sect->nreloc));
Nick Kledzik388f3d02014-05-28 01:16:35 +0000313 if (section.type == S_NON_LAZY_SYMBOL_POINTERS) {
314 appendIndirectSymbols(section.indirectSymbols, mb->getBuffer(),
315 swap, isBigEndianArch,
316 indirectSymbolTableOffset,
317 indirectSymbolTableCount,
318 read32(swap, sect->reserved1), contentSize/4);
319 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000320 f->sections.push_back(section);
321 }
322 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000323 break;
324 case LC_SEGMENT:
325 if (!is64) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000326 const segment_command *seg =
Nick Kledzike34182f2013-11-06 21:36:55 +0000327 reinterpret_cast<const segment_command*>(lc);
Artyom Skrobovf8874b02014-06-14 13:26:14 +0000328 const unsigned sectionCount = (swap
329 ? llvm::sys::getSwappedBytes(seg->nsects)
330 : seg->nsects);
Nick Kledzike34182f2013-11-06 21:36:55 +0000331 const section *sects = reinterpret_cast<const section*>
332 (lc + sizeof(segment_command));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000333 const unsigned lcSize = sizeof(segment_command)
Nick Kledzike34182f2013-11-06 21:36:55 +0000334 + sectionCount*sizeof(section);
335 // Verify sections don't extend beyond end of segment load command.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000336 if (lcSize > size)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000337 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000338 for (unsigned i=0; i < sectionCount; ++i) {
339 const section *sect = &sects[i];
340 Section section;
341 section.segmentName = getString16(sect->segname);
342 section.sectionName = getString16(sect->sectname);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000343 section.type = (SectionType)(read32(swap, sect->flags)
Nick Kledzike34182f2013-11-06 21:36:55 +0000344 & SECTION_TYPE);
345 section.attributes = read32(swap, sect->flags) & SECTION_ATTRIBUTES;
346 section.alignment = read32(swap, sect->align);
347 section.address = read32(swap, sect->addr);
Joey Gouly010b3762014-01-14 22:32:38 +0000348 const uint8_t *content =
349 (uint8_t *)start + read32(swap, sect->offset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000350 size_t contentSize = read32(swap, sect->size);
351 // Note: this assign() is copying the content bytes. Ideally,
352 // we can use a custom allocator for vector to avoid the copy.
Nick Kledzik6edd7222014-01-11 01:07:43 +0000353 section.content = llvm::makeArrayRef(content, contentSize);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000354 appendRelocations(section.relocations, mb->getBuffer(),
355 swap, isBigEndianArch, read32(swap, sect->reloff),
Nick Kledzike34182f2013-11-06 21:36:55 +0000356 read32(swap, sect->nreloc));
Nick Kledzik388f3d02014-05-28 01:16:35 +0000357 if (section.type == S_NON_LAZY_SYMBOL_POINTERS) {
358 appendIndirectSymbols(section.indirectSymbols, mb->getBuffer(),
359 swap, isBigEndianArch,
360 indirectSymbolTableOffset,
361 indirectSymbolTableCount,
362 read32(swap, sect->reserved1), contentSize/4);
363 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000364 f->sections.push_back(section);
365 }
366 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000367 break;
368 case LC_SYMTAB: {
Nick Kledzike34182f2013-11-06 21:36:55 +0000369 const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
Joey Gouly010b3762014-01-14 22:32:38 +0000370 const char *strings = start + read32(swap, st->stroff);
Nick Kledzike34182f2013-11-06 21:36:55 +0000371 const uint32_t strSize = read32(swap, st->strsize);
372 // Validate string pool and symbol table all in buffer.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000373 if ( read32(swap, st->stroff)+read32(swap, st->strsize)
Joey Gouly010b3762014-01-14 22:32:38 +0000374 > objSize )
Rafael Espindola1d364c12014-06-03 04:41:30 +0000375 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000376 if (is64) {
377 const uint32_t symOffset = read32(swap, st->symoff);
378 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000379 if ( symOffset+(symCount*sizeof(nlist_64)) > objSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000380 return true;
Joey Gouly010b3762014-01-14 22:32:38 +0000381 const nlist_64 *symbols =
382 reinterpret_cast<const nlist_64 *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000383 // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
384 for(uint32_t i=0; i < symCount; ++i) {
385 const nlist_64 *sin = &symbols[i];
386 nlist_64 tempSym;
387 if (swap) {
388 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
389 }
390 Symbol sout;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000391 if (sin->n_strx > strSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000392 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000393 sout.name = &strings[sin->n_strx];
394 sout.type = (NListType)(sin->n_type & N_TYPE);
395 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
396 sout.sect = sin->n_sect;
397 sout.desc = sin->n_desc;
398 sout.value = sin->n_value;
399 if (sout.type == N_UNDF)
400 f->undefinedSymbols.push_back(sout);
Nick Kledzik3f690762014-06-27 18:25:01 +0000401 else if (sin->n_type & N_EXT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000402 f->globalSymbols.push_back(sout);
403 else
404 f->localSymbols.push_back(sout);
405 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000406 } else {
Nick Kledzike34182f2013-11-06 21:36:55 +0000407 const uint32_t symOffset = read32(swap, st->symoff);
408 const uint32_t symCount = read32(swap, st->nsyms);
Joey Gouly010b3762014-01-14 22:32:38 +0000409 if ( symOffset+(symCount*sizeof(nlist)) > objSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000410 return true;
Joey Gouly010b3762014-01-14 22:32:38 +0000411 const nlist *symbols =
412 reinterpret_cast<const nlist *>(start + symOffset);
Nick Kledzike34182f2013-11-06 21:36:55 +0000413 // Convert each nlist to a lld::mach_o::normalized::Symbol.
414 for(uint32_t i=0; i < symCount; ++i) {
415 const nlist *sin = &symbols[i];
416 nlist tempSym;
417 if (swap) {
418 tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
419 }
420 Symbol sout;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000421 if (sin->n_strx > strSize)
Rafael Espindola1d364c12014-06-03 04:41:30 +0000422 return true;
Nick Kledzike34182f2013-11-06 21:36:55 +0000423 sout.name = &strings[sin->n_strx];
424 sout.type = (NListType)(sin->n_type & N_TYPE);
425 sout.scope = (sin->n_type & (N_PEXT|N_EXT));
426 sout.sect = sin->n_sect;
427 sout.desc = sin->n_desc;
428 sout.value = sin->n_value;
429 if (sout.type == N_UNDF)
430 f->undefinedSymbols.push_back(sout);
431 else if (sout.scope == (SymbolScope)N_EXT)
432 f->globalSymbols.push_back(sout);
433 else
434 f->localSymbols.push_back(sout);
435 }
436 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000437 }
438 break;
439 case LC_ID_DYLIB: {
Tim Northover301c4e62014-07-01 08:15:41 +0000440 const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
Nick Kledzik21921372014-07-24 23:06:56 +0000441 f->installName = lc + read32(swap, dl->dylib.name);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000442 }
443 break;
444 case LC_DATA_IN_CODE: {
Nick Kledzik21921372014-07-24 23:06:56 +0000445 const linkedit_data_command *ldc =
446 reinterpret_cast<const linkedit_data_command*>(lc);
447 dataInCode = reinterpret_cast<const data_in_code_entry*>(
448 start + read32(swap, ldc->dataoff));
449 dataInCodeSize = read32(swap, ldc->datasize);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000450 }
Nick Kledzik141330a2014-09-03 19:52:50 +0000451 break;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000452 case LC_LOAD_DYLIB:
453 case LC_LOAD_WEAK_DYLIB:
454 case LC_REEXPORT_DYLIB:
455 case LC_LOAD_UPWARD_DYLIB: {
456 const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
457 DependentDylib entry;
458 entry.path = lc + read32(swap, dl->dylib.name);
459 entry.kind = LoadCommandType(cmd);
460 f->dependentDylibs.push_back(entry);
461 }
462 break;
Nick Kledzik141330a2014-09-03 19:52:50 +0000463 case LC_DYLD_INFO:
464 case LC_DYLD_INFO_ONLY:
465 dyldInfo = reinterpret_cast<const dyld_info_command*>(lc);
466 break;
Tim Northover301c4e62014-07-01 08:15:41 +0000467 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000468 return false;
469 });
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000470 if (ec)
Nick Kledzike34182f2013-11-06 21:36:55 +0000471 return ec;
472
Nick Kledzik21921372014-07-24 23:06:56 +0000473 if (dataInCode) {
474 // Convert on-disk data_in_code_entry array to DataInCode vector.
475 for (unsigned i=0; i < dataInCodeSize/sizeof(data_in_code_entry); ++i) {
476 DataInCode entry;
477 entry.offset = read32(swap, dataInCode[i].offset);
478 entry.length = read16(swap, dataInCode[i].length);
479 entry.kind = (DataRegionType)read16(swap, dataInCode[i].kind);
480 f->dataInCode.push_back(entry);
481 }
482 }
483
Nick Kledzik141330a2014-09-03 19:52:50 +0000484 if (dyldInfo) {
485 // If any exports, extract and add to normalized exportInfo vector.
486 if (dyldInfo->export_size) {
487 const uint8_t *trieStart = reinterpret_cast<const uint8_t*>(start +
488 dyldInfo->export_off);
489 ArrayRef<uint8_t> trie(trieStart, dyldInfo->export_size);
490 for (const ExportEntry &trieExport : MachOObjectFile::exports(trie)) {
491 Export normExport;
492 normExport.name = trieExport.name().copy(f->ownedAllocations);
493 normExport.offset = trieExport.address();
494 normExport.kind = ExportSymbolKind(trieExport.flags() & EXPORT_SYMBOL_FLAGS_KIND_MASK);
495 normExport.flags = trieExport.flags() & ~EXPORT_SYMBOL_FLAGS_KIND_MASK;
496 normExport.otherOffset = trieExport.other();
497 if (!trieExport.otherName().empty())
498 normExport.otherName = trieExport.otherName().copy(f->ownedAllocations);
499 f->exportInfo.push_back(normExport);
500 }
501 }
502 }
503
Nick Kledzike34182f2013-11-06 21:36:55 +0000504 return std::move(f);
505}
506
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000507class MachOReader : public Reader {
508public:
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000509 MachOReader(MachOLinkingContext &ctx) : _ctx(ctx) {}
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000510
511 bool canParse(file_magic magic, StringRef ext,
512 const MemoryBuffer &mb) const override {
Nick Kledzik14b5d202014-10-08 01:48:10 +0000513 switch (magic) {
514 case llvm::sys::fs::file_magic::macho_object:
515 case llvm::sys::fs::file_magic::macho_dynamically_linked_shared_lib:
516 case llvm::sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
517 return (mb.getBufferSize() > 32);
518 default:
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000519 return false;
Nick Kledzik14b5d202014-10-08 01:48:10 +0000520 }
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000521 }
522
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000523 std::error_code
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000524 parseFile(std::unique_ptr<MemoryBuffer> &mb, const Registry &registry,
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000525 std::vector<std::unique_ptr<File>> &result) const override {
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000526 // Convert binary file to normalized mach-o.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000527 auto normFile = readBinary(mb, _ctx.arch());
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000528 if (std::error_code ec = normFile.getError())
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000529 return ec;
530 // Convert normalized mach-o to atoms.
531 auto file = normalizedToAtoms(**normFile, mb->getBufferIdentifier(), false);
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000532 if (std::error_code ec = file.getError())
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000533 return ec;
534
535 result.push_back(std::move(*file));
536
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000537 return std::error_code();
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000538 }
539private:
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000540 MachOLinkingContext &_ctx;
Nick Kledzikcc28bc12014-05-30 01:13:49 +0000541};
542
543
Nick Kledzike34182f2013-11-06 21:36:55 +0000544} // namespace normalized
545} // namespace mach_o
Nick Kledzike5552772013-12-19 21:58:00 +0000546
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000547void Registry::addSupportMachOObjects(MachOLinkingContext &ctx) {
Nick Kledzik2458bec2014-07-16 19:49:02 +0000548 MachOLinkingContext::Arch arch = ctx.arch();
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000549 add(std::unique_ptr<Reader>(new mach_o::normalized::MachOReader(ctx)));
Nick Kledzik2458bec2014-07-16 19:49:02 +0000550 addKindTable(Reference::KindNamespace::mach_o, ctx.archHandler().kindArch(),
551 ctx.archHandler().kindStrings());
Nick Kledzik6edd7222014-01-11 01:07:43 +0000552 add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
Nick Kledzik378066c2014-06-30 22:57:33 +0000553 new mach_o::MachOYamlIOTaggedDocumentHandler(arch)));
Nick Kledzike5552772013-12-19 21:58:00 +0000554}
555
Nick Kledzik14b5d202014-10-08 01:48:10 +0000556
Nick Kledzike34182f2013-11-06 21:36:55 +0000557} // namespace lld
558