LLVM  16.0.0git
MachOEmitter.cpp
Go to the documentation of this file.
1 //===- yaml2macho - Convert YAML to a Mach object file --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// The Mach component of yaml2obj.
11 ///
12 //===----------------------------------------------------------------------===//
13 
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/LEB128.h"
23 
24 #include "llvm/Support/Format.h"
25 
26 using namespace llvm;
27 
28 namespace {
29 
30 class MachOWriter {
31 public:
32  MachOWriter(MachOYAML::Object &Obj) : Obj(Obj), fileStart(0) {
35  memset(reinterpret_cast<void *>(&Header), 0, sizeof(MachO::mach_header_64));
36  }
37 
38  Error writeMachO(raw_ostream &OS);
39 
40 private:
41  void writeHeader(raw_ostream &OS);
42  void writeLoadCommands(raw_ostream &OS);
43  Error writeSectionData(raw_ostream &OS);
44  void writeRelocations(raw_ostream &OS);
45  void writeLinkEditData(raw_ostream &OS);
46 
47  void writeBindOpcodes(raw_ostream &OS,
48  std::vector<MachOYAML::BindOpcode> &BindOpcodes);
49  // LinkEdit writers
50  void writeRebaseOpcodes(raw_ostream &OS);
51  void writeBasicBindOpcodes(raw_ostream &OS);
52  void writeWeakBindOpcodes(raw_ostream &OS);
53  void writeLazyBindOpcodes(raw_ostream &OS);
54  void writeNameList(raw_ostream &OS);
55  void writeStringTable(raw_ostream &OS);
56  void writeExportTrie(raw_ostream &OS);
57  void writeDynamicSymbolTable(raw_ostream &OS);
58  void writeFunctionStarts(raw_ostream &OS);
59  void writeChainedFixups(raw_ostream &OS);
60  void writeDyldExportsTrie(raw_ostream &OS);
61  void writeDataInCode(raw_ostream &OS);
62 
63  void dumpExportEntry(raw_ostream &OS, MachOYAML::ExportEntry &Entry);
64  void ZeroToOffset(raw_ostream &OS, size_t offset);
65 
66  MachOYAML::Object &Obj;
67  bool is64Bit;
68  uint64_t fileStart;
69  MachO::mach_header_64 Header;
70 
71  // Old PPC Object Files didn't have __LINKEDIT segments, the data was just
72  // stuck at the end of the file.
73  bool FoundLinkEditSeg = false;
74 };
75 
76 Error MachOWriter::writeMachO(raw_ostream &OS) {
77  fileStart = OS.tell();
78  writeHeader(OS);
79  writeLoadCommands(OS);
80  if (Error Err = writeSectionData(OS))
81  return Err;
82  writeRelocations(OS);
83  if (!FoundLinkEditSeg)
84  writeLinkEditData(OS);
85  return Error::success();
86 }
87 
88 void MachOWriter::writeHeader(raw_ostream &OS) {
89  Header.magic = Obj.Header.magic;
90  Header.cputype = Obj.Header.cputype;
91  Header.cpusubtype = Obj.Header.cpusubtype;
92  Header.filetype = Obj.Header.filetype;
93  Header.ncmds = Obj.Header.ncmds;
94  Header.sizeofcmds = Obj.Header.sizeofcmds;
95  Header.flags = Obj.Header.flags;
96  Header.reserved = Obj.Header.reserved;
97 
99  MachO::swapStruct(Header);
100 
101  auto header_size =
103  OS.write((const char *)&Header, header_size);
104 }
105 
106 template <typename SectionType>
108  SectionType TempSec;
109  memcpy(reinterpret_cast<void *>(&TempSec.sectname[0]), &Sec.sectname[0], 16);
110  memcpy(reinterpret_cast<void *>(&TempSec.segname[0]), &Sec.segname[0], 16);
111  TempSec.addr = Sec.addr;
112  TempSec.size = Sec.size;
113  TempSec.offset = Sec.offset;
114  TempSec.align = Sec.align;
115  TempSec.reloff = Sec.reloff;
116  TempSec.nreloc = Sec.nreloc;
117  TempSec.flags = Sec.flags;
118  TempSec.reserved1 = Sec.reserved1;
119  TempSec.reserved2 = Sec.reserved2;
120  return TempSec;
121 }
122 
123 template <typename StructType>
124 size_t writeLoadCommandData(MachOYAML::LoadCommand &LC, raw_ostream &OS,
125  bool IsLittleEndian) {
126  return 0;
127 }
128 
129 template <>
130 size_t writeLoadCommandData<MachO::segment_command>(MachOYAML::LoadCommand &LC,
131  raw_ostream &OS,
132  bool IsLittleEndian) {
133  size_t BytesWritten = 0;
134  for (const auto &Sec : LC.Sections) {
135  auto TempSec = constructSection<MachO::section>(Sec);
136  if (IsLittleEndian != sys::IsLittleEndianHost)
137  MachO::swapStruct(TempSec);
138  OS.write(reinterpret_cast<const char *>(&(TempSec)),
139  sizeof(MachO::section));
140  BytesWritten += sizeof(MachO::section);
141  }
142  return BytesWritten;
143 }
144 
145 template <>
146 size_t writeLoadCommandData<MachO::segment_command_64>(
147  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
148  size_t BytesWritten = 0;
149  for (const auto &Sec : LC.Sections) {
150  auto TempSec = constructSection<MachO::section_64>(Sec);
151  TempSec.reserved3 = Sec.reserved3;
152  if (IsLittleEndian != sys::IsLittleEndianHost)
153  MachO::swapStruct(TempSec);
154  OS.write(reinterpret_cast<const char *>(&(TempSec)),
155  sizeof(MachO::section_64));
156  BytesWritten += sizeof(MachO::section_64);
157  }
158  return BytesWritten;
159 }
160 
161 size_t writePayloadString(MachOYAML::LoadCommand &LC, raw_ostream &OS) {
162  size_t BytesWritten = 0;
163  if (!LC.Content.empty()) {
164  OS.write(LC.Content.c_str(), LC.Content.length());
165  BytesWritten = LC.Content.length();
166  }
167  return BytesWritten;
168 }
169 
170 template <>
171 size_t writeLoadCommandData<MachO::dylib_command>(MachOYAML::LoadCommand &LC,
172  raw_ostream &OS,
173  bool IsLittleEndian) {
174  return writePayloadString(LC, OS);
175 }
176 
177 template <>
178 size_t writeLoadCommandData<MachO::dylinker_command>(MachOYAML::LoadCommand &LC,
179  raw_ostream &OS,
180  bool IsLittleEndian) {
181  return writePayloadString(LC, OS);
182 }
183 
184 template <>
185 size_t writeLoadCommandData<MachO::rpath_command>(MachOYAML::LoadCommand &LC,
186  raw_ostream &OS,
187  bool IsLittleEndian) {
188  return writePayloadString(LC, OS);
189 }
190 
191 template <>
192 size_t writeLoadCommandData<MachO::sub_framework_command>(
193  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
194  return writePayloadString(LC, OS);
195 }
196 
197 template <>
198 size_t writeLoadCommandData<MachO::sub_umbrella_command>(
199  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
200  return writePayloadString(LC, OS);
201 }
202 
203 template <>
204 size_t writeLoadCommandData<MachO::sub_client_command>(
205  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
206  return writePayloadString(LC, OS);
207 }
208 
209 template <>
210 size_t writeLoadCommandData<MachO::sub_library_command>(
211  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
212  return writePayloadString(LC, OS);
213 }
214 
215 template <>
216 size_t writeLoadCommandData<MachO::build_version_command>(
217  MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) {
218  size_t BytesWritten = 0;
219  for (const auto &T : LC.Tools) {
220  struct MachO::build_tool_version tool = T;
221  if (IsLittleEndian != sys::IsLittleEndianHost)
222  MachO::swapStruct(tool);
223  OS.write(reinterpret_cast<const char *>(&tool),
224  sizeof(MachO::build_tool_version));
225  BytesWritten += sizeof(MachO::build_tool_version);
226  }
227  return BytesWritten;
228 }
229 
230 void ZeroFillBytes(raw_ostream &OS, size_t Size) {
231  std::vector<uint8_t> FillData(Size, 0);
232  OS.write(reinterpret_cast<char *>(FillData.data()), Size);
233 }
234 
235 void Fill(raw_ostream &OS, size_t Size, uint32_t Data) {
236  std::vector<uint32_t> FillData((Size / 4) + 1, Data);
237  OS.write(reinterpret_cast<char *>(FillData.data()), Size);
238 }
239 
240 void MachOWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) {
241  auto currOffset = OS.tell() - fileStart;
242  if (currOffset < Offset)
243  ZeroFillBytes(OS, Offset - currOffset);
244 }
245 
246 void MachOWriter::writeLoadCommands(raw_ostream &OS) {
247  for (auto &LC : Obj.LoadCommands) {
248  size_t BytesWritten = 0;
250 
251 #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \
252  case MachO::LCName: \
253  if (Obj.IsLittleEndian != sys::IsLittleEndianHost) \
254  MachO::swapStruct(Data.LCStruct##_data); \
255  OS.write(reinterpret_cast<const char *>(&(Data.LCStruct##_data)), \
256  sizeof(MachO::LCStruct)); \
257  BytesWritten = sizeof(MachO::LCStruct); \
258  BytesWritten += \
259  writeLoadCommandData<MachO::LCStruct>(LC, OS, Obj.IsLittleEndian); \
260  break;
261 
262  switch (LC.Data.load_command_data.cmd) {
263  default:
265  MachO::swapStruct(Data.load_command_data);
266  OS.write(reinterpret_cast<const char *>(&(Data.load_command_data)),
267  sizeof(MachO::load_command));
268  BytesWritten = sizeof(MachO::load_command);
269  BytesWritten +=
270  writeLoadCommandData<MachO::load_command>(LC, OS, Obj.IsLittleEndian);
271  break;
272 #include "llvm/BinaryFormat/MachO.def"
273  }
274 
275  if (LC.PayloadBytes.size() > 0) {
276  OS.write(reinterpret_cast<const char *>(LC.PayloadBytes.data()),
277  LC.PayloadBytes.size());
278  BytesWritten += LC.PayloadBytes.size();
279  }
280 
281  if (LC.ZeroPadBytes > 0) {
282  ZeroFillBytes(OS, LC.ZeroPadBytes);
283  BytesWritten += LC.ZeroPadBytes;
284  }
285 
286  // Fill remaining bytes with 0. This will only get hit in partially
287  // specified test cases.
288  auto BytesRemaining = LC.Data.load_command_data.cmdsize - BytesWritten;
289  if (BytesRemaining > 0) {
290  ZeroFillBytes(OS, BytesRemaining);
291  }
292  }
293 }
294 
295 Error MachOWriter::writeSectionData(raw_ostream &OS) {
296  uint64_t LinkEditOff = 0;
297  for (auto &LC : Obj.LoadCommands) {
298  switch (LC.Data.load_command_data.cmd) {
299  case MachO::LC_SEGMENT:
300  case MachO::LC_SEGMENT_64:
301  uint64_t segOff = is64Bit ? LC.Data.segment_command_64_data.fileoff
302  : LC.Data.segment_command_data.fileoff;
303  if (0 ==
304  strncmp(&LC.Data.segment_command_data.segname[0], "__LINKEDIT", 16)) {
305  FoundLinkEditSeg = true;
306  LinkEditOff = segOff;
307  if (Obj.RawLinkEditSegment)
308  continue;
309  writeLinkEditData(OS);
310  }
311  for (auto &Sec : LC.Sections) {
312  ZeroToOffset(OS, Sec.offset);
313  // Zero Fill any data between the end of the last thing we wrote and the
314  // start of this section.
315  if (OS.tell() - fileStart > Sec.offset && Sec.offset != (uint32_t)0)
316  return createStringError(
318  "wrote too much data somewhere, section offsets don't line up");
319 
320  StringRef SectName(Sec.sectname,
321  strnlen(Sec.sectname, sizeof(Sec.sectname)));
322  // If the section's content is specified in the 'DWARF' entry, we will
323  // emit it regardless of the section's segname.
324  if (Obj.DWARF.getNonEmptySectionNames().count(SectName.substr(2))) {
325  if (Sec.content)
327  "cannot specify section '" + SectName +
328  "' contents in the 'DWARF' entry and "
329  "the 'content' at the same time");
330  auto EmitFunc = DWARFYAML::getDWARFEmitterByName(SectName.substr(2));
331  if (Error Err = EmitFunc(OS, Obj.DWARF))
332  return Err;
333  continue;
334  }
335 
336  // Skip if it's a virtual section.
338  continue;
339 
340  if (Sec.content) {
342  Content.writeAsBinary(OS);
343  ZeroFillBytes(OS, Sec.size - Content.binary_size());
344  } else {
345  // Fill section data with 0xDEADBEEF.
346  Fill(OS, Sec.size, 0xDEADBEEFu);
347  }
348  }
349  uint64_t segSize = is64Bit ? LC.Data.segment_command_64_data.filesize
350  : LC.Data.segment_command_data.filesize;
351  ZeroToOffset(OS, segOff + segSize);
352  break;
353  }
354  }
355 
356  if (Obj.RawLinkEditSegment) {
357  ZeroToOffset(OS, LinkEditOff);
358  if (OS.tell() - fileStart > LinkEditOff || !LinkEditOff)
360  "section offsets don't line up");
362  }
363  return Error::success();
364 }
365 
366 // The implementation of makeRelocationInfo and makeScatteredRelocationInfo is
367 // consistent with how libObject parses MachO binary files. For the reference
368 // see getStruct, getRelocation, getPlainRelocationPCRel,
369 // getPlainRelocationLength and related methods in MachOObjectFile.cpp
371 makeRelocationInfo(const MachOYAML::Relocation &R, bool IsLE) {
372  assert(!R.is_scattered && "non-scattered relocation expected");
374  MRE.r_word0 = R.address;
375  if (IsLE)
376  MRE.r_word1 = ((unsigned)R.symbolnum << 0) | ((unsigned)R.is_pcrel << 24) |
377  ((unsigned)R.length << 25) | ((unsigned)R.is_extern << 27) |
378  ((unsigned)R.type << 28);
379  else
380  MRE.r_word1 = ((unsigned)R.symbolnum << 8) | ((unsigned)R.is_pcrel << 7) |
381  ((unsigned)R.length << 5) | ((unsigned)R.is_extern << 4) |
382  ((unsigned)R.type << 0);
383  return MRE;
384 }
385 
387 makeScatteredRelocationInfo(const MachOYAML::Relocation &R) {
388  assert(R.is_scattered && "scattered relocation expected");
390  MRE.r_word0 = (((unsigned)R.address << 0) | ((unsigned)R.type << 24) |
391  ((unsigned)R.length << 28) | ((unsigned)R.is_pcrel << 30) |
393  MRE.r_word1 = R.value;
394  return MRE;
395 }
396 
397 void MachOWriter::writeRelocations(raw_ostream &OS) {
398  for (const MachOYAML::LoadCommand &LC : Obj.LoadCommands) {
399  switch (LC.Data.load_command_data.cmd) {
400  case MachO::LC_SEGMENT:
401  case MachO::LC_SEGMENT_64:
402  for (const MachOYAML::Section &Sec : LC.Sections) {
403  if (Sec.relocations.empty())
404  continue;
405  ZeroToOffset(OS, Sec.reloff);
406  for (const MachOYAML::Relocation &R : Sec.relocations) {
408  R.is_scattered ? makeScatteredRelocationInfo(R)
409  : makeRelocationInfo(R, Obj.IsLittleEndian);
411  MachO::swapStruct(MRE);
412  OS.write(reinterpret_cast<const char *>(&MRE),
414  }
415  }
416  }
417  }
418 }
419 
420 void MachOWriter::writeBindOpcodes(
421  raw_ostream &OS, std::vector<MachOYAML::BindOpcode> &BindOpcodes) {
422 
423  for (auto Opcode : BindOpcodes) {
424  uint8_t OpByte = Opcode.Opcode | Opcode.Imm;
425  OS.write(reinterpret_cast<char *>(&OpByte), 1);
426  for (auto Data : Opcode.ULEBExtraData) {
427  encodeULEB128(Data, OS);
428  }
429  for (auto Data : Opcode.SLEBExtraData) {
430  encodeSLEB128(Data, OS);
431  }
432  if (!Opcode.Symbol.empty()) {
433  OS.write(Opcode.Symbol.data(), Opcode.Symbol.size());
434  OS.write('\0');
435  }
436  }
437 }
438 
439 void MachOWriter::dumpExportEntry(raw_ostream &OS,
440  MachOYAML::ExportEntry &Entry) {
441  encodeULEB128(Entry.TerminalSize, OS);
442  if (Entry.TerminalSize > 0) {
443  encodeULEB128(Entry.Flags, OS);
444  if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
445  encodeULEB128(Entry.Other, OS);
446  OS << Entry.ImportName;
447  OS.write('\0');
448  } else {
449  encodeULEB128(Entry.Address, OS);
451  encodeULEB128(Entry.Other, OS);
452  }
453  }
454  OS.write(static_cast<uint8_t>(Entry.Children.size()));
455  for (auto EE : Entry.Children) {
456  OS << EE.Name;
457  OS.write('\0');
458  encodeULEB128(EE.NodeOffset, OS);
459  }
460  for (auto EE : Entry.Children)
461  dumpExportEntry(OS, EE);
462 }
463 
464 void MachOWriter::writeExportTrie(raw_ostream &OS) {
465  dumpExportEntry(OS, Obj.LinkEdit.ExportTrie);
466 }
467 
468 template <typename NListType>
470  bool IsLittleEndian) {
471  NListType ListEntry;
472  ListEntry.n_strx = NLE.n_strx;
473  ListEntry.n_type = NLE.n_type;
474  ListEntry.n_sect = NLE.n_sect;
475  ListEntry.n_desc = NLE.n_desc;
476  ListEntry.n_value = NLE.n_value;
477 
478  if (IsLittleEndian != sys::IsLittleEndianHost)
479  MachO::swapStruct(ListEntry);
480  OS.write(reinterpret_cast<const char *>(&ListEntry), sizeof(NListType));
481 }
482 
483 void MachOWriter::writeLinkEditData(raw_ostream &OS) {
484  typedef void (MachOWriter::*writeHandler)(raw_ostream &);
485  typedef std::pair<uint64_t, writeHandler> writeOperation;
486  std::vector<writeOperation> WriteQueue;
487 
488  MachO::dyld_info_command *DyldInfoOnlyCmd = nullptr;
489  MachO::symtab_command *SymtabCmd = nullptr;
490  MachO::dysymtab_command *DSymtabCmd = nullptr;
491  MachO::linkedit_data_command *FunctionStartsCmd = nullptr;
492  MachO::linkedit_data_command *ChainedFixupsCmd = nullptr;
493  MachO::linkedit_data_command *DyldExportsTrieCmd = nullptr;
494  MachO::linkedit_data_command *DataInCodeCmd = nullptr;
495  for (auto &LC : Obj.LoadCommands) {
496  switch (LC.Data.load_command_data.cmd) {
497  case MachO::LC_SYMTAB:
498  SymtabCmd = &LC.Data.symtab_command_data;
499  WriteQueue.push_back(
500  std::make_pair(SymtabCmd->symoff, &MachOWriter::writeNameList));
501  WriteQueue.push_back(
502  std::make_pair(SymtabCmd->stroff, &MachOWriter::writeStringTable));
503  break;
504  case MachO::LC_DYLD_INFO_ONLY:
505  DyldInfoOnlyCmd = &LC.Data.dyld_info_command_data;
506  WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->rebase_off,
507  &MachOWriter::writeRebaseOpcodes));
508  WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->bind_off,
509  &MachOWriter::writeBasicBindOpcodes));
510  WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->weak_bind_off,
511  &MachOWriter::writeWeakBindOpcodes));
512  WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->lazy_bind_off,
513  &MachOWriter::writeLazyBindOpcodes));
514  WriteQueue.push_back(std::make_pair(DyldInfoOnlyCmd->export_off,
515  &MachOWriter::writeExportTrie));
516  break;
517  case MachO::LC_DYSYMTAB:
518  DSymtabCmd = &LC.Data.dysymtab_command_data;
519  WriteQueue.push_back(std::make_pair(
520  DSymtabCmd->indirectsymoff, &MachOWriter::writeDynamicSymbolTable));
521  break;
522  case MachO::LC_FUNCTION_STARTS:
523  FunctionStartsCmd = &LC.Data.linkedit_data_command_data;
524  WriteQueue.push_back(std::make_pair(FunctionStartsCmd->dataoff,
525  &MachOWriter::writeFunctionStarts));
526  break;
527  case MachO::LC_DYLD_CHAINED_FIXUPS:
528  ChainedFixupsCmd = &LC.Data.linkedit_data_command_data;
529  WriteQueue.push_back(std::make_pair(ChainedFixupsCmd->dataoff,
530  &MachOWriter::writeChainedFixups));
531  break;
532  case MachO::LC_DYLD_EXPORTS_TRIE:
533  DyldExportsTrieCmd = &LC.Data.linkedit_data_command_data;
534  WriteQueue.push_back(std::make_pair(DyldExportsTrieCmd->dataoff,
535  &MachOWriter::writeDyldExportsTrie));
536  break;
537  case MachO::LC_DATA_IN_CODE:
538  DataInCodeCmd = &LC.Data.linkedit_data_command_data;
539  WriteQueue.push_back(std::make_pair(DataInCodeCmd->dataoff,
540  &MachOWriter::writeDataInCode));
541  break;
542  }
543  }
544 
545  llvm::sort(WriteQueue, llvm::less_first());
546 
547  for (auto writeOp : WriteQueue) {
548  ZeroToOffset(OS, writeOp.first);
549  (this->*writeOp.second)(OS);
550  }
551 }
552 
553 void MachOWriter::writeRebaseOpcodes(raw_ostream &OS) {
554  MachOYAML::LinkEditData &LinkEdit = Obj.LinkEdit;
555 
556  for (auto Opcode : LinkEdit.RebaseOpcodes) {
557  uint8_t OpByte = Opcode.Opcode | Opcode.Imm;
558  OS.write(reinterpret_cast<char *>(&OpByte), 1);
559  for (auto Data : Opcode.ExtraData)
560  encodeULEB128(Data, OS);
561  }
562 }
563 
564 void MachOWriter::writeBasicBindOpcodes(raw_ostream &OS) {
565  writeBindOpcodes(OS, Obj.LinkEdit.BindOpcodes);
566 }
567 
568 void MachOWriter::writeWeakBindOpcodes(raw_ostream &OS) {
569  writeBindOpcodes(OS, Obj.LinkEdit.WeakBindOpcodes);
570 }
571 
572 void MachOWriter::writeLazyBindOpcodes(raw_ostream &OS) {
573  writeBindOpcodes(OS, Obj.LinkEdit.LazyBindOpcodes);
574 }
575 
576 void MachOWriter::writeNameList(raw_ostream &OS) {
577  for (auto NLE : Obj.LinkEdit.NameList) {
578  if (is64Bit)
579  writeNListEntry<MachO::nlist_64>(NLE, OS, Obj.IsLittleEndian);
580  else
581  writeNListEntry<MachO::nlist>(NLE, OS, Obj.IsLittleEndian);
582  }
583 }
584 
586  for (auto Str : Obj.LinkEdit.StringTable) {
587  OS.write(Str.data(), Str.size());
588  OS.write('\0');
589  }
590 }
591 
592 void MachOWriter::writeDynamicSymbolTable(raw_ostream &OS) {
593  for (auto Data : Obj.LinkEdit.IndirectSymbols)
594  OS.write(reinterpret_cast<const char *>(&Data),
595  sizeof(yaml::Hex32::BaseType));
596 }
597 
598 void MachOWriter::writeFunctionStarts(raw_ostream &OS) {
599  uint64_t Addr = 0;
600  for (uint64_t NextAddr : Obj.LinkEdit.FunctionStarts) {
601  uint64_t Delta = NextAddr - Addr;
602  encodeULEB128(Delta, OS);
603  Addr = NextAddr;
604  }
605 
606  OS.write('\0');
607 }
608 
609 void MachOWriter::writeDataInCode(raw_ostream &OS) {
610  for (const auto &Entry : Obj.LinkEdit.DataInCode) {
611  MachO::data_in_code_entry DICE{Entry.Offset, Entry.Length, Entry.Kind};
613  MachO::swapStruct(DICE);
614  OS.write(reinterpret_cast<const char *>(&DICE),
615  sizeof(MachO::data_in_code_entry));
616  }
617 }
618 
619 void MachOWriter::writeChainedFixups(raw_ostream &OS) {
620  if (Obj.LinkEdit.ChainedFixups.size() > 0)
621  OS.write(reinterpret_cast<const char *>(Obj.LinkEdit.ChainedFixups.data()),
622  Obj.LinkEdit.ChainedFixups.size());
623 }
624 
625 void MachOWriter::writeDyldExportsTrie(raw_ostream &OS) {
626  dumpExportEntry(OS, Obj.LinkEdit.ExportTrie);
627 }
628 
629 class UniversalWriter {
630 public:
631  UniversalWriter(yaml::YamlObjectFile &ObjectFile)
632  : ObjectFile(ObjectFile), fileStart(0) {}
633 
634  Error writeMachO(raw_ostream &OS);
635 
636 private:
637  void writeFatHeader(raw_ostream &OS);
638  void writeFatArchs(raw_ostream &OS);
639 
640  void ZeroToOffset(raw_ostream &OS, size_t offset);
641 
643  uint64_t fileStart;
644 };
645 
646 Error UniversalWriter::writeMachO(raw_ostream &OS) {
647  fileStart = OS.tell();
648  if (ObjectFile.MachO) {
649  MachOWriter Writer(*ObjectFile.MachO);
650  return Writer.writeMachO(OS);
651  }
652 
653  writeFatHeader(OS);
654  writeFatArchs(OS);
655 
656  auto &FatFile = *ObjectFile.FatMachO;
657  if (FatFile.FatArchs.size() < FatFile.Slices.size())
658  return createStringError(
660  "cannot write 'Slices' if not described in 'FatArches'");
661 
662  for (size_t i = 0; i < FatFile.Slices.size(); i++) {
663  ZeroToOffset(OS, FatFile.FatArchs[i].offset);
664  MachOWriter Writer(FatFile.Slices[i]);
665  if (Error Err = Writer.writeMachO(OS))
666  return Err;
667 
668  auto SliceEnd = FatFile.FatArchs[i].offset + FatFile.FatArchs[i].size;
669  ZeroToOffset(OS, SliceEnd);
670  }
671 
672  return Error::success();
673 }
674 
675 void UniversalWriter::writeFatHeader(raw_ostream &OS) {
676  auto &FatFile = *ObjectFile.FatMachO;
677  MachO::fat_header header;
678  header.magic = FatFile.Header.magic;
679  header.nfat_arch = FatFile.Header.nfat_arch;
681  swapStruct(header);
682  OS.write(reinterpret_cast<const char *>(&header), sizeof(MachO::fat_header));
683 }
684 
685 template <typename FatArchType>
686 FatArchType constructFatArch(MachOYAML::FatArch &Arch) {
687  FatArchType FatArch;
688  FatArch.cputype = Arch.cputype;
689  FatArch.cpusubtype = Arch.cpusubtype;
690  FatArch.offset = Arch.offset;
691  FatArch.size = Arch.size;
692  FatArch.align = Arch.align;
693  return FatArch;
694 }
695 
696 template <typename StructType>
697 void writeFatArch(MachOYAML::FatArch &LC, raw_ostream &OS) {}
698 
699 template <>
700 void writeFatArch<MachO::fat_arch>(MachOYAML::FatArch &Arch, raw_ostream &OS) {
701  auto FatArch = constructFatArch<MachO::fat_arch>(Arch);
703  swapStruct(FatArch);
704  OS.write(reinterpret_cast<const char *>(&FatArch), sizeof(MachO::fat_arch));
705 }
706 
707 template <>
708 void writeFatArch<MachO::fat_arch_64>(MachOYAML::FatArch &Arch,
709  raw_ostream &OS) {
710  auto FatArch = constructFatArch<MachO::fat_arch_64>(Arch);
711  FatArch.reserved = Arch.reserved;
713  swapStruct(FatArch);
714  OS.write(reinterpret_cast<const char *>(&FatArch),
715  sizeof(MachO::fat_arch_64));
716 }
717 
718 void UniversalWriter::writeFatArchs(raw_ostream &OS) {
719  auto &FatFile = *ObjectFile.FatMachO;
720  bool is64Bit = FatFile.Header.magic == MachO::FAT_MAGIC_64;
721  for (auto Arch : FatFile.FatArchs) {
722  if (is64Bit)
723  writeFatArch<MachO::fat_arch_64>(Arch, OS);
724  else
725  writeFatArch<MachO::fat_arch>(Arch, OS);
726  }
727 }
728 
729 void UniversalWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) {
730  auto currOffset = OS.tell() - fileStart;
731  if (currOffset < Offset)
732  ZeroFillBytes(OS, Offset - currOffset);
733 }
734 
735 } // end anonymous namespace
736 
737 namespace llvm {
738 namespace yaml {
739 
741  UniversalWriter Writer(Doc);
742  if (Error Err = Writer.writeMachO(Out)) {
744  [&](const ErrorInfoBase &Err) { EH(Err.message()); });
745  return false;
746  }
747  return true;
748 }
749 
750 } // namespace yaml
751 } // namespace llvm
llvm::MachOYAML::ExportEntry
Definition: MachOYAML.h:105
llvm::MachOYAML::FatArch::offset
llvm::yaml::Hex64 offset
Definition: MachOYAML.h:156
i
i
Definition: README.txt:29
llvm::raw_ostream::tell
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:135
llvm::MachOYAML::LoadCommand::Sections
std::vector< Section > Sections
Definition: MachOYAML.h:76
llvm::errc::invalid_argument
@ invalid_argument
llvm::MachO::section
Definition: MachO.h:570
llvm::MachOYAML::NListEntry::n_desc
uint16_t n_desc
Definition: MachOYAML.h:87
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ObjectYAML.h
llvm::MachO::any_relocation_info
Definition: MachO.h:996
llvm::MachOYAML::Object
Definition: MachOYAML.h:138
llvm::MachOYAML::Section
Definition: MachOYAML.h:44
llvm::MachOYAML::Section::segname
char segname[16]
Definition: MachOYAML.h:46
llvm::MachO::fat_header::nfat_arch
uint32_t nfat_arch
Definition: MachO.h:957
llvm::MachOYAML::LinkEditData::DataInCode
std::vector< DataInCodeEntry > DataInCode
Definition: MachOYAML.h:132
T
is64Bit
static bool is64Bit(const char *name)
Definition: X86Disassembler.cpp:1018
llvm::MachOYAML::LinkEditData::ExportTrie
MachOYAML::ExportEntry ExportTrie
Definition: MachOYAML.h:127
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:329
llvm::MachOYAML::LoadCommand::ZeroPadBytes
uint64_t ZeroPadBytes
Definition: MachOYAML.h:80
llvm::MachO::dysymtab_command::indirectsymoff
uint32_t indirectsymoff
Definition: MachO.h:724
Content
T Content
Definition: ELFObjHandler.cpp:89
Error.h
llvm::MachOYAML::Section::nreloc
uint32_t nreloc
Definition: MachOYAML.h:52
llvm::yaml::YamlObjectFile
Definition: ObjectYAML.h:29
llvm::MachO::FAT_MAGIC_64
@ FAT_MAGIC_64
Definition: MachO.h:36
Errc.h
llvm::MachO::symtab_command
Definition: MachO.h:700
llvm::MachOYAML::LinkEditData::LazyBindOpcodes
std::vector< MachOYAML::BindOpcode > LazyBindOpcodes
Definition: MachOYAML.h:126
llvm::MachOYAML::NListEntry
Definition: MachOYAML.h:83
llvm::MachOYAML::LoadCommand::PayloadBytes
std::vector< llvm::yaml::Hex8 > PayloadBytes
Definition: MachOYAML.h:78
llvm::MachO::isVirtualSection
bool isVirtualSection(uint8_t type)
Definition: MachO.h:599
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::MachO::dyld_info_command::export_off
uint32_t export_off
Definition: MachO.h:889
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:80
llvm::MachOYAML::Object::DWARF
DWARFYAML::Data DWARF
Definition: MachOYAML.h:145
llvm::MachOYAML::Section::addr
llvm::yaml::Hex64 addr
Definition: MachOYAML.h:47
llvm::MachOYAML::LinkEditData::FunctionStarts
std::vector< yaml::Hex64 > FunctionStarts
Definition: MachOYAML.h:131
llvm::MachO::SECTION_TYPE
@ SECTION_TYPE
Definition: MachO.h:114
Format.h
llvm::MachOYAML::LinkEditData::RebaseOpcodes
std::vector< MachOYAML::RebaseOpcode > RebaseOpcodes
Definition: MachOYAML.h:123
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:265
llvm::MachOYAML::LoadCommand::Content
std::string Content
Definition: MachOYAML.h:79
llvm::MachOYAML::FileHeader::sizeofcmds
uint32_t sizeofcmds
Definition: MachOYAML.h:67
llvm::MachO::dyld_info_command
Definition: MachO.h:878
llvm::MachOYAML::LinkEditData::IndirectSymbols
std::vector< yaml::Hex32 > IndirectSymbols
Definition: MachOYAML.h:130
llvm::MachOYAML::Section::size
uint64_t size
Definition: MachOYAML.h:48
llvm::MachO::data_in_code_entry
Definition: MachO.h:812
llvm::yaml::yaml2macho
bool yaml2macho(YamlObjectFile &Doc, raw_ostream &Out, ErrorHandler EH)
Definition: MachOEmitter.cpp:740
llvm::MachO::fat_arch
Definition: MachO.h:960
llvm::MachOYAML::Section::sectname
char sectname[16]
Definition: MachOYAML.h:45
llvm::MachO::any_relocation_info::r_word1
uint32_t r_word1
Definition: MachO.h:997
llvm::encodeSLEB128
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
llvm::less_first
Function object to check whether the first component of a std::pair compares less than the first comp...
Definition: STLExtras.h:1476
llvm::MachOYAML::FatArch::align
uint32_t align
Definition: MachOYAML.h:158
llvm::MachOYAML::NListEntry::n_value
uint64_t n_value
Definition: MachOYAML.h:88
llvm::MachOYAML::FatArch::cputype
llvm::yaml::Hex32 cputype
Definition: MachOYAML.h:154
llvm::MachO::fat_header::magic
uint32_t magic
Definition: MachO.h:956
llvm::MachO::linkedit_data_command
Definition: MachO.h:805
llvm::raw_ostream::write
raw_ostream & write(unsigned char C)
Definition: raw_ostream.cpp:218
llvm::MachOYAML::FileHeader::filetype
llvm::yaml::Hex32 filetype
Definition: MachOYAML.h:65
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::object::writeStringTable
static void writeStringTable(std::vector< uint8_t > &B, ArrayRef< const std::string > Strings)
Definition: COFFImportFile.cpp:72
llvm::MachOYAML::LoadCommand::Data
llvm::MachO::macho_load_command Data
Definition: MachOYAML.h:75
llvm::MachOYAML::Section::relocations
std::vector< Relocation > relocations
Definition: MachOYAML.h:58
ZeroFillBytes
static void ZeroFillBytes(raw_ostream &OS, size_t Size)
Definition: DWARFEmitter.cpp:65
llvm::ErrorInfoBase
Base class for error info classes.
Definition: Error.h:46
llvm::MachOYAML::LoadCommand
Definition: MachOYAML.h:72
llvm::MachOYAML::Object::LinkEdit
LinkEditData LinkEdit
Definition: MachOYAML.h:143
llvm::MachOYAML::LinkEditData::NameList
std::vector< NListEntry > NameList
Definition: MachOYAML.h:128
llvm::MachOYAML::Object::LoadCommands
std::vector< LoadCommand > LoadCommands
Definition: MachOYAML.h:141
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1682
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLFunctionalExtras.h:36
llvm::MachO::mach_header_64
Definition: MachO.h:526
llvm::DWARFYAML::Data::getNonEmptySectionNames
SetVector< StringRef > getNonEmptySectionNames() const
Definition: DWARFYAML.cpp:25
constructSection
Section constructSection(const MachO::section &Sec, uint32_t Index)
Definition: MachOReader.cpp:49
llvm::MachOYAML::FatArch::cpusubtype
llvm::yaml::Hex32 cpusubtype
Definition: MachOYAML.h:155
llvm::MachOYAML::FileHeader::reserved
llvm::yaml::Hex32 reserved
Definition: MachOYAML.h:69
BaseType
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
Definition: SafepointIRVerifier.cpp:314
uint64_t
llvm::MachOYAML::Section::offset
llvm::yaml::Hex32 offset
Definition: MachOYAML.h:49
llvm::MachO::R_SCATTERED
@ R_SCATTERED
Definition: MachO.h:401
Addr
uint64_t Addr
Definition: ELFObjHandler.cpp:79
llvm::DWARFYAML::getDWARFEmitterByName
std::function< Error(raw_ostream &, const Data &)> getDWARFEmitterByName(StringRef SecName)
Definition: DWARFEmitter.h:47
llvm::MachOYAML::FileHeader::flags
llvm::yaml::Hex32 flags
Definition: MachOYAML.h:68
llvm::yaml::BinaryRef::writeAsBinary
void writeAsBinary(raw_ostream &OS, uint64_t N=UINT64_MAX) const
Write the contents (regardless of whether it is binary or a hex string) as binary to the given raw_os...
Definition: YAML.cpp:39
llvm::MachO::build_tool_version
Definition: MachO.h:857
llvm::MachO::any_relocation_info::r_word0
uint32_t r_word0
Definition: MachO.h:997
LEB128.h
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::MachOYAML::NListEntry::n_sect
uint8_t n_sect
Definition: MachOYAML.h:86
llvm::MachO::dyld_info_command::lazy_bind_off
uint32_t lazy_bind_off
Definition: MachO.h:887
llvm::MachOYAML::FatArch::size
uint64_t size
Definition: MachOYAML.h:157
llvm::MachOYAML::LinkEditData::ChainedFixups
std::vector< yaml::Hex8 > ChainedFixups
Definition: MachOYAML.h:133
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MachOYAML::NListEntry::n_type
llvm::yaml::Hex8 n_type
Definition: MachOYAML.h:85
memcpy
<%struct.s * > cast struct s *S to sbyte *< sbyte * > sbyte uint cast struct s *agg result to sbyte *< sbyte * > sbyte uint cast struct s *memtmp to sbyte *< sbyte * > sbyte uint ret void llc ends up issuing two memcpy or custom lower memcpy(of small size) to be ldmia/stmia. I think option 2 is better but the current register allocator cannot allocate a chunk of registers at a time. A feasible temporary solution is to use specific physical registers at the lowering time for small(<
llvm::codeview::CodeViewContainer::ObjectFile
@ ObjectFile
llvm::MachOYAML::Object::IsLittleEndian
bool IsLittleEndian
Definition: MachOYAML.h:139
llvm::MachOYAML::Section::content
Optional< llvm::yaml::BinaryRef > content
Definition: MachOYAML.h:57
llvm::MachOYAML::NListEntry::n_strx
uint32_t n_strx
Definition: MachOYAML.h:84
YAMLTraits.h
llvm::MachOYAML::LinkEditData
Definition: MachOYAML.h:122
llvm::MachO::load_command
Definition: MachO.h:537
yaml2obj.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
llvm::yaml::BinaryRef
Specialized YAMLIO scalar type for representing a binary blob.
Definition: YAML.h:63
llvm::MachOYAML::FileHeader::cputype
llvm::yaml::Hex32 cputype
Definition: MachOYAML.h:63
uint32_t
llvm::MachOYAML::LinkEditData::WeakBindOpcodes
std::vector< MachOYAML::BindOpcode > WeakBindOpcodes
Definition: MachOYAML.h:125
llvm::MachOYAML::FileHeader::magic
llvm::yaml::Hex32 magic
Definition: MachOYAML.h:62
llvm::MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
@ EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER
Definition: MachO.h:295
llvm::MachO::NListType
NListType
Definition: MachO.h:313
llvm::MachO::dyld_info_command::weak_bind_off
uint32_t weak_bind_off
Definition: MachO.h:885
llvm::MachOYAML::Object::Header
FileHeader Header
Definition: MachOYAML.h:140
llvm::MachOYAML::LinkEditData::BindOpcodes
std::vector< MachOYAML::BindOpcode > BindOpcodes
Definition: MachOYAML.h:124
DWARFEmitter.h
llvm::MachO::dysymtab_command
Definition: MachO.h:709
llvm::MachOYAML::LoadCommand::Tools
std::vector< MachO::build_tool_version > Tools
Definition: MachOYAML.h:77
llvm::MachO::EXPORT_SYMBOL_FLAGS_REEXPORT
@ EXPORT_SYMBOL_FLAGS_REEXPORT
Definition: MachO.h:294
llvm::MachO::section_64
Definition: MachO.h:584
llvm::MachOYAML::FileHeader::cpusubtype
llvm::yaml::Hex32 cpusubtype
Definition: MachOYAML.h:64
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1238
llvm::MachOYAML::Section::reserved3
llvm::yaml::Hex32 reserved3
Definition: MachOYAML.h:56
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::MachO::symtab_command::stroff
uint32_t stroff
Definition: MachO.h:705
llvm::MachOYAML::Object::RawLinkEditSegment
Optional< llvm::yaml::BinaryRef > RawLinkEditSegment
Definition: MachOYAML.h:144
llvm::MachOYAML::FatArch
Definition: MachOYAML.h:153
llvm::MachO::mach_header
Definition: MachO.h:516
llvm::MachOYAML::FatArch::reserved
llvm::yaml::Hex32 reserved
Definition: MachOYAML.h:159
llvm::MachOYAML::Section::reserved1
llvm::yaml::Hex32 reserved1
Definition: MachOYAML.h:54
llvm::sys::IsLittleEndianHost
static const bool IsLittleEndianHost
Definition: SwapByteOrder.h:101
writeNListEntry
void writeNListEntry(const SymbolEntry &SE, bool IsLittleEndian, char *&Out, uint32_t Nstrx)
Definition: MachOWriter.cpp:272
llvm::MachOYAML::LinkEditData::StringTable
std::vector< StringRef > StringTable
Definition: MachOYAML.h:129
llvm::MachOYAML::Section::reserved2
llvm::yaml::Hex32 reserved2
Definition: MachOYAML.h:55
llvm::encodeULEB128
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
llvm::MachOYAML::FileHeader::ncmds
uint32_t ncmds
Definition: MachOYAML.h:66
llvm::MachO::fat_arch_64
Definition: MachO.h:968
llvm::MachO::symtab_command::symoff
uint32_t symoff
Definition: MachO.h:703
llvm::MachO::dyld_info_command::bind_off
uint32_t bind_off
Definition: MachO.h:883
llvm::MachO::dyld_info_command::rebase_off
uint32_t rebase_off
Definition: MachO.h:881
MachO.h
llvm::MachO::MH_CIGAM_64
@ MH_CIGAM_64
Definition: MachO.h:33
llvm::MachO::MH_MAGIC_64
@ MH_MAGIC_64
Definition: MachO.h:32
InlinePriorityMode::Size
@ Size
raw_ostream.h
llvm::MachO::linkedit_data_command::dataoff
uint32_t dataoff
Definition: MachO.h:808
llvm::MachO::swapStruct
void swapStruct(fat_header &mh)
Definition: MachO.h:1139
llvm::MachOYAML::Section::reloff
llvm::yaml::Hex32 reloff
Definition: MachOYAML.h:51
llvm::MachOYAML::Section::flags
llvm::yaml::Hex32 flags
Definition: MachOYAML.h:53
llvm::MachO::fat_header
Definition: MachO.h:955
llvm::handleAllErrors
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:965
llvm::MachOYAML::Relocation
Definition: MachOYAML.h:30
llvm::MachO::SectionType
SectionType
These are the section type and attributes fields.
Definition: MachO.h:122
llvm::MachOYAML::Section::align
uint32_t align
Definition: MachOYAML.h:50
llvm::MachO::macho_load_command
Definition: MachO.h:2147