LLVM 24.0.0git
COFFObjcopy.cpp
Go to the documentation of this file.
1//===- COFFObjcopy.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
10#include "COFFObject.h"
11#include "COFFReader.h"
12#include "COFFWriter.h"
15
17#include "llvm/Object/Binary.h"
18#include "llvm/Object/COFF.h"
19#include "llvm/Support/CRC.h"
20#include "llvm/Support/Errc.h"
21#include "llvm/Support/Path.h"
22#include <cassert>
23
24namespace llvm {
25namespace objcopy {
26namespace coff {
27
28using namespace object;
29using namespace COFF;
30
31static bool isDebugSection(const Section &Sec) {
32 return Sec.Name.starts_with(".debug");
33}
34
35// The COMDAT selection is stored in the section definition symbol's aux
36// record, so it must be kept even if no relocation references it.
37static bool isComdatSectionDefinition(const Object &Obj, const Symbol &Sym) {
38 if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC && Sym.Sym.Value == 0 &&
39 Sym.Sym.NumberOfAuxSymbols != 0 && Sym.TargetSectionId > 0) {
40 // Looks like a section definition symbol, check if it is a COMDAT.
41 const Section *Sec = Obj.findSection(Sym.TargetSectionId);
42 return Sec && Sec->Name == Sym.Name &&
44 }
45 return false;
46}
47
48static uint64_t getNextRVA(const Object &Obj) {
49 if (Obj.getSections().empty())
50 return 0;
51 const Section &Last = Obj.getSections().back();
52 return alignTo(Last.Header.VirtualAddress + Last.Header.VirtualSize,
53 Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
54}
55
60 if (!LinkTargetOrErr)
61 return createFileError(File, LinkTargetOrErr.getError());
62 auto LinkTarget = std::move(*LinkTargetOrErr);
63 uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer()));
64
66 size_t CRCPos = alignTo(FileName.size() + 1, 4);
67 std::vector<uint8_t> Data(CRCPos + 4);
68 memcpy(Data.data(), FileName.data(), FileName.size());
69 support::endian::write32le(Data.data() + CRCPos, CRC32);
70 return Data;
71}
72
73// Adds named section with given contents to the object.
74static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,
78
79 Section Sec;
80 Sec.setOwnedContents(Contents);
81 Sec.Name = Name;
82 Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;
83 Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;
84 Sec.Header.SizeOfRawData =
85 NeedVA ? alignTo(Sec.Header.VirtualSize,
86 Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)
87 : Sec.getContents().size();
88 // Sec.Header.PointerToRawData is filled in by the writer.
89 Sec.Header.PointerToRelocations = 0;
90 Sec.Header.PointerToLinenumbers = 0;
91 // Sec.Header.NumberOfRelocations is filled in by the writer.
92 Sec.Header.NumberOfLinenumbers = 0;
93 Sec.Header.Characteristics = Characteristics;
94
95 Obj.addSections(Sec);
96}
97
98static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
101 if (!Contents)
102 return Contents.takeError();
103
104 addSection(Obj, ".gnu_debuglink", *Contents,
107
108 return Error::success();
109}
110
112 // Need to preserve alignment flags.
113 const uint32_t PreserveMask =
121
122 // Setup new section characteristics based on the flags provided in command
123 // line.
124 uint32_t NewCharacteristics = (OldChar & PreserveMask) | IMAGE_SCN_MEM_READ;
125
126 if ((AllFlags & SectionFlag::SecAlloc) && !(AllFlags & SectionFlag::SecLoad))
127 NewCharacteristics |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
128 if (AllFlags & SectionFlag::SecNoload)
129 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
130 if (!(AllFlags & SectionFlag::SecReadonly))
131 NewCharacteristics |= IMAGE_SCN_MEM_WRITE;
132 if (AllFlags & SectionFlag::SecDebug)
133 NewCharacteristics |=
135 if (AllFlags & SectionFlag::SecCode)
136 NewCharacteristics |= IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
137 if (AllFlags & SectionFlag::SecData)
138 NewCharacteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
139 if (AllFlags & SectionFlag::SecShare)
140 NewCharacteristics |= IMAGE_SCN_MEM_SHARED;
141 if (AllFlags & SectionFlag::SecExclude)
142 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
143
144 return NewCharacteristics;
145}
146
148 for (const coff::Section &Section : O.getSections()) {
149 if (Section.Name != SectionName)
150 continue;
151
153
154 std::unique_ptr<FileOutputBuffer> Buffer;
155 if (auto B = FileOutputBuffer::create(FileName, Contents.size()))
156 Buffer = std::move(*B);
157 else
158 return B.takeError();
159
160 llvm::copy(Contents, Buffer->getBufferStart());
161 if (Error E = Buffer->commit())
162 return E;
163
164 return Error::success();
165 }
166 return createStringError(object_error::parse_failed, "section '%s' not found",
167 SectionName.str().c_str());
168}
169
170static Error handleArgs(const CommonConfig &Config,
171 const COFFConfig &COFFConfig, Object &Obj) {
172 for (StringRef Op : Config.DumpSection) {
173 auto [Section, File] = Op.split('=');
174 if (Error E = dumpSection(Obj, Section, File))
175 return E;
176 }
177
178 // Perform the actual section removals.
179 Obj.removeSections([&Config](const Section &Sec) {
180 // Contrary to --only-keep-debug, --only-section fully removes sections that
181 // aren't mentioned.
182 if (!Config.OnlySection.empty() && !Config.OnlySection.matches(Sec.Name))
183 return true;
184
185 if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
186 Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {
187 if (isDebugSection(Sec) &&
189 return true;
190 }
191
192 if (Config.ToRemove.matches(Sec.Name))
193 return true;
194
195 return false;
196 });
197
198 if (Config.OnlyKeepDebug) {
199 const data_directory *DebugDir =
200 Obj.DataDirectories.size() > DEBUG_DIRECTORY
201 ? &Obj.DataDirectories[DEBUG_DIRECTORY]
202 : nullptr;
203 // For --only-keep-debug, we keep all other sections, but remove their
204 // content. The VirtualSize field in the section header is kept intact.
205 Obj.truncateSections([DebugDir](const Section &Sec) {
206 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
207 !(DebugDir && DebugDir->Size > 0 &&
209 DebugDir->RelativeVirtualAddress <
211 ((Sec.Header.Characteristics &
213 });
214 }
215
216 // StripAll removes all symbols and thus also removes all relocations.
217 if (Config.StripAll || Config.StripAllGNU)
218 for (Section &Sec : Obj.getMutableSections())
219 Sec.Relocs.clear();
220
221 // If we need to do per-symbol removals, initialize the Referenced field.
222 if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||
223 !Config.SymbolsToRemove.empty())
224 if (Error E = Obj.markSymbols())
225 return E;
226
227 for (Symbol &Sym : Obj.getMutableSymbols()) {
228 auto I = Config.SymbolsToRename.find(Sym.Name);
229 if (I != Config.SymbolsToRename.end())
230 Sym.Name = I->getValue();
231 }
232
233 auto ToRemove = [&](const Symbol &Sym) -> Expected<bool> {
234 // For StripAll, all relocations have been stripped and we remove all
235 // symbols.
236 if (Config.StripAll || Config.StripAllGNU)
237 return true;
238
239 if (Config.SymbolsToRemove.matches(Sym.Name)) {
240 // Explicitly removing a referenced symbol is an error.
241 if (Sym.Referenced)
243 "'" + Config.OutputFilename +
244 "': not stripping symbol '" + Sym.Name +
245 "' because it is named in a relocation");
246 return true;
247 }
248
249 if (isComdatSectionDefinition(Obj, Sym))
250 return false;
251
252 if (!Sym.Referenced) {
253 // With --strip-unneeded, GNU objcopy removes all unreferenced local
254 // symbols, and any unreferenced undefined external.
255 // With --strip-unneeded-symbol we strip only specific unreferenced
256 // local symbol instead of removing all of such.
257 if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||
258 Sym.Sym.SectionNumber == 0)
259 if (Config.StripUnneeded ||
260 Config.UnneededSymbolsToRemove.matches(Sym.Name))
261 return true;
262
263 // GNU objcopy keeps referenced local symbols and external symbols
264 // if --discard-all is set, similar to what --strip-unneeded does,
265 // but undefined local symbols are kept when --discard-all is set.
266 if (Config.DiscardMode == DiscardType::All &&
267 Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&
268 Sym.Sym.SectionNumber != 0)
269 return true;
270 }
271
272 return false;
273 };
274
275 // Actually do removals of symbols.
276 if (Error Err = Obj.removeSymbols(ToRemove))
277 return Err;
278
279 if (!Config.SetSectionFlags.empty())
280 for (Section &Sec : Obj.getMutableSections()) {
281 const auto It = Config.SetSectionFlags.find(Sec.Name);
282 if (It != Config.SetSectionFlags.end())
284 It->second.NewFlags, Sec.Header.Characteristics);
285 }
286
287 for (const NewSectionInfo &NewSection : Config.AddSection) {
289 const auto It = Config.SetSectionFlags.find(NewSection.SectionName);
290 if (It != Config.SetSectionFlags.end())
291 Characteristics = flagsToCharacteristics(It->second.NewFlags, 0);
292 else
294
295 addSection(Obj, NewSection.SectionName,
296 ArrayRef(reinterpret_cast<const uint8_t *>(
297 NewSection.SectionData->getBufferStart()),
298 NewSection.SectionData->getBufferSize()),
300 }
301
302 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
303 auto It = llvm::find_if(Obj.getMutableSections(), [&](auto &Sec) {
304 return Sec.Name == NewSection.SectionName;
305 });
306 if (It == Obj.getMutableSections().end())
308 "could not find section with name '%s'",
309 NewSection.SectionName.str().c_str());
310 size_t ContentSize = It->getContents().size();
311 if (!ContentSize)
312 return createStringError(
314 "section '%s' cannot be updated because it does not have contents",
315 NewSection.SectionName.str().c_str());
316 if (ContentSize < NewSection.SectionData->getBufferSize())
317 return createStringError(
319 "new section cannot be larger than previous section");
320 It->setOwnedContents({NewSection.SectionData->getBufferStart(),
321 NewSection.SectionData->getBufferEnd()});
322 }
323
324 if (!Config.AddGnuDebugLink.empty())
325 if (Error E = addGnuDebugLink(Obj, Config.AddGnuDebugLink))
326 return E;
327
330 if (!Obj.IsPE)
331 return createStringError(
333 "'" + Config.OutputFilename +
334 "': unable to set subsystem on a relocatable object file");
336 Obj.PeHeader.Subsystem = *COFFConfig.Subsystem;
338 Obj.PeHeader.MajorSubsystemVersion = *COFFConfig.MajorSubsystemVersion;
340 Obj.PeHeader.MinorSubsystemVersion = *COFFConfig.MinorSubsystemVersion;
341 }
342
343 return Error::success();
344}
345
348 raw_ostream &Out) {
349 COFFReader Reader(In);
350 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
351 if (!ObjOrErr)
352 return createFileError(Config.InputFilename, ObjOrErr.takeError());
353 Object *Obj = ObjOrErr->get();
354 assert(Obj && "Unable to deserialize COFF object");
355 if (Error E = handleArgs(Config, COFFConfig, *Obj))
356 return createFileError(Config.InputFilename, std::move(E));
357 COFFWriter Writer(*Obj, Out);
358 if (Error E = Writer.write())
359 return createFileError(Config.OutputFilename, std::move(E));
360 return Error::success();
361}
362
363} // end namespace coff
364} // end namespace objcopy
365} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define I(x, y, z)
Definition MD5.cpp:57
This file contains some functions that are useful when dealing with strings.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static LLVM_ABI Expected< std::unique_ptr< FileOutputBuffer > > create(StringRef FilePath, size_t Size, unsigned Flags=0)
Factory method to create an OutputBuffer object which manages a read/write buffer of the specified si...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
bool matches(StringRef S) const
Expected< std::unique_ptr< Object > > create() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ IMAGE_SCN_ALIGN_64BYTES
Definition COFF.h:321
@ IMAGE_SCN_ALIGN_128BYTES
Definition COFF.h:322
@ IMAGE_SCN_MEM_SHARED
Definition COFF.h:334
@ IMAGE_SCN_ALIGN_256BYTES
Definition COFF.h:323
@ IMAGE_SCN_ALIGN_1024BYTES
Definition COFF.h:325
@ IMAGE_SCN_ALIGN_1BYTES
Definition COFF.h:315
@ IMAGE_SCN_LNK_REMOVE
Definition COFF.h:308
@ IMAGE_SCN_CNT_CODE
Definition COFF.h:303
@ IMAGE_SCN_MEM_READ
Definition COFF.h:336
@ IMAGE_SCN_MEM_EXECUTE
Definition COFF.h:335
@ IMAGE_SCN_ALIGN_512BYTES
Definition COFF.h:324
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition COFF.h:305
@ IMAGE_SCN_MEM_DISCARDABLE
Definition COFF.h:331
@ IMAGE_SCN_ALIGN_4096BYTES
Definition COFF.h:327
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_ALIGN_8192BYTES
Definition COFF.h:328
@ IMAGE_SCN_ALIGN_16BYTES
Definition COFF.h:319
@ IMAGE_SCN_LNK_COMDAT
Definition COFF.h:309
@ IMAGE_SCN_ALIGN_8BYTES
Definition COFF.h:318
@ IMAGE_SCN_ALIGN_4BYTES
Definition COFF.h:317
@ IMAGE_SCN_ALIGN_32BYTES
Definition COFF.h:320
@ IMAGE_SCN_ALIGN_2BYTES
Definition COFF.h:316
@ IMAGE_SCN_ALIGN_2048BYTES
Definition COFF.h:326
@ IMAGE_SCN_MEM_WRITE
Definition COFF.h:337
@ DEBUG_DIRECTORY
Definition COFF.h:637
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition COFF.h:225
Characteristics
Definition COFF.h:138
static bool isDebugSection(const Section &Sec)
LLVM_ABI Error executeObjcopyOnBinary(const CommonConfig &Config, const COFFConfig &, object::COFFObjectFile &In, raw_ostream &Out)
Apply the transformations described by Config and COFFConfig to In and writes the result into Out.
static bool isComdatSectionDefinition(const Object &Obj, const Symbol &Sym)
static void addSection(Object &Obj, StringRef Name, ArrayRef< uint8_t > Contents, uint32_t Characteristics)
static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar)
static Error dumpSection(Object &O, StringRef SectionName, StringRef FileName)
static uint64_t getNextRVA(const Object &Obj)
static Error handleArgs(const CommonConfig &Config, const COFFConfig &COFFConfig, Object &Obj)
static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile)
static Expected< std::vector< uint8_t > > createGnuDebugLinkSectionContents(StringRef File)
void write32le(void *P, uint32_t V)
Definition Endian.h:455
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ invalid_argument
Definition Errc.h:56
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
LLVM_ABI uint32_t crc32(ArrayRef< uint8_t > Data)
Definition CRC.cpp:101
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
std::optional< unsigned > MinorSubsystemVersion
Definition COFFConfig.h:21
std::optional< unsigned > Subsystem
Definition COFFConfig.h:19
std::optional< unsigned > MajorSubsystemVersion
Definition COFFConfig.h:20
SmallVector< NewSectionInfo, 0 > UpdateSection
SmallVector< StringRef, 0 > DumpSection
StringMap< SectionFlagsUpdate > SetSectionFlags
SmallVector< NewSectionInfo, 0 > AddSection
StringMap< StringRef > SymbolsToRename
std::shared_ptr< MemoryBuffer > SectionData
void setOwnedContents(std::vector< uint8_t > &&Data)
Definition COFFObject.h:53
object::coff_section Header
Definition COFFObject.h:36
std::vector< Relocation > Relocs
Definition COFFObject.h:37
ArrayRef< uint8_t > getContents() const
Definition COFFObject.h:42
object::coff_symbol32 Sym
Definition COFFObject.h:83
support::ulittle32_t Characteristics
Definition COFF.h:459
support::ulittle32_t SizeOfRawData
Definition COFF.h:453
support::ulittle32_t VirtualAddress
Definition COFF.h:452
support::ulittle32_t Value
Definition COFF.h:261
uint8_t NumberOfAuxSymbols
Definition COFF.h:267
support::ulittle32_t RelativeVirtualAddress
Definition COFF.h:178
support::ulittle32_t Size
Definition COFF.h:179