1 //===-- MachOUtils.h - Mach-o specific helpers for dsymutil --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MachOUtils.h"
11 #include "BinaryHolder.h"
13 #include "NonRelocatableStringpool.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCMachObjectWriter.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/Object/MachO.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/raw_ostream.h"
27 namespace MachOUtils {
29 std::string getArchName(StringRef Arch) {
30 if (Arch.startswith("thumb"))
31 return (llvm::Twine("arm") + Arch.drop_front(5)).str();
35 static bool runLipo(StringRef SDKPath, SmallVectorImpl<const char *> &Args) {
36 auto Path = sys::findProgramByName("lipo", makeArrayRef(SDKPath));
38 Path = sys::findProgramByName("lipo");
41 errs() << "error: lipo: " << Path.getError().message() << "\n";
47 sys::ExecuteAndWait(*Path, Args.data(), nullptr, {}, 0, 0, &ErrMsg);
49 errs() << "error: lipo: " << ErrMsg << "\n";
56 bool generateUniversalBinary(SmallVectorImpl<ArchAndFilename> &ArchFiles,
57 StringRef OutputFileName,
58 const LinkOptions &Options, StringRef SDKPath) {
59 // No need to merge one file into a universal fat binary. First, try
60 // to move it (rename) to the final location. If that fails because
61 // of cross-device link issues then copy and delete.
62 if (ArchFiles.size() == 1) {
63 StringRef From(ArchFiles.front().Path);
64 if (sys::fs::rename(From, OutputFileName)) {
65 if (std::error_code EC = sys::fs::copy_file(From, OutputFileName)) {
66 errs() << "error: while copying " << From << " to " << OutputFileName
67 << ": " << EC.message() << "\n";
70 sys::fs::remove(From);
75 SmallVector<const char *, 8> Args;
76 Args.push_back("lipo");
77 Args.push_back("-create");
79 for (auto &Thin : ArchFiles)
80 Args.push_back(Thin.Path.c_str());
82 // Align segments to match dsymutil-classic alignment
83 for (auto &Thin : ArchFiles) {
84 Thin.Arch = getArchName(Thin.Arch);
85 Args.push_back("-segalign");
86 Args.push_back(Thin.Arch.c_str());
90 Args.push_back("-output");
91 Args.push_back(OutputFileName.data());
92 Args.push_back(nullptr);
94 if (Options.Verbose) {
95 outs() << "Running lipo\n";
97 outs() << ' ' << ((Arg == nullptr) ? "\n" : Arg);
100 return Options.NoOutput ? true : runLipo(SDKPath, Args);
103 // Return a MachO::segment_command_64 that holds the same values as the passed
104 // MachO::segment_command. We do that to avoid having to duplicate the logic
105 // for 32bits and 64bits segments.
106 struct MachO::segment_command_64 adaptFrom32bits(MachO::segment_command Seg) {
107 MachO::segment_command_64 Seg64;
109 Seg64.cmdsize = Seg.cmdsize;
110 memcpy(Seg64.segname, Seg.segname, sizeof(Seg.segname));
111 Seg64.vmaddr = Seg.vmaddr;
112 Seg64.vmsize = Seg.vmsize;
113 Seg64.fileoff = Seg.fileoff;
114 Seg64.filesize = Seg.filesize;
115 Seg64.maxprot = Seg.maxprot;
116 Seg64.initprot = Seg.initprot;
117 Seg64.nsects = Seg.nsects;
118 Seg64.flags = Seg.flags;
122 // Iterate on all \a Obj segments, and apply \a Handler to them.
123 template <typename FunctionTy>
124 static void iterateOnSegments(const object::MachOObjectFile &Obj,
125 FunctionTy Handler) {
126 for (const auto &LCI : Obj.load_commands()) {
127 MachO::segment_command_64 Segment;
128 if (LCI.C.cmd == MachO::LC_SEGMENT)
129 Segment = adaptFrom32bits(Obj.getSegmentLoadCommand(LCI));
130 else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
131 Segment = Obj.getSegment64LoadCommand(LCI);
139 // Transfer the symbols described by \a NList to \a NewSymtab which is just the
140 // raw contents of the symbol table for the dSYM companion file. \returns
141 // whether the symbol was transferred or not.
142 template <typename NListTy>
143 static bool transferSymbol(NListTy NList, bool IsLittleEndian,
144 StringRef Strings, SmallVectorImpl<char> &NewSymtab,
145 NonRelocatableStringpool &NewStrings,
147 // Do not transfer undefined symbols, we want real addresses.
148 if ((NList.n_type & MachO::N_TYPE) == MachO::N_UNDF)
151 StringRef Name = StringRef(Strings.begin() + NList.n_strx);
154 (NList.n_type != MachO::N_SO) || (!Name.empty() && Name[0] != '\0');
156 } else if (NList.n_type == MachO::N_SO) {
161 // FIXME: The + 1 is here to mimic dsymutil-classic that has 2 empty
162 // strings at the start of the generated string table (There is
163 // corresponding code in the string table emission).
164 NList.n_strx = NewStrings.getStringOffset(Name) + 1;
165 if (IsLittleEndian != sys::IsLittleEndianHost)
166 MachO::swapStruct(NList);
168 NewSymtab.append(reinterpret_cast<char *>(&NList),
169 reinterpret_cast<char *>(&NList + 1));
173 // Wrapper around transferSymbol to transfer all of \a Obj symbols
174 // to \a NewSymtab. This function does not write in the output file.
175 // \returns the number of symbols in \a NewSymtab.
176 static unsigned transferSymbols(const object::MachOObjectFile &Obj,
177 SmallVectorImpl<char> &NewSymtab,
178 NonRelocatableStringpool &NewStrings) {
180 StringRef Strings = Obj.getStringTableData();
181 bool IsLittleEndian = Obj.isLittleEndian();
182 bool InDebugNote = false;
185 for (const object::SymbolRef &Symbol : Obj.symbols()) {
186 object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
187 if (transferSymbol(Obj.getSymbol64TableEntry(DRI), IsLittleEndian,
188 Strings, NewSymtab, NewStrings, InDebugNote))
192 for (const object::SymbolRef &Symbol : Obj.symbols()) {
193 object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
194 if (transferSymbol(Obj.getSymbolTableEntry(DRI), IsLittleEndian, Strings,
195 NewSymtab, NewStrings, InDebugNote))
202 static MachO::section
203 getSection(const object::MachOObjectFile &Obj,
204 const MachO::segment_command &Seg,
205 const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
206 return Obj.getSection(LCI, Idx);
209 static MachO::section_64
210 getSection(const object::MachOObjectFile &Obj,
211 const MachO::segment_command_64 &Seg,
212 const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
213 return Obj.getSection64(LCI, Idx);
216 // Transfer \a Segment from \a Obj to the output file. This calls into \a Writer
217 // to write these load commands directly in the output file at the current
219 // The function also tries to find a hole in the address map to fit the __DWARF
220 // segment of \a DwarfSegmentSize size. \a EndAddress is updated to point at the
221 // highest segment address.
222 // When the __LINKEDIT segment is transferred, its offset and size are set resp.
223 // to \a LinkeditOffset and \a LinkeditSize.
224 template <typename SegmentTy>
225 static void transferSegmentAndSections(
226 const object::MachOObjectFile::LoadCommandInfo &LCI, SegmentTy Segment,
227 const object::MachOObjectFile &Obj, MCObjectWriter &Writer,
228 uint64_t LinkeditOffset, uint64_t LinkeditSize, uint64_t DwarfSegmentSize,
229 uint64_t &GapForDwarf, uint64_t &EndAddress) {
230 if (StringRef("__DWARF") == Segment.segname)
233 Segment.fileoff = Segment.filesize = 0;
235 if (StringRef("__LINKEDIT") == Segment.segname) {
236 Segment.fileoff = LinkeditOffset;
237 Segment.filesize = LinkeditSize;
238 // Resize vmsize by rounding to the page size.
239 Segment.vmsize = alignTo(LinkeditSize, 0x1000);
242 // Check if the end address of the last segment and our current
243 // start address leave a sufficient gap to store the __DWARF
245 uint64_t PrevEndAddress = EndAddress;
246 EndAddress = alignTo(EndAddress, 0x1000);
247 if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress &&
248 Segment.vmaddr - EndAddress >= DwarfSegmentSize)
249 GapForDwarf = EndAddress;
251 // The segments are not necessarily sorted by their vmaddr.
253 std::max<uint64_t>(PrevEndAddress, Segment.vmaddr + Segment.vmsize);
254 unsigned nsects = Segment.nsects;
255 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
256 MachO::swapStruct(Segment);
258 StringRef(reinterpret_cast<char *>(&Segment), sizeof(Segment)));
259 for (unsigned i = 0; i < nsects; ++i) {
260 auto Sect = getSection(Obj, Segment, LCI, i);
261 Sect.offset = Sect.reloff = Sect.nreloc = 0;
262 if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
263 MachO::swapStruct(Sect);
264 Writer.writeBytes(StringRef(reinterpret_cast<char *>(&Sect), sizeof(Sect)));
268 // Write the __DWARF segment load command to the output file.
269 static void createDwarfSegment(uint64_t VMAddr, uint64_t FileOffset,
270 uint64_t FileSize, unsigned NumSections,
271 MCAsmLayout &Layout, MachObjectWriter &Writer) {
272 Writer.writeSegmentLoadCommand("__DWARF", NumSections, VMAddr,
273 alignTo(FileSize, 0x1000), FileOffset,
274 FileSize, /* MaxProt */ 7,
277 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
278 MCSection *Sec = Layout.getSectionOrder()[i];
279 if (Sec->begin() == Sec->end() || !Layout.getSectionFileSize(Sec))
282 unsigned Align = Sec->getAlignment();
284 VMAddr = alignTo(VMAddr, Align);
285 FileOffset = alignTo(FileOffset, Align);
287 Writer.writeSection(Layout, *Sec, VMAddr, FileOffset, 0, 0, 0);
289 FileOffset += Layout.getSectionAddressSize(Sec);
290 VMAddr += Layout.getSectionAddressSize(Sec);
294 static bool isExecutable(const object::MachOObjectFile &Obj) {
296 return Obj.getHeader64().filetype != MachO::MH_OBJECT;
298 return Obj.getHeader().filetype != MachO::MH_OBJECT;
301 static bool hasLinkEditSegment(const object::MachOObjectFile &Obj) {
302 bool HasLinkEditSegment = false;
303 iterateOnSegments(Obj, [&](const MachO::segment_command_64 &Segment) {
304 if (StringRef("__LINKEDIT") == Segment.segname)
305 HasLinkEditSegment = true;
307 return HasLinkEditSegment;
310 static unsigned segmentLoadCommandSize(bool Is64Bit, unsigned NumSections) {
312 return sizeof(MachO::segment_command_64) +
313 NumSections * sizeof(MachO::section_64);
315 return sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
318 // Stream a dSYM companion binary file corresponding to the binary referenced
319 // by \a DM to \a OutFile. The passed \a MS MCStreamer is setup to write to
320 // \a OutFile and it must be using a MachObjectWriter object to do so.
321 bool generateDsymCompanion(const DebugMap &DM, MCStreamer &MS,
322 raw_fd_ostream &OutFile) {
323 auto &ObjectStreamer = static_cast<MCObjectStreamer &>(MS);
324 MCAssembler &MCAsm = ObjectStreamer.getAssembler();
325 auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter());
326 MCAsmLayout Layout(MCAsm);
328 MCAsm.layout(Layout);
330 BinaryHolder InputBinaryHolder(false);
331 auto ErrOrObjs = InputBinaryHolder.GetObjectFiles(DM.getBinaryPath());
332 if (auto Error = ErrOrObjs.getError())
333 return error(Twine("opening ") + DM.getBinaryPath() + ": " +
335 "output file streaming");
337 auto ErrOrInputBinary =
338 InputBinaryHolder.GetAs<object::MachOObjectFile>(DM.getTriple());
339 if (auto Error = ErrOrInputBinary.getError())
340 return error(Twine("opening ") + DM.getBinaryPath() + ": " +
342 "output file streaming");
343 auto &InputBinary = *ErrOrInputBinary;
345 bool Is64Bit = Writer.is64Bit();
346 MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand();
349 MachO::uuid_command UUIDCmd;
350 memset(&UUIDCmd, 0, sizeof(UUIDCmd));
351 UUIDCmd.cmd = MachO::LC_UUID;
352 UUIDCmd.cmdsize = sizeof(MachO::uuid_command);
353 for (auto &LCI : InputBinary.load_commands()) {
354 if (LCI.C.cmd == MachO::LC_UUID) {
355 UUIDCmd = InputBinary.getUuidCommand(LCI);
360 // Compute the number of load commands we will need.
361 unsigned LoadCommandSize = 0;
362 unsigned NumLoadCommands = 0;
363 // We will copy the UUID if there is one.
364 if (UUIDCmd.cmd != 0) {
366 LoadCommandSize += sizeof(MachO::uuid_command);
369 // If we have a valid symtab to copy, do it.
370 bool ShouldEmitSymtab =
371 isExecutable(InputBinary) && hasLinkEditSegment(InputBinary);
372 if (ShouldEmitSymtab) {
373 LoadCommandSize += sizeof(MachO::symtab_command);
377 unsigned HeaderSize =
378 Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
379 // We will copy every segment that isn't __DWARF.
380 iterateOnSegments(InputBinary, [&](const MachO::segment_command_64 &Segment) {
381 if (StringRef("__DWARF") == Segment.segname)
385 LoadCommandSize += segmentLoadCommandSize(Is64Bit, Segment.nsects);
388 // We will add our own brand new __DWARF segment if we have debug
390 unsigned NumDwarfSections = 0;
391 uint64_t DwarfSegmentSize = 0;
393 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
394 MCSection *Sec = Layout.getSectionOrder()[i];
395 if (Sec->begin() == Sec->end())
398 if (uint64_t Size = Layout.getSectionFileSize(Sec)) {
399 DwarfSegmentSize = alignTo(DwarfSegmentSize, Sec->getAlignment());
400 DwarfSegmentSize += Size;
405 if (NumDwarfSections) {
407 LoadCommandSize += segmentLoadCommandSize(Is64Bit, NumDwarfSections);
410 SmallString<0> NewSymtab;
411 NonRelocatableStringpool NewStrings;
412 unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
413 unsigned NumSyms = 0;
414 uint64_t NewStringsSize = 0;
415 if (ShouldEmitSymtab) {
416 NewSymtab.reserve(SymtabCmd.nsyms * NListSize / 2);
417 NumSyms = transferSymbols(InputBinary, NewSymtab, NewStrings);
418 NewStringsSize = NewStrings.getSize() + 1;
421 uint64_t SymtabStart = LoadCommandSize;
422 SymtabStart += HeaderSize;
423 SymtabStart = alignTo(SymtabStart, 0x1000);
425 // We gathered all the information we need, start emitting the output file.
426 Writer.writeHeader(MachO::MH_DSYM, NumLoadCommands, LoadCommandSize, false);
428 // Write the load commands.
429 assert(OutFile.tell() == HeaderSize);
430 if (UUIDCmd.cmd != 0) {
431 Writer.write32(UUIDCmd.cmd);
432 Writer.write32(UUIDCmd.cmdsize);
434 StringRef(reinterpret_cast<const char *>(UUIDCmd.uuid), 16));
435 assert(OutFile.tell() == HeaderSize + sizeof(UUIDCmd));
438 assert(SymtabCmd.cmd && "No symbol table.");
439 uint64_t StringStart = SymtabStart + NumSyms * NListSize;
440 if (ShouldEmitSymtab)
441 Writer.writeSymtabLoadCommand(SymtabStart, NumSyms, StringStart,
444 uint64_t DwarfSegmentStart = StringStart + NewStringsSize;
445 DwarfSegmentStart = alignTo(DwarfSegmentStart, 0x1000);
447 // Write the load commands for the segments and sections we 'import' from
448 // the original binary.
449 uint64_t EndAddress = 0;
450 uint64_t GapForDwarf = UINT64_MAX;
451 for (auto &LCI : InputBinary.load_commands()) {
452 if (LCI.C.cmd == MachO::LC_SEGMENT)
453 transferSegmentAndSections(LCI, InputBinary.getSegmentLoadCommand(LCI),
454 InputBinary, Writer, SymtabStart,
455 StringStart + NewStringsSize - SymtabStart,
456 DwarfSegmentSize, GapForDwarf, EndAddress);
457 else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
458 transferSegmentAndSections(LCI, InputBinary.getSegment64LoadCommand(LCI),
459 InputBinary, Writer, SymtabStart,
460 StringStart + NewStringsSize - SymtabStart,
461 DwarfSegmentSize, GapForDwarf, EndAddress);
464 uint64_t DwarfVMAddr = alignTo(EndAddress, 0x1000);
465 uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX;
466 if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax ||
467 DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr /* Overflow */) {
468 // There is no room for the __DWARF segment at the end of the
469 // address space. Look through segments to find a gap.
470 DwarfVMAddr = GapForDwarf;
471 if (DwarfVMAddr == UINT64_MAX)
472 warn("not enough VM space for the __DWARF segment.",
473 "output file streaming");
476 // Write the load command for the __DWARF segment.
477 createDwarfSegment(DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize,
478 NumDwarfSections, Layout, Writer);
480 assert(OutFile.tell() == LoadCommandSize + HeaderSize);
481 Writer.WriteZeros(SymtabStart - (LoadCommandSize + HeaderSize));
482 assert(OutFile.tell() == SymtabStart);
485 if (ShouldEmitSymtab) {
486 Writer.writeBytes(NewSymtab.str());
487 assert(OutFile.tell() == StringStart);
489 // Transfer string table.
490 // FIXME: The NonRelocatableStringpool starts with an empty string, but
491 // dsymutil-classic starts the reconstructed string table with 2 of these.
492 // Reproduce that behavior for now (there is corresponding code in
494 Writer.WriteZeros(1);
495 std::vector<DwarfStringPoolEntryRef> Strings = NewStrings.getEntries();
496 for (auto EntryRef : Strings) {
497 if (EntryRef.getIndex() == -1U)
499 StringRef ZeroTerminated(EntryRef.getString().data(),
500 EntryRef.getString().size() + 1);
501 Writer.writeBytes(ZeroTerminated);
505 assert(OutFile.tell() == StringStart + NewStringsSize);
507 // Pad till the Dwarf segment start.
508 Writer.WriteZeros(DwarfSegmentStart - (StringStart + NewStringsSize));
509 assert(OutFile.tell() == DwarfSegmentStart);
511 // Emit the Dwarf sections contents.
512 for (const MCSection &Sec : MCAsm) {
513 if (Sec.begin() == Sec.end())
516 uint64_t Pos = OutFile.tell();
517 Writer.WriteZeros(alignTo(Pos, Sec.getAlignment()) - Pos);
518 MCAsm.writeSectionData(&Sec, Layout);
523 } // namespace MachOUtils
524 } // namespace dsymutil