1 //===- yaml2coff - Convert YAML to a COFF object file ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// The COFF component of yaml2obj.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "yaml2obj.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
21 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
22 #include "llvm/Object/COFF.h"
23 #include "llvm/ObjectYAML/ObjectYAML.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/WithColor.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <vector>
30
31 using namespace llvm;
32
33 /// This parses a yaml stream that represents a COFF object file.
34 /// See docs/yaml2obj for the yaml scheema.
35 struct COFFParser {
COFFParserCOFFParser36 COFFParser(COFFYAML::Object &Obj)
37 : Obj(Obj), SectionTableStart(0), SectionTableSize(0) {
38 // A COFF string table always starts with a 4 byte size field. Offsets into
39 // it include this size, so allocate it now.
40 StringTable.append(4, char(0));
41 }
42
useBigObjCOFFParser43 bool useBigObj() const {
44 return static_cast<int32_t>(Obj.Sections.size()) >
45 COFF::MaxNumberOfSections16;
46 }
47
isPECOFFParser48 bool isPE() const { return Obj.OptionalHeader.hasValue(); }
is64BitCOFFParser49 bool is64Bit() const {
50 return Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 ||
51 Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_ARM64;
52 }
53
getFileAlignmentCOFFParser54 uint32_t getFileAlignment() const {
55 return Obj.OptionalHeader->Header.FileAlignment;
56 }
57
getHeaderSizeCOFFParser58 unsigned getHeaderSize() const {
59 return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
60 }
61
getSymbolSizeCOFFParser62 unsigned getSymbolSize() const {
63 return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
64 }
65
parseSectionsCOFFParser66 bool parseSections() {
67 for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
68 e = Obj.Sections.end(); i != e; ++i) {
69 COFFYAML::Section &Sec = *i;
70
71 // If the name is less than 8 bytes, store it in place, otherwise
72 // store it in the string table.
73 StringRef Name = Sec.Name;
74
75 if (Name.size() <= COFF::NameSize) {
76 std::copy(Name.begin(), Name.end(), Sec.Header.Name);
77 } else {
78 // Add string to the string table and format the index for output.
79 unsigned Index = getStringIndex(Name);
80 std::string str = utostr(Index);
81 if (str.size() > 7) {
82 errs() << "String table got too large\n";
83 return false;
84 }
85 Sec.Header.Name[0] = '/';
86 std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
87 }
88
89 if (Sec.Alignment) {
90 if (Sec.Alignment > 8192) {
91 errs() << "Section alignment is too large\n";
92 return false;
93 }
94 if (!isPowerOf2_32(Sec.Alignment)) {
95 errs() << "Section alignment is not a power of 2\n";
96 return false;
97 }
98 Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
99 }
100 }
101 return true;
102 }
103
parseSymbolsCOFFParser104 bool parseSymbols() {
105 for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
106 e = Obj.Symbols.end(); i != e; ++i) {
107 COFFYAML::Symbol &Sym = *i;
108
109 // If the name is less than 8 bytes, store it in place, otherwise
110 // store it in the string table.
111 StringRef Name = Sym.Name;
112 if (Name.size() <= COFF::NameSize) {
113 std::copy(Name.begin(), Name.end(), Sym.Header.Name);
114 } else {
115 // Add string to the string table and format the index for output.
116 unsigned Index = getStringIndex(Name);
117 *reinterpret_cast<support::aligned_ulittle32_t*>(
118 Sym.Header.Name + 4) = Index;
119 }
120
121 Sym.Header.Type = Sym.SimpleType;
122 Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
123 }
124 return true;
125 }
126
parseCOFFParser127 bool parse() {
128 if (!parseSections())
129 return false;
130 if (!parseSymbols())
131 return false;
132 return true;
133 }
134
getStringIndexCOFFParser135 unsigned getStringIndex(StringRef Str) {
136 StringMap<unsigned>::iterator i = StringTableMap.find(Str);
137 if (i == StringTableMap.end()) {
138 unsigned Index = StringTable.size();
139 StringTable.append(Str.begin(), Str.end());
140 StringTable.push_back(0);
141 StringTableMap[Str] = Index;
142 return Index;
143 }
144 return i->second;
145 }
146
147 COFFYAML::Object &Obj;
148
149 codeview::StringsAndChecksums StringsAndChecksums;
150 BumpPtrAllocator Allocator;
151 StringMap<unsigned> StringTableMap;
152 std::string StringTable;
153 uint32_t SectionTableStart;
154 uint32_t SectionTableSize;
155 };
156
157 // Take a CP and assign addresses and sizes to everything. Returns false if the
158 // layout is not valid to do.
layoutOptionalHeader(COFFParser & CP)159 static bool layoutOptionalHeader(COFFParser &CP) {
160 if (!CP.isPE())
161 return true;
162 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
163 : sizeof(object::pe32_header);
164 CP.Obj.Header.SizeOfOptionalHeader =
165 PEHeaderSize +
166 sizeof(object::data_directory) * (COFF::NUM_DATA_DIRECTORIES + 1);
167 return true;
168 }
169
170 namespace {
171 enum { DOSStubSize = 128 };
172 }
173
174 static yaml::BinaryRef
toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,const codeview::StringsAndChecksums & SC,BumpPtrAllocator & Allocator)175 toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,
176 const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
177 using namespace codeview;
178 ExitOnError Err("Error occurred writing .debug$S section");
179 auto CVSS =
180 Err(CodeViewYAML::toCodeViewSubsectionList(Allocator, Subsections, SC));
181
182 std::vector<DebugSubsectionRecordBuilder> Builders;
183 uint32_t Size = sizeof(uint32_t);
184 for (auto &SS : CVSS) {
185 DebugSubsectionRecordBuilder B(SS, CodeViewContainer::ObjectFile);
186 Size += B.calculateSerializedLength();
187 Builders.push_back(std::move(B));
188 }
189 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
190 MutableArrayRef<uint8_t> Output(Buffer, Size);
191 BinaryStreamWriter Writer(Output, support::little);
192
193 Err(Writer.writeInteger<uint32_t>(COFF::DEBUG_SECTION_MAGIC));
194 for (const auto &B : Builders) {
195 Err(B.commit(Writer));
196 }
197 return {Output};
198 }
199
200 // Take a CP and assign addresses and sizes to everything. Returns false if the
201 // layout is not valid to do.
layoutCOFF(COFFParser & CP)202 static bool layoutCOFF(COFFParser &CP) {
203 // The section table starts immediately after the header, including the
204 // optional header.
205 CP.SectionTableStart =
206 CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
207 if (CP.isPE())
208 CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
209 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
210
211 uint32_t CurrentSectionDataOffset =
212 CP.SectionTableStart + CP.SectionTableSize;
213
214 for (COFFYAML::Section &S : CP.Obj.Sections) {
215 // We support specifying exactly one of SectionData or Subsections. So if
216 // there is already some SectionData, then we don't need to do any of this.
217 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
218 CodeViewYAML::initializeStringsAndChecksums(S.DebugS,
219 CP.StringsAndChecksums);
220 if (CP.StringsAndChecksums.hasChecksums() &&
221 CP.StringsAndChecksums.hasStrings())
222 break;
223 }
224 }
225
226 // Assign each section data address consecutively.
227 for (COFFYAML::Section &S : CP.Obj.Sections) {
228 if (S.Name == ".debug$S") {
229 if (S.SectionData.binary_size() == 0) {
230 assert(CP.StringsAndChecksums.hasStrings() &&
231 "Object file does not have debug string table!");
232
233 S.SectionData =
234 toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
235 }
236 } else if (S.Name == ".debug$T") {
237 if (S.SectionData.binary_size() == 0)
238 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
239 } else if (S.Name == ".debug$P") {
240 if (S.SectionData.binary_size() == 0)
241 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
242 } else if (S.Name == ".debug$H") {
243 if (S.DebugH.hasValue() && S.SectionData.binary_size() == 0)
244 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
245 }
246
247 if (S.SectionData.binary_size() > 0) {
248 CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,
249 CP.isPE() ? CP.getFileAlignment() : 4);
250 S.Header.SizeOfRawData = S.SectionData.binary_size();
251 if (CP.isPE())
252 S.Header.SizeOfRawData =
253 alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
254 S.Header.PointerToRawData = CurrentSectionDataOffset;
255 CurrentSectionDataOffset += S.Header.SizeOfRawData;
256 if (!S.Relocations.empty()) {
257 S.Header.PointerToRelocations = CurrentSectionDataOffset;
258 S.Header.NumberOfRelocations = S.Relocations.size();
259 CurrentSectionDataOffset +=
260 S.Header.NumberOfRelocations * COFF::RelocationSize;
261 }
262 } else {
263 S.Header.SizeOfRawData = 0;
264 S.Header.PointerToRawData = 0;
265 }
266 }
267
268 uint32_t SymbolTableStart = CurrentSectionDataOffset;
269
270 // Calculate number of symbols.
271 uint32_t NumberOfSymbols = 0;
272 for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
273 e = CP.Obj.Symbols.end();
274 i != e; ++i) {
275 uint32_t NumberOfAuxSymbols = 0;
276 if (i->FunctionDefinition)
277 NumberOfAuxSymbols += 1;
278 if (i->bfAndefSymbol)
279 NumberOfAuxSymbols += 1;
280 if (i->WeakExternal)
281 NumberOfAuxSymbols += 1;
282 if (!i->File.empty())
283 NumberOfAuxSymbols +=
284 (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
285 if (i->SectionDefinition)
286 NumberOfAuxSymbols += 1;
287 if (i->CLRToken)
288 NumberOfAuxSymbols += 1;
289 i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
290 NumberOfSymbols += 1 + NumberOfAuxSymbols;
291 }
292
293 // Store all the allocated start addresses in the header.
294 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
295 CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
296 if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)
297 CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
298 else
299 CP.Obj.Header.PointerToSymbolTable = 0;
300
301 *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
302 = CP.StringTable.size();
303
304 return true;
305 }
306
307 template <typename value_type>
308 struct binary_le_impl {
309 value_type Value;
binary_le_implbinary_le_impl310 binary_le_impl(value_type V) : Value(V) {}
311 };
312
313 template <typename value_type>
operator <<(raw_ostream & OS,const binary_le_impl<value_type> & BLE)314 raw_ostream &operator <<( raw_ostream &OS
315 , const binary_le_impl<value_type> &BLE) {
316 char Buffer[sizeof(BLE.Value)];
317 support::endian::write<value_type, support::little, support::unaligned>(
318 Buffer, BLE.Value);
319 OS.write(Buffer, sizeof(BLE.Value));
320 return OS;
321 }
322
323 template <typename value_type>
binary_le(value_type V)324 binary_le_impl<value_type> binary_le(value_type V) {
325 return binary_le_impl<value_type>(V);
326 }
327
328 template <size_t NumBytes> struct zeros_impl {};
329
330 template <size_t NumBytes>
operator <<(raw_ostream & OS,const zeros_impl<NumBytes> &)331 raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) {
332 char Buffer[NumBytes];
333 memset(Buffer, 0, sizeof(Buffer));
334 OS.write(Buffer, sizeof(Buffer));
335 return OS;
336 }
337
338 template <typename T>
zeros(const T &)339 zeros_impl<sizeof(T)> zeros(const T &) {
340 return zeros_impl<sizeof(T)>();
341 }
342
343 struct num_zeros_impl {
344 size_t N;
num_zeros_implnum_zeros_impl345 num_zeros_impl(size_t N) : N(N) {}
346 };
347
operator <<(raw_ostream & OS,const num_zeros_impl & NZI)348 raw_ostream &operator<<(raw_ostream &OS, const num_zeros_impl &NZI) {
349 for (size_t I = 0; I != NZI.N; ++I)
350 OS.write(0);
351 return OS;
352 }
353
num_zeros(size_t N)354 static num_zeros_impl num_zeros(size_t N) {
355 num_zeros_impl NZI(N);
356 return NZI;
357 }
358
359 template <typename T>
initializeOptionalHeader(COFFParser & CP,uint16_t Magic,T Header)360 static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header) {
361 memset(Header, 0, sizeof(*Header));
362 Header->Magic = Magic;
363 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
364 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
365 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
366 SizeOfUninitializedData = 0;
367 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
368 Header->FileAlignment);
369 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
370 uint32_t BaseOfData = 0;
371 for (const COFFYAML::Section &S : CP.Obj.Sections) {
372 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
373 SizeOfCode += S.Header.SizeOfRawData;
374 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
375 SizeOfInitializedData += S.Header.SizeOfRawData;
376 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
377 SizeOfUninitializedData += S.Header.SizeOfRawData;
378 if (S.Name.equals(".text"))
379 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
380 else if (S.Name.equals(".data"))
381 BaseOfData = S.Header.VirtualAddress; // RVA
382 if (S.Header.VirtualAddress)
383 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
384 }
385 Header->SizeOfCode = SizeOfCode;
386 Header->SizeOfInitializedData = SizeOfInitializedData;
387 Header->SizeOfUninitializedData = SizeOfUninitializedData;
388 Header->AddressOfEntryPoint =
389 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
390 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
391 Header->MajorOperatingSystemVersion =
392 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
393 Header->MinorOperatingSystemVersion =
394 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
395 Header->MajorImageVersion =
396 CP.Obj.OptionalHeader->Header.MajorImageVersion;
397 Header->MinorImageVersion =
398 CP.Obj.OptionalHeader->Header.MinorImageVersion;
399 Header->MajorSubsystemVersion =
400 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
401 Header->MinorSubsystemVersion =
402 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
403 Header->SizeOfImage = SizeOfImage;
404 Header->SizeOfHeaders = SizeOfHeaders;
405 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
406 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
407 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
408 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
409 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
410 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
411 Header->NumberOfRvaAndSize = COFF::NUM_DATA_DIRECTORIES + 1;
412 return BaseOfData;
413 }
414
writeCOFF(COFFParser & CP,raw_ostream & OS)415 static bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
416 if (CP.isPE()) {
417 // PE files start with a DOS stub.
418 object::dos_header DH;
419 memset(&DH, 0, sizeof(DH));
420
421 // DOS EXEs start with "MZ" magic.
422 DH.Magic[0] = 'M';
423 DH.Magic[1] = 'Z';
424 // Initializing the AddressOfRelocationTable is strictly optional but
425 // mollifies certain tools which expect it to have a value greater than
426 // 0x40.
427 DH.AddressOfRelocationTable = sizeof(DH);
428 // This is the address of the PE signature.
429 DH.AddressOfNewExeHeader = DOSStubSize;
430
431 // Write out our DOS stub.
432 OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));
433 // Write padding until we reach the position of where our PE signature
434 // should live.
435 OS << num_zeros(DOSStubSize - sizeof(DH));
436 // Write out the PE signature.
437 OS.write(COFF::PEMagic, sizeof(COFF::PEMagic));
438 }
439 if (CP.useBigObj()) {
440 OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
441 << binary_le(static_cast<uint16_t>(0xffff))
442 << binary_le(static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion))
443 << binary_le(CP.Obj.Header.Machine)
444 << binary_le(CP.Obj.Header.TimeDateStamp);
445 OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
446 OS << zeros(uint32_t(0))
447 << zeros(uint32_t(0))
448 << zeros(uint32_t(0))
449 << zeros(uint32_t(0))
450 << binary_le(CP.Obj.Header.NumberOfSections)
451 << binary_le(CP.Obj.Header.PointerToSymbolTable)
452 << binary_le(CP.Obj.Header.NumberOfSymbols);
453 } else {
454 OS << binary_le(CP.Obj.Header.Machine)
455 << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
456 << binary_le(CP.Obj.Header.TimeDateStamp)
457 << binary_le(CP.Obj.Header.PointerToSymbolTable)
458 << binary_le(CP.Obj.Header.NumberOfSymbols)
459 << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
460 << binary_le(CP.Obj.Header.Characteristics);
461 }
462 if (CP.isPE()) {
463 if (CP.is64Bit()) {
464 object::pe32plus_header PEH;
465 initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH);
466 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
467 } else {
468 object::pe32_header PEH;
469 uint32_t BaseOfData = initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH);
470 PEH.BaseOfData = BaseOfData;
471 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
472 }
473 for (const Optional<COFF::DataDirectory> &DD :
474 CP.Obj.OptionalHeader->DataDirectories) {
475 if (!DD.hasValue()) {
476 OS << zeros(uint32_t(0));
477 OS << zeros(uint32_t(0));
478 } else {
479 OS << binary_le(DD->RelativeVirtualAddress);
480 OS << binary_le(DD->Size);
481 }
482 }
483 OS << zeros(uint32_t(0));
484 OS << zeros(uint32_t(0));
485 }
486
487 assert(OS.tell() == CP.SectionTableStart);
488 // Output section table.
489 for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
490 e = CP.Obj.Sections.end();
491 i != e; ++i) {
492 OS.write(i->Header.Name, COFF::NameSize);
493 OS << binary_le(i->Header.VirtualSize)
494 << binary_le(i->Header.VirtualAddress)
495 << binary_le(i->Header.SizeOfRawData)
496 << binary_le(i->Header.PointerToRawData)
497 << binary_le(i->Header.PointerToRelocations)
498 << binary_le(i->Header.PointerToLineNumbers)
499 << binary_le(i->Header.NumberOfRelocations)
500 << binary_le(i->Header.NumberOfLineNumbers)
501 << binary_le(i->Header.Characteristics);
502 }
503 assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);
504
505 unsigned CurSymbol = 0;
506 StringMap<unsigned> SymbolTableIndexMap;
507 for (std::vector<COFFYAML::Symbol>::iterator I = CP.Obj.Symbols.begin(),
508 E = CP.Obj.Symbols.end();
509 I != E; ++I) {
510 SymbolTableIndexMap[I->Name] = CurSymbol;
511 CurSymbol += 1 + I->Header.NumberOfAuxSymbols;
512 }
513
514 // Output section data.
515 for (const COFFYAML::Section &S : CP.Obj.Sections) {
516 if (!S.Header.SizeOfRawData)
517 continue;
518 assert(S.Header.PointerToRawData >= OS.tell());
519 OS << num_zeros(S.Header.PointerToRawData - OS.tell());
520 S.SectionData.writeAsBinary(OS);
521 assert(S.Header.SizeOfRawData >= S.SectionData.binary_size());
522 OS << num_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size());
523 for (const COFFYAML::Relocation &R : S.Relocations) {
524 uint32_t SymbolTableIndex;
525 if (R.SymbolTableIndex) {
526 if (!R.SymbolName.empty())
527 WithColor::error()
528 << "Both SymbolName and SymbolTableIndex specified\n";
529 SymbolTableIndex = *R.SymbolTableIndex;
530 } else {
531 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
532 }
533 OS << binary_le(R.VirtualAddress)
534 << binary_le(SymbolTableIndex)
535 << binary_le(R.Type);
536 }
537 }
538
539 // Output symbol table.
540
541 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
542 e = CP.Obj.Symbols.end();
543 i != e; ++i) {
544 OS.write(i->Header.Name, COFF::NameSize);
545 OS << binary_le(i->Header.Value);
546 if (CP.useBigObj())
547 OS << binary_le(i->Header.SectionNumber);
548 else
549 OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
550 OS << binary_le(i->Header.Type)
551 << binary_le(i->Header.StorageClass)
552 << binary_le(i->Header.NumberOfAuxSymbols);
553
554 if (i->FunctionDefinition)
555 OS << binary_le(i->FunctionDefinition->TagIndex)
556 << binary_le(i->FunctionDefinition->TotalSize)
557 << binary_le(i->FunctionDefinition->PointerToLinenumber)
558 << binary_le(i->FunctionDefinition->PointerToNextFunction)
559 << zeros(i->FunctionDefinition->unused)
560 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
561 if (i->bfAndefSymbol)
562 OS << zeros(i->bfAndefSymbol->unused1)
563 << binary_le(i->bfAndefSymbol->Linenumber)
564 << zeros(i->bfAndefSymbol->unused2)
565 << binary_le(i->bfAndefSymbol->PointerToNextFunction)
566 << zeros(i->bfAndefSymbol->unused3)
567 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
568 if (i->WeakExternal)
569 OS << binary_le(i->WeakExternal->TagIndex)
570 << binary_le(i->WeakExternal->Characteristics)
571 << zeros(i->WeakExternal->unused)
572 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
573 if (!i->File.empty()) {
574 unsigned SymbolSize = CP.getSymbolSize();
575 uint32_t NumberOfAuxRecords =
576 (i->File.size() + SymbolSize - 1) / SymbolSize;
577 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
578 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
579 OS.write(i->File.data(), i->File.size());
580 OS << num_zeros(NumZeros);
581 }
582 if (i->SectionDefinition)
583 OS << binary_le(i->SectionDefinition->Length)
584 << binary_le(i->SectionDefinition->NumberOfRelocations)
585 << binary_le(i->SectionDefinition->NumberOfLinenumbers)
586 << binary_le(i->SectionDefinition->CheckSum)
587 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
588 << binary_le(i->SectionDefinition->Selection)
589 << zeros(i->SectionDefinition->unused)
590 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16))
591 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
592 if (i->CLRToken)
593 OS << binary_le(i->CLRToken->AuxType)
594 << zeros(i->CLRToken->unused1)
595 << binary_le(i->CLRToken->SymbolTableIndex)
596 << zeros(i->CLRToken->unused2)
597 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
598 }
599
600 // Output string table.
601 if (CP.Obj.Header.PointerToSymbolTable)
602 OS.write(&CP.StringTable[0], CP.StringTable.size());
603 return true;
604 }
605
yaml2coff(llvm::COFFYAML::Object & Doc,raw_ostream & Out)606 int yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out) {
607 COFFParser CP(Doc);
608 if (!CP.parse()) {
609 errs() << "yaml2obj: Failed to parse YAML file!\n";
610 return 1;
611 }
612
613 if (!layoutOptionalHeader(CP)) {
614 errs() << "yaml2obj: Failed to layout optional header for COFF file!\n";
615 return 1;
616 }
617
618 if (!layoutCOFF(CP)) {
619 errs() << "yaml2obj: Failed to layout COFF file!\n";
620 return 1;
621 }
622 if (!writeCOFF(CP, Out)) {
623 errs() << "yaml2obj: Failed to write COFF file!\n";
624 return 1;
625 }
626 return 0;
627 }
628