1 //===- Writer.cpp ---------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/BinaryFormat/COFF.h"
14 #include "llvm/Object/COFF.h"
15 #include "llvm/Support/ErrorHandling.h"
23 using namespace object;
26 Error COFFWriter::finalizeRelocTargets() {
27 for (Section &Sec : Obj.getMutableSections()) {
28 for (Relocation &R : Sec.Relocs) {
29 const Symbol *Sym = Obj.findSymbol(R.Target);
31 return createStringError(object_error::invalid_symbol_index,
32 "relocation target '%s' (%zu) not found",
33 R.TargetName.str().c_str(), R.Target);
34 R.Reloc.SymbolTableIndex = Sym->RawIndex;
37 return Error::success();
40 Error COFFWriter::finalizeSymbolContents() {
41 for (Symbol &Sym : Obj.getMutableSymbols()) {
42 if (Sym.TargetSectionId <= 0) {
43 // Undefined, or a special kind of symbol. These negative values
44 // are stored in the SectionNumber field which is unsigned.
45 Sym.Sym.SectionNumber = static_cast<uint32_t>(Sym.TargetSectionId);
47 const Section *Sec = Obj.findSection(Sym.TargetSectionId);
49 return createStringError(object_error::invalid_symbol_index,
50 "symbol '%s' points to a removed section",
51 Sym.Name.str().c_str());
52 Sym.Sym.SectionNumber = Sec->Index;
54 if (Sym.Sym.NumberOfAuxSymbols == 1 &&
55 Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC) {
56 coff_aux_section_definition *SD =
57 reinterpret_cast<coff_aux_section_definition *>(
58 Sym.AuxData[0].Opaque);
59 uint32_t SDSectionNumber;
60 if (Sym.AssociativeComdatTargetSectionId == 0) {
61 // Not a comdat associative section; just set the Number field to
62 // the number of the section itself.
63 SDSectionNumber = Sec->Index;
65 Sec = Obj.findSection(Sym.AssociativeComdatTargetSectionId);
67 return createStringError(
68 object_error::invalid_symbol_index,
69 "symbol '%s' is associative to a removed section",
70 Sym.Name.str().c_str());
71 SDSectionNumber = Sec->Index;
73 // Update the section definition with the new section number.
74 SD->NumberLowPart = static_cast<uint16_t>(SDSectionNumber);
75 SD->NumberHighPart = static_cast<uint16_t>(SDSectionNumber >> 16);
78 // Check that we actually have got AuxData to match the weak symbol target
79 // we want to set. Only >= 1 would be required, but only == 1 makes sense.
80 if (Sym.WeakTargetSymbolId && Sym.Sym.NumberOfAuxSymbols == 1) {
81 coff_aux_weak_external *WE =
82 reinterpret_cast<coff_aux_weak_external *>(Sym.AuxData[0].Opaque);
83 const Symbol *Target = Obj.findSymbol(*Sym.WeakTargetSymbolId);
84 if (Target == nullptr)
85 return createStringError(object_error::invalid_symbol_index,
86 "symbol '%s' is missing its weak target",
87 Sym.Name.str().c_str());
88 WE->TagIndex = Target->RawIndex;
91 return Error::success();
94 void COFFWriter::layoutSections() {
95 for (auto &S : Obj.getMutableSections()) {
96 if (S.Header.SizeOfRawData > 0)
97 S.Header.PointerToRawData = FileSize;
98 FileSize += S.Header.SizeOfRawData; // For executables, this is already
99 // aligned to FileAlignment.
100 if (S.Relocs.size() >= 0xffff) {
101 S.Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
102 S.Header.NumberOfRelocations = 0xffff;
103 S.Header.PointerToRelocations = FileSize;
104 FileSize += sizeof(coff_relocation);
106 S.Header.NumberOfRelocations = S.Relocs.size();
107 S.Header.PointerToRelocations = S.Relocs.size() ? FileSize : 0;
110 FileSize += S.Relocs.size() * sizeof(coff_relocation);
111 FileSize = alignTo(FileSize, FileAlignment);
113 if (S.Header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
114 SizeOfInitializedData += S.Header.SizeOfRawData;
118 size_t COFFWriter::finalizeStringTable() {
119 for (const auto &S : Obj.getSections())
120 if (S.Name.size() > COFF::NameSize)
121 StrTabBuilder.add(S.Name);
123 for (const auto &S : Obj.getSymbols())
124 if (S.Name.size() > COFF::NameSize)
125 StrTabBuilder.add(S.Name);
127 StrTabBuilder.finalize();
129 for (auto &S : Obj.getMutableSections()) {
130 memset(S.Header.Name, 0, sizeof(S.Header.Name));
131 if (S.Name.size() > COFF::NameSize) {
132 snprintf(S.Header.Name, sizeof(S.Header.Name), "/%d",
133 (int)StrTabBuilder.getOffset(S.Name));
135 memcpy(S.Header.Name, S.Name.data(), S.Name.size());
138 for (auto &S : Obj.getMutableSymbols()) {
139 if (S.Name.size() > COFF::NameSize) {
140 S.Sym.Name.Offset.Zeroes = 0;
141 S.Sym.Name.Offset.Offset = StrTabBuilder.getOffset(S.Name);
143 strncpy(S.Sym.Name.ShortName, S.Name.data(), COFF::NameSize);
146 return StrTabBuilder.getSize();
149 template <class SymbolTy>
150 std::pair<size_t, size_t> COFFWriter::finalizeSymbolTable() {
151 size_t RawSymIndex = 0;
152 for (auto &S : Obj.getMutableSymbols()) {
153 // Symbols normally have NumberOfAuxSymbols set correctly all the time.
154 // For file symbols, we need to know the output file's symbol size to be
155 // able to calculate the number of slots it occupies.
156 if (!S.AuxFile.empty())
157 S.Sym.NumberOfAuxSymbols =
158 alignTo(S.AuxFile.size(), sizeof(SymbolTy)) / sizeof(SymbolTy);
159 S.RawIndex = RawSymIndex;
160 RawSymIndex += 1 + S.Sym.NumberOfAuxSymbols;
162 return std::make_pair(RawSymIndex * sizeof(SymbolTy), sizeof(SymbolTy));
165 Error COFFWriter::finalize(bool IsBigObj) {
166 size_t SymTabSize, SymbolSize;
167 std::tie(SymTabSize, SymbolSize) = IsBigObj
168 ? finalizeSymbolTable<coff_symbol32>()
169 : finalizeSymbolTable<coff_symbol16>();
171 if (Error E = finalizeRelocTargets())
173 if (Error E = finalizeSymbolContents())
176 size_t SizeOfHeaders = 0;
178 size_t PeHeaderSize = 0;
180 Obj.DosHeader.AddressOfNewExeHeader =
181 sizeof(Obj.DosHeader) + Obj.DosStub.size();
182 SizeOfHeaders += Obj.DosHeader.AddressOfNewExeHeader + sizeof(PEMagic);
184 FileAlignment = Obj.PeHeader.FileAlignment;
185 Obj.PeHeader.NumberOfRvaAndSize = Obj.DataDirectories.size();
187 PeHeaderSize = Obj.Is64 ? sizeof(pe32plus_header) : sizeof(pe32_header);
189 PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
191 Obj.CoffFileHeader.NumberOfSections = Obj.getSections().size();
193 IsBigObj ? sizeof(coff_bigobj_file_header) : sizeof(coff_file_header);
194 SizeOfHeaders += sizeof(coff_section) * Obj.getSections().size();
195 SizeOfHeaders = alignTo(SizeOfHeaders, FileAlignment);
197 Obj.CoffFileHeader.SizeOfOptionalHeader =
198 PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
200 FileSize = SizeOfHeaders;
201 SizeOfInitializedData = 0;
206 Obj.PeHeader.SizeOfHeaders = SizeOfHeaders;
207 Obj.PeHeader.SizeOfInitializedData = SizeOfInitializedData;
209 if (!Obj.getSections().empty()) {
210 const Section &S = Obj.getSections().back();
211 Obj.PeHeader.SizeOfImage =
212 alignTo(S.Header.VirtualAddress + S.Header.VirtualSize,
213 Obj.PeHeader.SectionAlignment);
216 // If the PE header had a checksum, clear it, since it isn't valid
217 // any longer. (We don't calculate a new one.)
218 Obj.PeHeader.CheckSum = 0;
221 size_t StrTabSize = finalizeStringTable();
223 size_t PointerToSymbolTable = FileSize;
224 // StrTabSize <= 4 is the size of an empty string table, only consisting
225 // of the length field.
226 if (SymTabSize == 0 && StrTabSize <= 4 && Obj.IsPE) {
227 // For executables, don't point to the symbol table and skip writing
228 // the length field, if both the symbol and string tables are empty.
229 PointerToSymbolTable = 0;
233 size_t NumRawSymbols = SymTabSize / SymbolSize;
234 Obj.CoffFileHeader.PointerToSymbolTable = PointerToSymbolTable;
235 Obj.CoffFileHeader.NumberOfSymbols = NumRawSymbols;
236 FileSize += SymTabSize + StrTabSize;
237 FileSize = alignTo(FileSize, FileAlignment);
239 return Error::success();
242 void COFFWriter::writeHeaders(bool IsBigObj) {
243 uint8_t *Ptr = Buf.getBufferStart();
245 memcpy(Ptr, &Obj.DosHeader, sizeof(Obj.DosHeader));
246 Ptr += sizeof(Obj.DosHeader);
247 memcpy(Ptr, Obj.DosStub.data(), Obj.DosStub.size());
248 Ptr += Obj.DosStub.size();
249 memcpy(Ptr, PEMagic, sizeof(PEMagic));
250 Ptr += sizeof(PEMagic);
253 memcpy(Ptr, &Obj.CoffFileHeader, sizeof(Obj.CoffFileHeader));
254 Ptr += sizeof(Obj.CoffFileHeader);
256 // Generate a coff_bigobj_file_header, filling it in with the values
257 // from Obj.CoffFileHeader. All extra fields that don't exist in
258 // coff_file_header can be set to hardcoded values.
259 coff_bigobj_file_header BigObjHeader;
260 BigObjHeader.Sig1 = IMAGE_FILE_MACHINE_UNKNOWN;
261 BigObjHeader.Sig2 = 0xffff;
262 BigObjHeader.Version = BigObjHeader::MinBigObjectVersion;
263 BigObjHeader.Machine = Obj.CoffFileHeader.Machine;
264 BigObjHeader.TimeDateStamp = Obj.CoffFileHeader.TimeDateStamp;
265 memcpy(BigObjHeader.UUID, BigObjMagic, sizeof(BigObjMagic));
266 BigObjHeader.unused1 = 0;
267 BigObjHeader.unused2 = 0;
268 BigObjHeader.unused3 = 0;
269 BigObjHeader.unused4 = 0;
270 // The value in Obj.CoffFileHeader.NumberOfSections is truncated, thus
271 // get the original one instead.
272 BigObjHeader.NumberOfSections = Obj.getSections().size();
273 BigObjHeader.PointerToSymbolTable = Obj.CoffFileHeader.PointerToSymbolTable;
274 BigObjHeader.NumberOfSymbols = Obj.CoffFileHeader.NumberOfSymbols;
276 memcpy(Ptr, &BigObjHeader, sizeof(BigObjHeader));
277 Ptr += sizeof(BigObjHeader);
281 memcpy(Ptr, &Obj.PeHeader, sizeof(Obj.PeHeader));
282 Ptr += sizeof(Obj.PeHeader);
284 pe32_header PeHeader;
285 copyPeHeader(PeHeader, Obj.PeHeader);
286 // The pe32plus_header (stored in Object) lacks the BaseOfData field.
287 PeHeader.BaseOfData = Obj.BaseOfData;
289 memcpy(Ptr, &PeHeader, sizeof(PeHeader));
290 Ptr += sizeof(PeHeader);
292 for (const auto &DD : Obj.DataDirectories) {
293 memcpy(Ptr, &DD, sizeof(DD));
297 for (const auto &S : Obj.getSections()) {
298 memcpy(Ptr, &S.Header, sizeof(S.Header));
299 Ptr += sizeof(S.Header);
303 void COFFWriter::writeSections() {
304 for (const auto &S : Obj.getSections()) {
305 uint8_t *Ptr = Buf.getBufferStart() + S.Header.PointerToRawData;
306 ArrayRef<uint8_t> Contents = S.getContents();
307 std::copy(Contents.begin(), Contents.end(), Ptr);
309 // For executable sections, pad the remainder of the raw data size with
310 // 0xcc, which is int3 on x86.
311 if ((S.Header.Characteristics & IMAGE_SCN_CNT_CODE) &&
312 S.Header.SizeOfRawData > Contents.size())
313 memset(Ptr + Contents.size(), 0xcc,
314 S.Header.SizeOfRawData - Contents.size());
316 Ptr += S.Header.SizeOfRawData;
318 if (S.Relocs.size() >= 0xffff) {
319 object::coff_relocation R;
320 R.VirtualAddress = S.Relocs.size() + 1;
321 R.SymbolTableIndex = 0;
323 memcpy(Ptr, &R, sizeof(R));
326 for (const auto &R : S.Relocs) {
327 memcpy(Ptr, &R.Reloc, sizeof(R.Reloc));
328 Ptr += sizeof(R.Reloc);
333 template <class SymbolTy> void COFFWriter::writeSymbolStringTables() {
334 uint8_t *Ptr = Buf.getBufferStart() + Obj.CoffFileHeader.PointerToSymbolTable;
335 for (const auto &S : Obj.getSymbols()) {
336 // Convert symbols back to the right size, from coff_symbol32.
337 copySymbol<SymbolTy, coff_symbol32>(*reinterpret_cast<SymbolTy *>(Ptr),
339 Ptr += sizeof(SymbolTy);
340 if (!S.AuxFile.empty()) {
341 // For file symbols, just write the string into the aux symbol slots,
342 // assuming that the unwritten parts are initialized to zero in the memory
344 std::copy(S.AuxFile.begin(), S.AuxFile.end(), Ptr);
345 Ptr += S.Sym.NumberOfAuxSymbols * sizeof(SymbolTy);
347 // For other auxillary symbols, write their opaque payload into one symbol
348 // table slot each. For big object files, the symbols are larger than the
349 // opaque auxillary symbol struct and we leave padding at the end of each
351 for (const AuxSymbol &AuxSym : S.AuxData) {
352 ArrayRef<uint8_t> Ref = AuxSym.getRef();
353 std::copy(Ref.begin(), Ref.end(), Ptr);
354 Ptr += sizeof(SymbolTy);
358 if (StrTabBuilder.getSize() > 4 || !Obj.IsPE) {
359 // Always write a string table in object files, even an empty one.
360 StrTabBuilder.write(Ptr);
361 Ptr += StrTabBuilder.getSize();
365 Error COFFWriter::write(bool IsBigObj) {
366 if (Error E = finalize(IsBigObj))
369 if (Error E = Buf.allocate(FileSize))
372 writeHeaders(IsBigObj);
375 writeSymbolStringTables<coff_symbol32>();
377 writeSymbolStringTables<coff_symbol16>();
380 if (Error E = patchDebugDirectory())
386 // Locate which sections contain the debug directories, iterate over all
387 // the debug_directory structs in there, and set the PointerToRawData field
388 // in all of them, according to their new physical location in the file.
389 Error COFFWriter::patchDebugDirectory() {
390 if (Obj.DataDirectories.size() < DEBUG_DIRECTORY)
391 return Error::success();
392 const data_directory *Dir = &Obj.DataDirectories[DEBUG_DIRECTORY];
394 return Error::success();
395 for (const auto &S : Obj.getSections()) {
396 if (Dir->RelativeVirtualAddress >= S.Header.VirtualAddress &&
397 Dir->RelativeVirtualAddress <
398 S.Header.VirtualAddress + S.Header.SizeOfRawData) {
399 if (Dir->RelativeVirtualAddress + Dir->Size >
400 S.Header.VirtualAddress + S.Header.SizeOfRawData)
401 return createStringError(object_error::parse_failed,
402 "debug directory extends past end of section");
404 size_t Offset = Dir->RelativeVirtualAddress - S.Header.VirtualAddress;
405 uint8_t *Ptr = Buf.getBufferStart() + S.Header.PointerToRawData + Offset;
406 uint8_t *End = Ptr + Dir->Size;
408 debug_directory *Debug = reinterpret_cast<debug_directory *>(Ptr);
409 Debug->PointerToRawData =
410 S.Header.PointerToRawData + Offset + sizeof(debug_directory);
411 Ptr += sizeof(debug_directory) + Debug->SizeOfData;
412 Offset += sizeof(debug_directory) + Debug->SizeOfData;
414 // Debug directory found and patched, all done.
415 return Error::success();
418 return createStringError(object_error::parse_failed,
419 "debug directory not found");
422 Error COFFWriter::write() {
423 bool IsBigObj = Obj.getSections().size() > MaxNumberOfSections16;
424 if (IsBigObj && Obj.IsPE)
425 return createStringError(object_error::parse_failed,
426 "too many sections for executable");
427 return write(IsBigObj);
430 } // end namespace coff
431 } // end namespace objcopy
432 } // end namespace llvm