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 | |
14 | #include "llvm/BinaryFormat/MachO.h" |
15 | #include "llvm/ObjectYAML/DWARFEmitter.h" |
16 | #include "llvm/ObjectYAML/ObjectYAML.h" |
17 | #include "llvm/ObjectYAML/yaml2obj.h" |
18 | #include "llvm/Support/Errc.h" |
19 | #include "llvm/Support/Error.h" |
20 | #include "llvm/Support/FormatVariadic.h" |
21 | #include "llvm/Support/LEB128.h" |
22 | #include "llvm/Support/SystemZ/zOSSupport.h" |
23 | #include "llvm/Support/YAMLTraits.h" |
24 | #include "llvm/Support/raw_ostream.h" |
25 | |
26 | #include "llvm/Support/Format.h" |
27 | |
28 | using namespace llvm; |
29 | |
30 | namespace { |
31 | |
32 | class MachOWriter { |
33 | public: |
34 | MachOWriter(MachOYAML::Object &Obj) : Obj(Obj), fileStart(0) { |
35 | is64Bit = Obj.Header.magic == MachO::MH_MAGIC_64 || |
36 | Obj.Header.magic == MachO::MH_CIGAM_64; |
37 | memset(s: reinterpret_cast<void *>(&Header), c: 0, n: sizeof(MachO::mach_header_64)); |
38 | } |
39 | |
40 | Error writeMachO(raw_ostream &OS); |
41 | |
42 | private: |
43 | void writeHeader(raw_ostream &OS); |
44 | void writeLoadCommands(raw_ostream &OS); |
45 | Error writeSectionData(raw_ostream &OS); |
46 | void writeRelocations(raw_ostream &OS); |
47 | void writeLinkEditData(raw_ostream &OS); |
48 | |
49 | void writeBindOpcodes(raw_ostream &OS, |
50 | std::vector<MachOYAML::BindOpcode> &BindOpcodes); |
51 | // LinkEdit writers |
52 | void writeRebaseOpcodes(raw_ostream &OS); |
53 | void writeBasicBindOpcodes(raw_ostream &OS); |
54 | void writeWeakBindOpcodes(raw_ostream &OS); |
55 | void writeLazyBindOpcodes(raw_ostream &OS); |
56 | void writeNameList(raw_ostream &OS); |
57 | void writeStringTable(raw_ostream &OS); |
58 | void writeExportTrie(raw_ostream &OS); |
59 | void writeDynamicSymbolTable(raw_ostream &OS); |
60 | void writeFunctionStarts(raw_ostream &OS); |
61 | void writeChainedFixups(raw_ostream &OS); |
62 | void writeDyldExportsTrie(raw_ostream &OS); |
63 | void writeDataInCode(raw_ostream &OS); |
64 | |
65 | void dumpExportEntry(raw_ostream &OS, MachOYAML::ExportEntry &Entry); |
66 | void ZeroToOffset(raw_ostream &OS, size_t offset); |
67 | |
68 | MachOYAML::Object &Obj; |
69 | bool is64Bit; |
70 | uint64_t fileStart; |
71 | MachO::mach_header_64 ; |
72 | |
73 | // Old PPC Object Files didn't have __LINKEDIT segments, the data was just |
74 | // stuck at the end of the file. |
75 | bool FoundLinkEditSeg = false; |
76 | }; |
77 | |
78 | Error MachOWriter::writeMachO(raw_ostream &OS) { |
79 | fileStart = OS.tell(); |
80 | writeHeader(OS); |
81 | writeLoadCommands(OS); |
82 | if (Error Err = writeSectionData(OS)) |
83 | return Err; |
84 | writeRelocations(OS); |
85 | if (!FoundLinkEditSeg) |
86 | writeLinkEditData(OS); |
87 | return Error::success(); |
88 | } |
89 | |
90 | void MachOWriter::(raw_ostream &OS) { |
91 | Header.magic = Obj.Header.magic; |
92 | Header.cputype = Obj.Header.cputype; |
93 | Header.cpusubtype = Obj.Header.cpusubtype; |
94 | Header.filetype = Obj.Header.filetype; |
95 | Header.ncmds = Obj.Header.ncmds; |
96 | Header.sizeofcmds = Obj.Header.sizeofcmds; |
97 | Header.flags = Obj.Header.flags; |
98 | Header.reserved = Obj.Header.reserved; |
99 | |
100 | if (Obj.IsLittleEndian != sys::IsLittleEndianHost) |
101 | MachO::swapStruct(H&: Header); |
102 | |
103 | auto = |
104 | is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header); |
105 | OS.write(Ptr: (const char *)&Header, Size: header_size); |
106 | } |
107 | |
108 | template <typename SectionType> |
109 | SectionType constructSection(const MachOYAML::Section &Sec) { |
110 | SectionType TempSec; |
111 | memcpy(dest: reinterpret_cast<void *>(&TempSec.sectname[0]), src: &Sec.sectname[0], n: 16); |
112 | memcpy(dest: reinterpret_cast<void *>(&TempSec.segname[0]), src: &Sec.segname[0], n: 16); |
113 | TempSec.addr = Sec.addr; |
114 | TempSec.size = Sec.size; |
115 | TempSec.offset = Sec.offset; |
116 | TempSec.align = Sec.align; |
117 | TempSec.reloff = Sec.reloff; |
118 | TempSec.nreloc = Sec.nreloc; |
119 | TempSec.flags = Sec.flags; |
120 | TempSec.reserved1 = Sec.reserved1; |
121 | TempSec.reserved2 = Sec.reserved2; |
122 | return TempSec; |
123 | } |
124 | |
125 | template <typename StructType> |
126 | size_t writeLoadCommandData(MachOYAML::LoadCommand &LC, raw_ostream &OS, |
127 | bool IsLittleEndian) { |
128 | return 0; |
129 | } |
130 | |
131 | template <> |
132 | size_t writeLoadCommandData<MachO::segment_command>(MachOYAML::LoadCommand &LC, |
133 | raw_ostream &OS, |
134 | bool IsLittleEndian) { |
135 | size_t BytesWritten = 0; |
136 | for (const auto &Sec : LC.Sections) { |
137 | auto TempSec = constructSection<MachO::section>(Sec); |
138 | if (IsLittleEndian != sys::IsLittleEndianHost) |
139 | MachO::swapStruct(sect&: TempSec); |
140 | OS.write(Ptr: reinterpret_cast<const char *>(&(TempSec)), |
141 | Size: sizeof(MachO::section)); |
142 | BytesWritten += sizeof(MachO::section); |
143 | } |
144 | return BytesWritten; |
145 | } |
146 | |
147 | template <> |
148 | size_t writeLoadCommandData<MachO::segment_command_64>( |
149 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
150 | size_t BytesWritten = 0; |
151 | for (const auto &Sec : LC.Sections) { |
152 | auto TempSec = constructSection<MachO::section_64>(Sec); |
153 | TempSec.reserved3 = Sec.reserved3; |
154 | if (IsLittleEndian != sys::IsLittleEndianHost) |
155 | MachO::swapStruct(sect&: TempSec); |
156 | OS.write(Ptr: reinterpret_cast<const char *>(&(TempSec)), |
157 | Size: sizeof(MachO::section_64)); |
158 | BytesWritten += sizeof(MachO::section_64); |
159 | } |
160 | return BytesWritten; |
161 | } |
162 | |
163 | size_t writePayloadString(MachOYAML::LoadCommand &LC, raw_ostream &OS) { |
164 | size_t BytesWritten = 0; |
165 | if (!LC.Content.empty()) { |
166 | OS.write(Ptr: LC.Content.c_str(), Size: LC.Content.length()); |
167 | BytesWritten = LC.Content.length(); |
168 | } |
169 | return BytesWritten; |
170 | } |
171 | |
172 | template <> |
173 | size_t writeLoadCommandData<MachO::dylib_command>(MachOYAML::LoadCommand &LC, |
174 | raw_ostream &OS, |
175 | bool IsLittleEndian) { |
176 | return writePayloadString(LC, OS); |
177 | } |
178 | |
179 | template <> |
180 | size_t writeLoadCommandData<MachO::dylinker_command>(MachOYAML::LoadCommand &LC, |
181 | raw_ostream &OS, |
182 | bool IsLittleEndian) { |
183 | return writePayloadString(LC, OS); |
184 | } |
185 | |
186 | template <> |
187 | size_t writeLoadCommandData<MachO::rpath_command>(MachOYAML::LoadCommand &LC, |
188 | raw_ostream &OS, |
189 | bool IsLittleEndian) { |
190 | return writePayloadString(LC, OS); |
191 | } |
192 | |
193 | template <> |
194 | size_t writeLoadCommandData<MachO::sub_framework_command>( |
195 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
196 | return writePayloadString(LC, OS); |
197 | } |
198 | |
199 | template <> |
200 | size_t writeLoadCommandData<MachO::sub_umbrella_command>( |
201 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
202 | return writePayloadString(LC, OS); |
203 | } |
204 | |
205 | template <> |
206 | size_t writeLoadCommandData<MachO::sub_client_command>( |
207 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
208 | return writePayloadString(LC, OS); |
209 | } |
210 | |
211 | template <> |
212 | size_t writeLoadCommandData<MachO::sub_library_command>( |
213 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
214 | return writePayloadString(LC, OS); |
215 | } |
216 | |
217 | template <> |
218 | size_t writeLoadCommandData<MachO::build_version_command>( |
219 | MachOYAML::LoadCommand &LC, raw_ostream &OS, bool IsLittleEndian) { |
220 | size_t BytesWritten = 0; |
221 | for (const auto &T : LC.Tools) { |
222 | struct MachO::build_tool_version tool = T; |
223 | if (IsLittleEndian != sys::IsLittleEndianHost) |
224 | MachO::swapStruct(C&: tool); |
225 | OS.write(Ptr: reinterpret_cast<const char *>(&tool), |
226 | Size: sizeof(MachO::build_tool_version)); |
227 | BytesWritten += sizeof(MachO::build_tool_version); |
228 | } |
229 | return BytesWritten; |
230 | } |
231 | |
232 | void ZeroFillBytes(raw_ostream &OS, size_t Size) { |
233 | std::vector<uint8_t> FillData(Size, 0); |
234 | OS.write(Ptr: reinterpret_cast<char *>(FillData.data()), Size); |
235 | } |
236 | |
237 | void Fill(raw_ostream &OS, size_t Size, uint32_t Data) { |
238 | std::vector<uint32_t> FillData((Size / 4) + 1, Data); |
239 | OS.write(Ptr: reinterpret_cast<char *>(FillData.data()), Size); |
240 | } |
241 | |
242 | void MachOWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) { |
243 | auto currOffset = OS.tell() - fileStart; |
244 | if (currOffset < Offset) |
245 | ZeroFillBytes(OS, Size: Offset - currOffset); |
246 | } |
247 | |
248 | void MachOWriter::writeLoadCommands(raw_ostream &OS) { |
249 | for (auto &LC : Obj.LoadCommands) { |
250 | size_t BytesWritten = 0; |
251 | llvm::MachO::macho_load_command Data = LC.Data; |
252 | |
253 | #define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) \ |
254 | case MachO::LCName: \ |
255 | if (Obj.IsLittleEndian != sys::IsLittleEndianHost) \ |
256 | MachO::swapStruct(Data.LCStruct##_data); \ |
257 | OS.write(reinterpret_cast<const char *>(&(Data.LCStruct##_data)), \ |
258 | sizeof(MachO::LCStruct)); \ |
259 | BytesWritten = sizeof(MachO::LCStruct); \ |
260 | BytesWritten += \ |
261 | writeLoadCommandData<MachO::LCStruct>(LC, OS, Obj.IsLittleEndian); \ |
262 | break; |
263 | |
264 | switch (LC.Data.load_command_data.cmd) { |
265 | default: |
266 | if (Obj.IsLittleEndian != sys::IsLittleEndianHost) |
267 | MachO::swapStruct(lc&: Data.load_command_data); |
268 | OS.write(Ptr: reinterpret_cast<const char *>(&(Data.load_command_data)), |
269 | Size: sizeof(MachO::load_command)); |
270 | BytesWritten = sizeof(MachO::load_command); |
271 | BytesWritten += |
272 | writeLoadCommandData<MachO::load_command>(LC, OS, IsLittleEndian: Obj.IsLittleEndian); |
273 | break; |
274 | #include "llvm/BinaryFormat/MachO.def" |
275 | } |
276 | |
277 | if (LC.PayloadBytes.size() > 0) { |
278 | OS.write(Ptr: reinterpret_cast<const char *>(LC.PayloadBytes.data()), |
279 | Size: LC.PayloadBytes.size()); |
280 | BytesWritten += LC.PayloadBytes.size(); |
281 | } |
282 | |
283 | if (LC.ZeroPadBytes > 0) { |
284 | ZeroFillBytes(OS, Size: LC.ZeroPadBytes); |
285 | BytesWritten += LC.ZeroPadBytes; |
286 | } |
287 | |
288 | // Fill remaining bytes with 0. This will only get hit in partially |
289 | // specified test cases. |
290 | auto BytesRemaining = LC.Data.load_command_data.cmdsize - BytesWritten; |
291 | if (BytesRemaining > 0) { |
292 | ZeroFillBytes(OS, Size: BytesRemaining); |
293 | } |
294 | } |
295 | } |
296 | |
297 | Error MachOWriter::writeSectionData(raw_ostream &OS) { |
298 | uint64_t LinkEditOff = 0; |
299 | for (auto &LC : Obj.LoadCommands) { |
300 | switch (LC.Data.load_command_data.cmd) { |
301 | case MachO::LC_SEGMENT: |
302 | case MachO::LC_SEGMENT_64: |
303 | uint64_t segOff = is64Bit ? LC.Data.segment_command_64_data.fileoff |
304 | : LC.Data.segment_command_data.fileoff; |
305 | if (0 == |
306 | strncmp(s1: &LC.Data.segment_command_data.segname[0], s2: "__LINKEDIT" , n: 16)) { |
307 | FoundLinkEditSeg = true; |
308 | LinkEditOff = segOff; |
309 | if (Obj.RawLinkEditSegment) |
310 | continue; |
311 | writeLinkEditData(OS); |
312 | } |
313 | for (auto &Sec : LC.Sections) { |
314 | ZeroToOffset(OS, Offset: Sec.offset); |
315 | // Zero Fill any data between the end of the last thing we wrote and the |
316 | // start of this section. |
317 | if (OS.tell() - fileStart > Sec.offset && Sec.offset != (uint32_t)0) |
318 | return createStringError( |
319 | EC: errc::invalid_argument, |
320 | S: llvm::formatv( |
321 | Fmt: "wrote too much data somewhere, section offsets in " |
322 | "section {0} for segment {1} don't line up: " |
323 | "[cursor={2:x}], [fileStart={3:x}], [sectionOffset={4:x}]" , |
324 | Vals&: Sec.sectname, Vals&: Sec.segname, Vals: OS.tell(), Vals&: fileStart, |
325 | Vals&: Sec.offset.value)); |
326 | |
327 | StringRef SectName(Sec.sectname, |
328 | strnlen(string: Sec.sectname, maxlen: sizeof(Sec.sectname))); |
329 | // If the section's content is specified in the 'DWARF' entry, we will |
330 | // emit it regardless of the section's segname. |
331 | if (Obj.DWARF.getNonEmptySectionNames().count(key: SectName.substr(Start: 2))) { |
332 | if (Sec.content) |
333 | return createStringError(EC: errc::invalid_argument, |
334 | S: "cannot specify section '" + SectName + |
335 | "' contents in the 'DWARF' entry and " |
336 | "the 'content' at the same time" ); |
337 | auto EmitFunc = DWARFYAML::getDWARFEmitterByName(SecName: SectName.substr(Start: 2)); |
338 | if (Error Err = EmitFunc(OS, Obj.DWARF)) |
339 | return Err; |
340 | continue; |
341 | } |
342 | |
343 | // Skip if it's a virtual section. |
344 | if (MachO::isVirtualSection(type: Sec.flags & MachO::SECTION_TYPE)) |
345 | continue; |
346 | |
347 | if (Sec.content) { |
348 | yaml::BinaryRef Content = *Sec.content; |
349 | Content.writeAsBinary(OS); |
350 | ZeroFillBytes(OS, Size: Sec.size - Content.binary_size()); |
351 | } else { |
352 | // Fill section data with 0xDEADBEEF. |
353 | Fill(OS, Size: Sec.size, Data: 0xDEADBEEFu); |
354 | } |
355 | } |
356 | uint64_t segSize = is64Bit ? LC.Data.segment_command_64_data.filesize |
357 | : LC.Data.segment_command_data.filesize; |
358 | ZeroToOffset(OS, Offset: segOff + segSize); |
359 | break; |
360 | } |
361 | } |
362 | |
363 | if (Obj.RawLinkEditSegment) { |
364 | ZeroToOffset(OS, Offset: LinkEditOff); |
365 | if (OS.tell() - fileStart > LinkEditOff || !LinkEditOff) |
366 | return createStringError(EC: errc::invalid_argument, |
367 | S: "section offsets don't line up" ); |
368 | Obj.RawLinkEditSegment->writeAsBinary(OS); |
369 | } |
370 | return Error::success(); |
371 | } |
372 | |
373 | // The implementation of makeRelocationInfo and makeScatteredRelocationInfo is |
374 | // consistent with how libObject parses MachO binary files. For the reference |
375 | // see getStruct, getRelocation, getPlainRelocationPCRel, |
376 | // getPlainRelocationLength and related methods in MachOObjectFile.cpp |
377 | static MachO::any_relocation_info |
378 | makeRelocationInfo(const MachOYAML::Relocation &R, bool IsLE) { |
379 | assert(!R.is_scattered && "non-scattered relocation expected" ); |
380 | MachO::any_relocation_info MRE; |
381 | MRE.r_word0 = R.address; |
382 | if (IsLE) |
383 | MRE.r_word1 = ((unsigned)R.symbolnum << 0) | ((unsigned)R.is_pcrel << 24) | |
384 | ((unsigned)R.length << 25) | ((unsigned)R.is_extern << 27) | |
385 | ((unsigned)R.type << 28); |
386 | else |
387 | MRE.r_word1 = ((unsigned)R.symbolnum << 8) | ((unsigned)R.is_pcrel << 7) | |
388 | ((unsigned)R.length << 5) | ((unsigned)R.is_extern << 4) | |
389 | ((unsigned)R.type << 0); |
390 | return MRE; |
391 | } |
392 | |
393 | static MachO::any_relocation_info |
394 | makeScatteredRelocationInfo(const MachOYAML::Relocation &R) { |
395 | assert(R.is_scattered && "scattered relocation expected" ); |
396 | MachO::any_relocation_info MRE; |
397 | MRE.r_word0 = (((unsigned)R.address << 0) | ((unsigned)R.type << 24) | |
398 | ((unsigned)R.length << 28) | ((unsigned)R.is_pcrel << 30) | |
399 | MachO::R_SCATTERED); |
400 | MRE.r_word1 = R.value; |
401 | return MRE; |
402 | } |
403 | |
404 | void MachOWriter::writeRelocations(raw_ostream &OS) { |
405 | for (const MachOYAML::LoadCommand &LC : Obj.LoadCommands) { |
406 | switch (LC.Data.load_command_data.cmd) { |
407 | case MachO::LC_SEGMENT: |
408 | case MachO::LC_SEGMENT_64: |
409 | for (const MachOYAML::Section &Sec : LC.Sections) { |
410 | if (Sec.relocations.empty()) |
411 | continue; |
412 | ZeroToOffset(OS, Offset: Sec.reloff); |
413 | for (const MachOYAML::Relocation &R : Sec.relocations) { |
414 | MachO::any_relocation_info MRE = |
415 | R.is_scattered ? makeScatteredRelocationInfo(R) |
416 | : makeRelocationInfo(R, IsLE: Obj.IsLittleEndian); |
417 | if (Obj.IsLittleEndian != sys::IsLittleEndianHost) |
418 | MachO::swapStruct(reloc&: MRE); |
419 | OS.write(Ptr: reinterpret_cast<const char *>(&MRE), |
420 | Size: sizeof(MachO::any_relocation_info)); |
421 | } |
422 | } |
423 | } |
424 | } |
425 | } |
426 | |
427 | void MachOWriter::writeBindOpcodes( |
428 | raw_ostream &OS, std::vector<MachOYAML::BindOpcode> &BindOpcodes) { |
429 | |
430 | for (const auto &Opcode : BindOpcodes) { |
431 | uint8_t OpByte = Opcode.Opcode | Opcode.Imm; |
432 | OS.write(Ptr: reinterpret_cast<char *>(&OpByte), Size: 1); |
433 | for (auto Data : Opcode.ULEBExtraData) { |
434 | encodeULEB128(Value: Data, OS); |
435 | } |
436 | for (auto Data : Opcode.SLEBExtraData) { |
437 | encodeSLEB128(Value: Data, OS); |
438 | } |
439 | if (!Opcode.Symbol.empty()) { |
440 | OS.write(Ptr: Opcode.Symbol.data(), Size: Opcode.Symbol.size()); |
441 | OS.write(C: '\0'); |
442 | } |
443 | } |
444 | } |
445 | |
446 | void MachOWriter::dumpExportEntry(raw_ostream &OS, |
447 | MachOYAML::ExportEntry &Entry) { |
448 | encodeULEB128(Value: Entry.TerminalSize, OS); |
449 | if (Entry.TerminalSize > 0) { |
450 | encodeULEB128(Value: Entry.Flags, OS); |
451 | if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) { |
452 | encodeULEB128(Value: Entry.Other, OS); |
453 | OS << Entry.ImportName; |
454 | OS.write(C: '\0'); |
455 | } else { |
456 | encodeULEB128(Value: Entry.Address, OS); |
457 | if (Entry.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) |
458 | encodeULEB128(Value: Entry.Other, OS); |
459 | } |
460 | } |
461 | OS.write(C: static_cast<uint8_t>(Entry.Children.size())); |
462 | for (const auto &EE : Entry.Children) { |
463 | OS << EE.Name; |
464 | OS.write(C: '\0'); |
465 | encodeULEB128(Value: EE.NodeOffset, OS); |
466 | } |
467 | for (auto EE : Entry.Children) |
468 | dumpExportEntry(OS, Entry&: EE); |
469 | } |
470 | |
471 | void MachOWriter::writeExportTrie(raw_ostream &OS) { |
472 | dumpExportEntry(OS, Entry&: Obj.LinkEdit.ExportTrie); |
473 | } |
474 | |
475 | template <typename NListType> |
476 | void writeNListEntry(MachOYAML::NListEntry &NLE, raw_ostream &OS, |
477 | bool IsLittleEndian) { |
478 | NListType ListEntry; |
479 | ListEntry.n_strx = NLE.n_strx; |
480 | ListEntry.n_type = NLE.n_type; |
481 | ListEntry.n_sect = NLE.n_sect; |
482 | ListEntry.n_desc = NLE.n_desc; |
483 | ListEntry.n_value = NLE.n_value; |
484 | |
485 | if (IsLittleEndian != sys::IsLittleEndianHost) |
486 | MachO::swapStruct(ListEntry); |
487 | OS.write(Ptr: reinterpret_cast<const char *>(&ListEntry), Size: sizeof(NListType)); |
488 | } |
489 | |
490 | void MachOWriter::writeLinkEditData(raw_ostream &OS) { |
491 | typedef void (MachOWriter::*writeHandler)(raw_ostream &); |
492 | typedef std::pair<uint64_t, writeHandler> writeOperation; |
493 | std::vector<writeOperation> WriteQueue; |
494 | |
495 | MachO::dyld_info_command *DyldInfoOnlyCmd = nullptr; |
496 | MachO::symtab_command *SymtabCmd = nullptr; |
497 | MachO::dysymtab_command *DSymtabCmd = nullptr; |
498 | MachO::linkedit_data_command *FunctionStartsCmd = nullptr; |
499 | MachO::linkedit_data_command *ChainedFixupsCmd = nullptr; |
500 | MachO::linkedit_data_command *DyldExportsTrieCmd = nullptr; |
501 | MachO::linkedit_data_command *DataInCodeCmd = nullptr; |
502 | for (auto &LC : Obj.LoadCommands) { |
503 | switch (LC.Data.load_command_data.cmd) { |
504 | case MachO::LC_SYMTAB: |
505 | SymtabCmd = &LC.Data.symtab_command_data; |
506 | WriteQueue.push_back( |
507 | x: std::make_pair(x&: SymtabCmd->symoff, y: &MachOWriter::writeNameList)); |
508 | WriteQueue.push_back( |
509 | x: std::make_pair(x&: SymtabCmd->stroff, y: &MachOWriter::writeStringTable)); |
510 | break; |
511 | case MachO::LC_DYLD_INFO_ONLY: |
512 | DyldInfoOnlyCmd = &LC.Data.dyld_info_command_data; |
513 | WriteQueue.push_back(x: std::make_pair(x&: DyldInfoOnlyCmd->rebase_off, |
514 | y: &MachOWriter::writeRebaseOpcodes)); |
515 | WriteQueue.push_back(x: std::make_pair(x&: DyldInfoOnlyCmd->bind_off, |
516 | y: &MachOWriter::writeBasicBindOpcodes)); |
517 | WriteQueue.push_back(x: std::make_pair(x&: DyldInfoOnlyCmd->weak_bind_off, |
518 | y: &MachOWriter::writeWeakBindOpcodes)); |
519 | WriteQueue.push_back(x: std::make_pair(x&: DyldInfoOnlyCmd->lazy_bind_off, |
520 | y: &MachOWriter::writeLazyBindOpcodes)); |
521 | WriteQueue.push_back(x: std::make_pair(x&: DyldInfoOnlyCmd->export_off, |
522 | y: &MachOWriter::writeExportTrie)); |
523 | break; |
524 | case MachO::LC_DYSYMTAB: |
525 | DSymtabCmd = &LC.Data.dysymtab_command_data; |
526 | WriteQueue.push_back(x: std::make_pair( |
527 | x&: DSymtabCmd->indirectsymoff, y: &MachOWriter::writeDynamicSymbolTable)); |
528 | break; |
529 | case MachO::LC_FUNCTION_STARTS: |
530 | FunctionStartsCmd = &LC.Data.linkedit_data_command_data; |
531 | WriteQueue.push_back(x: std::make_pair(x&: FunctionStartsCmd->dataoff, |
532 | y: &MachOWriter::writeFunctionStarts)); |
533 | break; |
534 | case MachO::LC_DYLD_CHAINED_FIXUPS: |
535 | ChainedFixupsCmd = &LC.Data.linkedit_data_command_data; |
536 | WriteQueue.push_back(x: std::make_pair(x&: ChainedFixupsCmd->dataoff, |
537 | y: &MachOWriter::writeChainedFixups)); |
538 | break; |
539 | case MachO::LC_DYLD_EXPORTS_TRIE: |
540 | DyldExportsTrieCmd = &LC.Data.linkedit_data_command_data; |
541 | WriteQueue.push_back(x: std::make_pair(x&: DyldExportsTrieCmd->dataoff, |
542 | y: &MachOWriter::writeDyldExportsTrie)); |
543 | break; |
544 | case MachO::LC_DATA_IN_CODE: |
545 | DataInCodeCmd = &LC.Data.linkedit_data_command_data; |
546 | WriteQueue.push_back(x: std::make_pair(x&: DataInCodeCmd->dataoff, |
547 | y: &MachOWriter::writeDataInCode)); |
548 | break; |
549 | } |
550 | } |
551 | |
552 | llvm::sort(C&: WriteQueue, Comp: llvm::less_first()); |
553 | |
554 | for (auto writeOp : WriteQueue) { |
555 | ZeroToOffset(OS, Offset: writeOp.first); |
556 | (this->*writeOp.second)(OS); |
557 | } |
558 | } |
559 | |
560 | void MachOWriter::writeRebaseOpcodes(raw_ostream &OS) { |
561 | MachOYAML::LinkEditData &LinkEdit = Obj.LinkEdit; |
562 | |
563 | for (const auto &Opcode : LinkEdit.RebaseOpcodes) { |
564 | uint8_t OpByte = Opcode.Opcode | Opcode.Imm; |
565 | OS.write(Ptr: reinterpret_cast<char *>(&OpByte), Size: 1); |
566 | for (auto Data : Opcode.ExtraData) |
567 | encodeULEB128(Value: Data, OS); |
568 | } |
569 | } |
570 | |
571 | void MachOWriter::writeBasicBindOpcodes(raw_ostream &OS) { |
572 | writeBindOpcodes(OS, BindOpcodes&: Obj.LinkEdit.BindOpcodes); |
573 | } |
574 | |
575 | void MachOWriter::writeWeakBindOpcodes(raw_ostream &OS) { |
576 | writeBindOpcodes(OS, BindOpcodes&: Obj.LinkEdit.WeakBindOpcodes); |
577 | } |
578 | |
579 | void MachOWriter::writeLazyBindOpcodes(raw_ostream &OS) { |
580 | writeBindOpcodes(OS, BindOpcodes&: Obj.LinkEdit.LazyBindOpcodes); |
581 | } |
582 | |
583 | void MachOWriter::writeNameList(raw_ostream &OS) { |
584 | for (auto NLE : Obj.LinkEdit.NameList) { |
585 | if (is64Bit) |
586 | writeNListEntry<MachO::nlist_64>(NLE, OS, IsLittleEndian: Obj.IsLittleEndian); |
587 | else |
588 | writeNListEntry<MachO::nlist>(NLE, OS, IsLittleEndian: Obj.IsLittleEndian); |
589 | } |
590 | } |
591 | |
592 | void MachOWriter::writeStringTable(raw_ostream &OS) { |
593 | for (auto Str : Obj.LinkEdit.StringTable) { |
594 | OS.write(Ptr: Str.data(), Size: Str.size()); |
595 | OS.write(C: '\0'); |
596 | } |
597 | } |
598 | |
599 | void MachOWriter::writeDynamicSymbolTable(raw_ostream &OS) { |
600 | for (auto Data : Obj.LinkEdit.IndirectSymbols) |
601 | OS.write(Ptr: reinterpret_cast<const char *>(&Data), |
602 | Size: sizeof(yaml::Hex32::BaseType)); |
603 | } |
604 | |
605 | void MachOWriter::writeFunctionStarts(raw_ostream &OS) { |
606 | uint64_t Addr = 0; |
607 | for (uint64_t NextAddr : Obj.LinkEdit.FunctionStarts) { |
608 | uint64_t Delta = NextAddr - Addr; |
609 | encodeULEB128(Value: Delta, OS); |
610 | Addr = NextAddr; |
611 | } |
612 | |
613 | OS.write(C: '\0'); |
614 | } |
615 | |
616 | void MachOWriter::writeDataInCode(raw_ostream &OS) { |
617 | for (const auto &Entry : Obj.LinkEdit.DataInCode) { |
618 | MachO::data_in_code_entry DICE{.offset: Entry.Offset, .length: Entry.Length, .kind: Entry.Kind}; |
619 | if (Obj.IsLittleEndian != sys::IsLittleEndianHost) |
620 | MachO::swapStruct(C&: DICE); |
621 | OS.write(Ptr: reinterpret_cast<const char *>(&DICE), |
622 | Size: sizeof(MachO::data_in_code_entry)); |
623 | } |
624 | } |
625 | |
626 | void MachOWriter::writeChainedFixups(raw_ostream &OS) { |
627 | if (Obj.LinkEdit.ChainedFixups.size() > 0) |
628 | OS.write(Ptr: reinterpret_cast<const char *>(Obj.LinkEdit.ChainedFixups.data()), |
629 | Size: Obj.LinkEdit.ChainedFixups.size()); |
630 | } |
631 | |
632 | void MachOWriter::writeDyldExportsTrie(raw_ostream &OS) { |
633 | dumpExportEntry(OS, Entry&: Obj.LinkEdit.ExportTrie); |
634 | } |
635 | |
636 | class UniversalWriter { |
637 | public: |
638 | UniversalWriter(yaml::YamlObjectFile &ObjectFile) |
639 | : ObjectFile(ObjectFile), fileStart(0) {} |
640 | |
641 | Error writeMachO(raw_ostream &OS); |
642 | |
643 | private: |
644 | void writeFatHeader(raw_ostream &OS); |
645 | void writeFatArchs(raw_ostream &OS); |
646 | |
647 | void ZeroToOffset(raw_ostream &OS, size_t offset); |
648 | |
649 | yaml::YamlObjectFile &ObjectFile; |
650 | uint64_t fileStart; |
651 | }; |
652 | |
653 | Error UniversalWriter::writeMachO(raw_ostream &OS) { |
654 | fileStart = OS.tell(); |
655 | if (ObjectFile.MachO) { |
656 | MachOWriter Writer(*ObjectFile.MachO); |
657 | return Writer.writeMachO(OS); |
658 | } |
659 | |
660 | writeFatHeader(OS); |
661 | writeFatArchs(OS); |
662 | |
663 | auto &FatFile = *ObjectFile.FatMachO; |
664 | if (FatFile.FatArchs.size() < FatFile.Slices.size()) |
665 | return createStringError( |
666 | EC: errc::invalid_argument, |
667 | S: "cannot write 'Slices' if not described in 'FatArches'" ); |
668 | |
669 | for (size_t i = 0; i < FatFile.Slices.size(); i++) { |
670 | ZeroToOffset(OS, offset: FatFile.FatArchs[i].offset); |
671 | MachOWriter Writer(FatFile.Slices[i]); |
672 | if (Error Err = Writer.writeMachO(OS)) |
673 | return Err; |
674 | |
675 | auto SliceEnd = FatFile.FatArchs[i].offset + FatFile.FatArchs[i].size; |
676 | ZeroToOffset(OS, offset: SliceEnd); |
677 | } |
678 | |
679 | return Error::success(); |
680 | } |
681 | |
682 | void UniversalWriter::(raw_ostream &OS) { |
683 | auto &FatFile = *ObjectFile.FatMachO; |
684 | MachO::fat_header ; |
685 | header.magic = FatFile.Header.magic; |
686 | header.nfat_arch = FatFile.Header.nfat_arch; |
687 | if (sys::IsLittleEndianHost) |
688 | swapStruct(mh&: header); |
689 | OS.write(Ptr: reinterpret_cast<const char *>(&header), Size: sizeof(MachO::fat_header)); |
690 | } |
691 | |
692 | template <typename FatArchType> |
693 | FatArchType constructFatArch(MachOYAML::FatArch &Arch) { |
694 | FatArchType FatArch; |
695 | FatArch.cputype = Arch.cputype; |
696 | FatArch.cpusubtype = Arch.cpusubtype; |
697 | FatArch.offset = Arch.offset; |
698 | FatArch.size = Arch.size; |
699 | FatArch.align = Arch.align; |
700 | return FatArch; |
701 | } |
702 | |
703 | template <typename StructType> |
704 | void writeFatArch(MachOYAML::FatArch &LC, raw_ostream &OS) {} |
705 | |
706 | template <> |
707 | void writeFatArch<MachO::fat_arch>(MachOYAML::FatArch &Arch, raw_ostream &OS) { |
708 | auto FatArch = constructFatArch<MachO::fat_arch>(Arch); |
709 | if (sys::IsLittleEndianHost) |
710 | swapStruct(mh&: FatArch); |
711 | OS.write(Ptr: reinterpret_cast<const char *>(&FatArch), Size: sizeof(MachO::fat_arch)); |
712 | } |
713 | |
714 | template <> |
715 | void writeFatArch<MachO::fat_arch_64>(MachOYAML::FatArch &Arch, |
716 | raw_ostream &OS) { |
717 | auto FatArch = constructFatArch<MachO::fat_arch_64>(Arch); |
718 | FatArch.reserved = Arch.reserved; |
719 | if (sys::IsLittleEndianHost) |
720 | swapStruct(mh&: FatArch); |
721 | OS.write(Ptr: reinterpret_cast<const char *>(&FatArch), |
722 | Size: sizeof(MachO::fat_arch_64)); |
723 | } |
724 | |
725 | void UniversalWriter::writeFatArchs(raw_ostream &OS) { |
726 | auto &FatFile = *ObjectFile.FatMachO; |
727 | bool is64Bit = FatFile.Header.magic == MachO::FAT_MAGIC_64; |
728 | for (auto Arch : FatFile.FatArchs) { |
729 | if (is64Bit) |
730 | writeFatArch<MachO::fat_arch_64>(Arch, OS); |
731 | else |
732 | writeFatArch<MachO::fat_arch>(Arch, OS); |
733 | } |
734 | } |
735 | |
736 | void UniversalWriter::ZeroToOffset(raw_ostream &OS, size_t Offset) { |
737 | auto currOffset = OS.tell() - fileStart; |
738 | if (currOffset < Offset) |
739 | ZeroFillBytes(OS, Size: Offset - currOffset); |
740 | } |
741 | |
742 | } // end anonymous namespace |
743 | |
744 | namespace llvm { |
745 | namespace yaml { |
746 | |
747 | bool yaml2macho(YamlObjectFile &Doc, raw_ostream &Out, ErrorHandler EH) { |
748 | UniversalWriter Writer(Doc); |
749 | if (Error Err = Writer.writeMachO(OS&: Out)) { |
750 | handleAllErrors(E: std::move(Err), |
751 | Handlers: [&](const ErrorInfoBase &Err) { EH(Err.message()); }); |
752 | return false; |
753 | } |
754 | return true; |
755 | } |
756 | |
757 | } // namespace yaml |
758 | } // namespace llvm |
759 | |