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 S
.Header
.NumberOfRelocations
= S
.Relocs
.size();
101 S
.Header
.PointerToRelocations
=
102 S
.Header
.NumberOfRelocations
> 0 ? FileSize
: 0;
103 FileSize
+= S
.Relocs
.size() * sizeof(coff_relocation
);
104 FileSize
= alignTo(FileSize
, FileAlignment
);
106 if (S
.Header
.Characteristics
& IMAGE_SCN_CNT_INITIALIZED_DATA
)
107 SizeOfInitializedData
+= S
.Header
.SizeOfRawData
;
111 size_t COFFWriter::finalizeStringTable() {
112 for (const auto &S
: Obj
.getSections())
113 if (S
.Name
.size() > COFF::NameSize
)
114 StrTabBuilder
.add(S
.Name
);
116 for (const auto &S
: Obj
.getSymbols())
117 if (S
.Name
.size() > COFF::NameSize
)
118 StrTabBuilder
.add(S
.Name
);
120 StrTabBuilder
.finalize();
122 for (auto &S
: Obj
.getMutableSections()) {
123 memset(S
.Header
.Name
, 0, sizeof(S
.Header
.Name
));
124 if (S
.Name
.size() > COFF::NameSize
) {
125 snprintf(S
.Header
.Name
, sizeof(S
.Header
.Name
), "/%d",
126 (int)StrTabBuilder
.getOffset(S
.Name
));
128 memcpy(S
.Header
.Name
, S
.Name
.data(), S
.Name
.size());
131 for (auto &S
: Obj
.getMutableSymbols()) {
132 if (S
.Name
.size() > COFF::NameSize
) {
133 S
.Sym
.Name
.Offset
.Zeroes
= 0;
134 S
.Sym
.Name
.Offset
.Offset
= StrTabBuilder
.getOffset(S
.Name
);
136 strncpy(S
.Sym
.Name
.ShortName
, S
.Name
.data(), COFF::NameSize
);
139 return StrTabBuilder
.getSize();
142 template <class SymbolTy
>
143 std::pair
<size_t, size_t> COFFWriter::finalizeSymbolTable() {
144 size_t RawSymIndex
= 0;
145 for (auto &S
: Obj
.getMutableSymbols()) {
146 // Symbols normally have NumberOfAuxSymbols set correctly all the time.
147 // For file symbols, we need to know the output file's symbol size to be
148 // able to calculate the number of slots it occupies.
149 if (!S
.AuxFile
.empty())
150 S
.Sym
.NumberOfAuxSymbols
=
151 alignTo(S
.AuxFile
.size(), sizeof(SymbolTy
)) / sizeof(SymbolTy
);
152 S
.RawIndex
= RawSymIndex
;
153 RawSymIndex
+= 1 + S
.Sym
.NumberOfAuxSymbols
;
155 return std::make_pair(RawSymIndex
* sizeof(SymbolTy
), sizeof(SymbolTy
));
158 Error
COFFWriter::finalize(bool IsBigObj
) {
159 size_t SymTabSize
, SymbolSize
;
160 std::tie(SymTabSize
, SymbolSize
) = IsBigObj
161 ? finalizeSymbolTable
<coff_symbol32
>()
162 : finalizeSymbolTable
<coff_symbol16
>();
164 if (Error E
= finalizeRelocTargets())
166 if (Error E
= finalizeSymbolContents())
169 size_t SizeOfHeaders
= 0;
171 size_t PeHeaderSize
= 0;
173 Obj
.DosHeader
.AddressOfNewExeHeader
=
174 sizeof(Obj
.DosHeader
) + Obj
.DosStub
.size();
175 SizeOfHeaders
+= Obj
.DosHeader
.AddressOfNewExeHeader
+ sizeof(PEMagic
);
177 FileAlignment
= Obj
.PeHeader
.FileAlignment
;
178 Obj
.PeHeader
.NumberOfRvaAndSize
= Obj
.DataDirectories
.size();
180 PeHeaderSize
= Obj
.Is64
? sizeof(pe32plus_header
) : sizeof(pe32_header
);
182 PeHeaderSize
+ sizeof(data_directory
) * Obj
.DataDirectories
.size();
184 Obj
.CoffFileHeader
.NumberOfSections
= Obj
.getSections().size();
186 IsBigObj
? sizeof(coff_bigobj_file_header
) : sizeof(coff_file_header
);
187 SizeOfHeaders
+= sizeof(coff_section
) * Obj
.getSections().size();
188 SizeOfHeaders
= alignTo(SizeOfHeaders
, FileAlignment
);
190 Obj
.CoffFileHeader
.SizeOfOptionalHeader
=
191 PeHeaderSize
+ sizeof(data_directory
) * Obj
.DataDirectories
.size();
193 FileSize
= SizeOfHeaders
;
194 SizeOfInitializedData
= 0;
199 Obj
.PeHeader
.SizeOfHeaders
= SizeOfHeaders
;
200 Obj
.PeHeader
.SizeOfInitializedData
= SizeOfInitializedData
;
202 if (!Obj
.getSections().empty()) {
203 const Section
&S
= Obj
.getSections().back();
204 Obj
.PeHeader
.SizeOfImage
=
205 alignTo(S
.Header
.VirtualAddress
+ S
.Header
.VirtualSize
,
206 Obj
.PeHeader
.SectionAlignment
);
209 // If the PE header had a checksum, clear it, since it isn't valid
210 // any longer. (We don't calculate a new one.)
211 Obj
.PeHeader
.CheckSum
= 0;
214 size_t StrTabSize
= finalizeStringTable();
216 size_t PointerToSymbolTable
= FileSize
;
217 // StrTabSize <= 4 is the size of an empty string table, only consisting
218 // of the length field.
219 if (SymTabSize
== 0 && StrTabSize
<= 4 && Obj
.IsPE
) {
220 // For executables, don't point to the symbol table and skip writing
221 // the length field, if both the symbol and string tables are empty.
222 PointerToSymbolTable
= 0;
226 size_t NumRawSymbols
= SymTabSize
/ SymbolSize
;
227 Obj
.CoffFileHeader
.PointerToSymbolTable
= PointerToSymbolTable
;
228 Obj
.CoffFileHeader
.NumberOfSymbols
= NumRawSymbols
;
229 FileSize
+= SymTabSize
+ StrTabSize
;
230 FileSize
= alignTo(FileSize
, FileAlignment
);
232 return Error::success();
235 void COFFWriter::writeHeaders(bool IsBigObj
) {
236 uint8_t *Ptr
= Buf
.getBufferStart();
238 memcpy(Ptr
, &Obj
.DosHeader
, sizeof(Obj
.DosHeader
));
239 Ptr
+= sizeof(Obj
.DosHeader
);
240 memcpy(Ptr
, Obj
.DosStub
.data(), Obj
.DosStub
.size());
241 Ptr
+= Obj
.DosStub
.size();
242 memcpy(Ptr
, PEMagic
, sizeof(PEMagic
));
243 Ptr
+= sizeof(PEMagic
);
246 memcpy(Ptr
, &Obj
.CoffFileHeader
, sizeof(Obj
.CoffFileHeader
));
247 Ptr
+= sizeof(Obj
.CoffFileHeader
);
249 // Generate a coff_bigobj_file_header, filling it in with the values
250 // from Obj.CoffFileHeader. All extra fields that don't exist in
251 // coff_file_header can be set to hardcoded values.
252 coff_bigobj_file_header BigObjHeader
;
253 BigObjHeader
.Sig1
= IMAGE_FILE_MACHINE_UNKNOWN
;
254 BigObjHeader
.Sig2
= 0xffff;
255 BigObjHeader
.Version
= BigObjHeader::MinBigObjectVersion
;
256 BigObjHeader
.Machine
= Obj
.CoffFileHeader
.Machine
;
257 BigObjHeader
.TimeDateStamp
= Obj
.CoffFileHeader
.TimeDateStamp
;
258 memcpy(BigObjHeader
.UUID
, BigObjMagic
, sizeof(BigObjMagic
));
259 BigObjHeader
.unused1
= 0;
260 BigObjHeader
.unused2
= 0;
261 BigObjHeader
.unused3
= 0;
262 BigObjHeader
.unused4
= 0;
263 // The value in Obj.CoffFileHeader.NumberOfSections is truncated, thus
264 // get the original one instead.
265 BigObjHeader
.NumberOfSections
= Obj
.getSections().size();
266 BigObjHeader
.PointerToSymbolTable
= Obj
.CoffFileHeader
.PointerToSymbolTable
;
267 BigObjHeader
.NumberOfSymbols
= Obj
.CoffFileHeader
.NumberOfSymbols
;
269 memcpy(Ptr
, &BigObjHeader
, sizeof(BigObjHeader
));
270 Ptr
+= sizeof(BigObjHeader
);
274 memcpy(Ptr
, &Obj
.PeHeader
, sizeof(Obj
.PeHeader
));
275 Ptr
+= sizeof(Obj
.PeHeader
);
277 pe32_header PeHeader
;
278 copyPeHeader(PeHeader
, Obj
.PeHeader
);
279 // The pe32plus_header (stored in Object) lacks the BaseOfData field.
280 PeHeader
.BaseOfData
= Obj
.BaseOfData
;
282 memcpy(Ptr
, &PeHeader
, sizeof(PeHeader
));
283 Ptr
+= sizeof(PeHeader
);
285 for (const auto &DD
: Obj
.DataDirectories
) {
286 memcpy(Ptr
, &DD
, sizeof(DD
));
290 for (const auto &S
: Obj
.getSections()) {
291 memcpy(Ptr
, &S
.Header
, sizeof(S
.Header
));
292 Ptr
+= sizeof(S
.Header
);
296 void COFFWriter::writeSections() {
297 for (const auto &S
: Obj
.getSections()) {
298 uint8_t *Ptr
= Buf
.getBufferStart() + S
.Header
.PointerToRawData
;
299 ArrayRef
<uint8_t> Contents
= S
.getContents();
300 std::copy(Contents
.begin(), Contents
.end(), Ptr
);
302 // For executable sections, pad the remainder of the raw data size with
303 // 0xcc, which is int3 on x86.
304 if ((S
.Header
.Characteristics
& IMAGE_SCN_CNT_CODE
) &&
305 S
.Header
.SizeOfRawData
> Contents
.size())
306 memset(Ptr
+ Contents
.size(), 0xcc,
307 S
.Header
.SizeOfRawData
- Contents
.size());
309 Ptr
+= S
.Header
.SizeOfRawData
;
310 for (const auto &R
: S
.Relocs
) {
311 memcpy(Ptr
, &R
.Reloc
, sizeof(R
.Reloc
));
312 Ptr
+= sizeof(R
.Reloc
);
317 template <class SymbolTy
> void COFFWriter::writeSymbolStringTables() {
318 uint8_t *Ptr
= Buf
.getBufferStart() + Obj
.CoffFileHeader
.PointerToSymbolTable
;
319 for (const auto &S
: Obj
.getSymbols()) {
320 // Convert symbols back to the right size, from coff_symbol32.
321 copySymbol
<SymbolTy
, coff_symbol32
>(*reinterpret_cast<SymbolTy
*>(Ptr
),
323 Ptr
+= sizeof(SymbolTy
);
324 if (!S
.AuxFile
.empty()) {
325 // For file symbols, just write the string into the aux symbol slots,
326 // assuming that the unwritten parts are initialized to zero in the memory
328 std::copy(S
.AuxFile
.begin(), S
.AuxFile
.end(), Ptr
);
329 Ptr
+= S
.Sym
.NumberOfAuxSymbols
* sizeof(SymbolTy
);
331 // For other auxillary symbols, write their opaque payload into one symbol
332 // table slot each. For big object files, the symbols are larger than the
333 // opaque auxillary symbol struct and we leave padding at the end of each
335 for (const AuxSymbol
&AuxSym
: S
.AuxData
) {
336 ArrayRef
<uint8_t> Ref
= AuxSym
.getRef();
337 std::copy(Ref
.begin(), Ref
.end(), Ptr
);
338 Ptr
+= sizeof(SymbolTy
);
342 if (StrTabBuilder
.getSize() > 4 || !Obj
.IsPE
) {
343 // Always write a string table in object files, even an empty one.
344 StrTabBuilder
.write(Ptr
);
345 Ptr
+= StrTabBuilder
.getSize();
349 Error
COFFWriter::write(bool IsBigObj
) {
350 if (Error E
= finalize(IsBigObj
))
353 if (Error E
= Buf
.allocate(FileSize
))
356 writeHeaders(IsBigObj
);
359 writeSymbolStringTables
<coff_symbol32
>();
361 writeSymbolStringTables
<coff_symbol16
>();
364 if (Error E
= patchDebugDirectory())
370 // Locate which sections contain the debug directories, iterate over all
371 // the debug_directory structs in there, and set the PointerToRawData field
372 // in all of them, according to their new physical location in the file.
373 Error
COFFWriter::patchDebugDirectory() {
374 if (Obj
.DataDirectories
.size() < DEBUG_DIRECTORY
)
375 return Error::success();
376 const data_directory
*Dir
= &Obj
.DataDirectories
[DEBUG_DIRECTORY
];
378 return Error::success();
379 for (const auto &S
: Obj
.getSections()) {
380 if (Dir
->RelativeVirtualAddress
>= S
.Header
.VirtualAddress
&&
381 Dir
->RelativeVirtualAddress
<
382 S
.Header
.VirtualAddress
+ S
.Header
.SizeOfRawData
) {
383 if (Dir
->RelativeVirtualAddress
+ Dir
->Size
>
384 S
.Header
.VirtualAddress
+ S
.Header
.SizeOfRawData
)
385 return createStringError(object_error::parse_failed
,
386 "debug directory extends past end of section");
388 size_t Offset
= Dir
->RelativeVirtualAddress
- S
.Header
.VirtualAddress
;
389 uint8_t *Ptr
= Buf
.getBufferStart() + S
.Header
.PointerToRawData
+ Offset
;
390 uint8_t *End
= Ptr
+ Dir
->Size
;
392 debug_directory
*Debug
= reinterpret_cast<debug_directory
*>(Ptr
);
393 Debug
->PointerToRawData
=
394 S
.Header
.PointerToRawData
+ Offset
+ sizeof(debug_directory
);
395 Ptr
+= sizeof(debug_directory
) + Debug
->SizeOfData
;
396 Offset
+= sizeof(debug_directory
) + Debug
->SizeOfData
;
398 // Debug directory found and patched, all done.
399 return Error::success();
402 return createStringError(object_error::parse_failed
,
403 "debug directory not found");
406 Error
COFFWriter::write() {
407 bool IsBigObj
= Obj
.getSections().size() > MaxNumberOfSections16
;
408 if (IsBigObj
&& Obj
.IsPE
)
409 return createStringError(object_error::parse_failed
,
410 "too many sections for executable");
411 return write(IsBigObj
);
414 } // end namespace coff
415 } // end namespace objcopy
416 } // end namespace llvm