]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/tools/llvm-objcopy/COFF/Writer.cpp
Fix a memory leak in if_delgroups() introduced in r334118.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / tools / llvm-objcopy / COFF / Writer.cpp
1 //===- Writer.cpp ---------------------------------------------------------===//
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 #include "Writer.h"
10 #include "Object.h"
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"
16 #include <cstddef>
17 #include <cstdint>
18
19 namespace llvm {
20 namespace objcopy {
21 namespace coff {
22
23 using namespace object;
24 using namespace COFF;
25
26 Error COFFWriter::finalizeRelocTargets() {
27   for (Section &Sec : Obj.getMutableSections()) {
28     for (Relocation &R : Sec.Relocs) {
29       const Symbol *Sym = Obj.findSymbol(R.Target);
30       if (Sym == nullptr)
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;
35     }
36   }
37   return Error::success();
38 }
39
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);
46     } else {
47       const Section *Sec = Obj.findSection(Sym.TargetSectionId);
48       if (Sec == nullptr)
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;
53
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;
64         } else {
65           Sec = Obj.findSection(Sym.AssociativeComdatTargetSectionId);
66           if (Sec == nullptr)
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;
72         }
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);
76       }
77     }
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;
89     }
90   }
91   return Error::success();
92 }
93
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);
105
106     if (S.Header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
107       SizeOfInitializedData += S.Header.SizeOfRawData;
108   }
109 }
110
111 size_t COFFWriter::finalizeStringTable() {
112   for (const auto &S : Obj.getSections())
113     if (S.Name.size() > COFF::NameSize)
114       StrTabBuilder.add(S.Name);
115
116   for (const auto &S : Obj.getSymbols())
117     if (S.Name.size() > COFF::NameSize)
118       StrTabBuilder.add(S.Name);
119
120   StrTabBuilder.finalize();
121
122   for (auto &S : Obj.getMutableSections()) {
123     if (S.Name.size() > COFF::NameSize) {
124       memset(S.Header.Name, 0, sizeof(S.Header.Name));
125       snprintf(S.Header.Name, sizeof(S.Header.Name), "/%d",
126                (int)StrTabBuilder.getOffset(S.Name));
127     } else {
128       strncpy(S.Header.Name, S.Name.data(), COFF::NameSize);
129     }
130   }
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);
135     } else {
136       strncpy(S.Sym.Name.ShortName, S.Name.data(), COFF::NameSize);
137     }
138   }
139   return StrTabBuilder.getSize();
140 }
141
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;
154   }
155   return std::make_pair(RawSymIndex * sizeof(SymbolTy), sizeof(SymbolTy));
156 }
157
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>();
163
164   if (Error E = finalizeRelocTargets())
165     return E;
166   if (Error E = finalizeSymbolContents())
167     return E;
168
169   size_t SizeOfHeaders = 0;
170   FileAlignment = 1;
171   size_t PeHeaderSize = 0;
172   if (Obj.IsPE) {
173     Obj.DosHeader.AddressOfNewExeHeader =
174         sizeof(Obj.DosHeader) + Obj.DosStub.size();
175     SizeOfHeaders += Obj.DosHeader.AddressOfNewExeHeader + sizeof(PEMagic);
176
177     FileAlignment = Obj.PeHeader.FileAlignment;
178     Obj.PeHeader.NumberOfRvaAndSize = Obj.DataDirectories.size();
179
180     PeHeaderSize = Obj.Is64 ? sizeof(pe32plus_header) : sizeof(pe32_header);
181     SizeOfHeaders +=
182         PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
183   }
184   Obj.CoffFileHeader.NumberOfSections = Obj.getSections().size();
185   SizeOfHeaders +=
186       IsBigObj ? sizeof(coff_bigobj_file_header) : sizeof(coff_file_header);
187   SizeOfHeaders += sizeof(coff_section) * Obj.getSections().size();
188   SizeOfHeaders = alignTo(SizeOfHeaders, FileAlignment);
189
190   Obj.CoffFileHeader.SizeOfOptionalHeader =
191       PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
192
193   FileSize = SizeOfHeaders;
194   SizeOfInitializedData = 0;
195
196   layoutSections();
197
198   if (Obj.IsPE) {
199     Obj.PeHeader.SizeOfHeaders = SizeOfHeaders;
200     Obj.PeHeader.SizeOfInitializedData = SizeOfInitializedData;
201
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);
207     }
208
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;
212   }
213
214   size_t StrTabSize = finalizeStringTable();
215
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;
223     StrTabSize = 0;
224   }
225
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);
231
232   return Error::success();
233 }
234
235 void COFFWriter::writeHeaders(bool IsBigObj) {
236   uint8_t *Ptr = Buf.getBufferStart();
237   if (Obj.IsPE) {
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);
244   }
245   if (!IsBigObj) {
246     memcpy(Ptr, &Obj.CoffFileHeader, sizeof(Obj.CoffFileHeader));
247     Ptr += sizeof(Obj.CoffFileHeader);
248   } else {
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;
268
269     memcpy(Ptr, &BigObjHeader, sizeof(BigObjHeader));
270     Ptr += sizeof(BigObjHeader);
271   }
272   if (Obj.IsPE) {
273     if (Obj.Is64) {
274       memcpy(Ptr, &Obj.PeHeader, sizeof(Obj.PeHeader));
275       Ptr += sizeof(Obj.PeHeader);
276     } else {
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;
281
282       memcpy(Ptr, &PeHeader, sizeof(PeHeader));
283       Ptr += sizeof(PeHeader);
284     }
285     for (const auto &DD : Obj.DataDirectories) {
286       memcpy(Ptr, &DD, sizeof(DD));
287       Ptr += sizeof(DD);
288     }
289   }
290   for (const auto &S : Obj.getSections()) {
291     memcpy(Ptr, &S.Header, sizeof(S.Header));
292     Ptr += sizeof(S.Header);
293   }
294 }
295
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);
301
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());
308
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);
313     }
314   }
315 }
316
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),
322                                         S.Sym);
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
327       // mapped file.
328       std::copy(S.AuxFile.begin(), S.AuxFile.end(), Ptr);
329       Ptr += S.Sym.NumberOfAuxSymbols * sizeof(SymbolTy);
330     } else {
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
334       // entry.
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);
339       }
340     }
341   }
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();
346   }
347 }
348
349 Error COFFWriter::write(bool IsBigObj) {
350   if (Error E = finalize(IsBigObj))
351     return E;
352
353   if (Error E = Buf.allocate(FileSize))
354     return E;
355
356   writeHeaders(IsBigObj);
357   writeSections();
358   if (IsBigObj)
359     writeSymbolStringTables<coff_symbol32>();
360   else
361     writeSymbolStringTables<coff_symbol16>();
362
363   if (Obj.IsPE)
364     if (Error E = patchDebugDirectory())
365       return E;
366
367   return Buf.commit();
368 }
369
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];
377   if (Dir->Size <= 0)
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");
387
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;
391       while (Ptr < End) {
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;
397       }
398       // Debug directory found and patched, all done.
399       return Error::success();
400     }
401   }
402   return createStringError(object_error::parse_failed,
403                            "debug directory not found");
404 }
405
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);
412 }
413
414 } // end namespace coff
415 } // end namespace objcopy
416 } // end namespace llvm