LLVM 20.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
35static uint64_t getNextRVA(const Object &Obj) {
36 if (Obj.getSections().empty())
37 return 0;
38 const Section &Last = Obj.getSections().back();
39 return alignTo(Last.Header.VirtualAddress + Last.Header.VirtualSize,
40 Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
41}
42
47 if (!LinkTargetOrErr)
48 return createFileError(File, LinkTargetOrErr.getError());
49 auto LinkTarget = std::move(*LinkTargetOrErr);
50 uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer()));
51
53 size_t CRCPos = alignTo(FileName.size() + 1, 4);
54 std::vector<uint8_t> Data(CRCPos + 4);
55 memcpy(Data.data(), FileName.data(), FileName.size());
56 support::endian::write32le(Data.data() + CRCPos, CRC32);
57 return Data;
58}
59
60// Adds named section with given contents to the object.
61static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,
65
66 Section Sec;
67 Sec.setOwnedContents(Contents);
68 Sec.Name = Name;
69 Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;
70 Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;
71 Sec.Header.SizeOfRawData =
72 NeedVA ? alignTo(Sec.Header.VirtualSize,
73 Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)
74 : Sec.getContents().size();
75 // Sec.Header.PointerToRawData is filled in by the writer.
76 Sec.Header.PointerToRelocations = 0;
77 Sec.Header.PointerToLinenumbers = 0;
78 // Sec.Header.NumberOfRelocations is filled in by the writer.
79 Sec.Header.NumberOfLinenumbers = 0;
80 Sec.Header.Characteristics = Characteristics;
81
82 Obj.addSections(Sec);
83}
84
85static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
88 if (!Contents)
89 return Contents.takeError();
90
91 addSection(Obj, ".gnu_debuglink", *Contents,
94
95 return Error::success();
96}
97
99 // Need to preserve alignment flags.
100 const uint32_t PreserveMask =
108
109 // Setup new section characteristics based on the flags provided in command
110 // line.
111 uint32_t NewCharacteristics = (OldChar & PreserveMask) | IMAGE_SCN_MEM_READ;
112
113 if ((AllFlags & SectionFlag::SecAlloc) && !(AllFlags & SectionFlag::SecLoad))
114 NewCharacteristics |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
115 if (AllFlags & SectionFlag::SecNoload)
116 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
117 if (!(AllFlags & SectionFlag::SecReadonly))
118 NewCharacteristics |= IMAGE_SCN_MEM_WRITE;
119 if (AllFlags & SectionFlag::SecDebug)
120 NewCharacteristics |=
122 if (AllFlags & SectionFlag::SecCode)
123 NewCharacteristics |= IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
124 if (AllFlags & SectionFlag::SecData)
125 NewCharacteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
126 if (AllFlags & SectionFlag::SecShare)
127 NewCharacteristics |= IMAGE_SCN_MEM_SHARED;
128 if (AllFlags & SectionFlag::SecExclude)
129 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
130
131 return NewCharacteristics;
132}
133
135 for (const coff::Section &Section : O.getSections()) {
136 if (Section.Name != SectionName)
137 continue;
138
140
141 std::unique_ptr<FileOutputBuffer> Buffer;
142 if (auto B = FileOutputBuffer::create(FileName, Contents.size()))
143 Buffer = std::move(*B);
144 else
145 return B.takeError();
146
147 llvm::copy(Contents, Buffer->getBufferStart());
148 if (Error E = Buffer->commit())
149 return E;
150
151 return Error::success();
152 }
153 return createStringError(object_error::parse_failed, "section '%s' not found",
154 SectionName.str().c_str());
155}
156
158 const COFFConfig &COFFConfig, Object &Obj) {
159 for (StringRef Op : Config.DumpSection) {
160 auto [Section, File] = Op.split('=');
161 if (Error E = dumpSection(Obj, Section, File))
162 return E;
163 }
164
165 // Perform the actual section removals.
166 Obj.removeSections([&Config](const Section &Sec) {
167 // Contrary to --only-keep-debug, --only-section fully removes sections that
168 // aren't mentioned.
169 if (!Config.OnlySection.empty() && !Config.OnlySection.matches(Sec.Name))
170 return true;
171
172 if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
173 Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {
174 if (isDebugSection(Sec) &&
175 (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
176 return true;
177 }
178
179 if (Config.ToRemove.matches(Sec.Name))
180 return true;
181
182 return false;
183 });
184
185 if (Config.OnlyKeepDebug) {
186 // For --only-keep-debug, we keep all other sections, but remove their
187 // content. The VirtualSize field in the section header is kept intact.
188 Obj.truncateSections([](const Section &Sec) {
189 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
190 ((Sec.Header.Characteristics &
192 });
193 }
194
195 // StripAll removes all symbols and thus also removes all relocations.
196 if (Config.StripAll || Config.StripAllGNU)
197 for (Section &Sec : Obj.getMutableSections())
198 Sec.Relocs.clear();
199
200 // If we need to do per-symbol removals, initialize the Referenced field.
201 if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||
202 !Config.SymbolsToRemove.empty())
203 if (Error E = Obj.markSymbols())
204 return E;
205
206 for (Symbol &Sym : Obj.getMutableSymbols()) {
207 auto I = Config.SymbolsToRename.find(Sym.Name);
208 if (I != Config.SymbolsToRename.end())
209 Sym.Name = I->getValue();
210 }
211
212 auto ToRemove = [&](const Symbol &Sym) -> Expected<bool> {
213 // For StripAll, all relocations have been stripped and we remove all
214 // symbols.
215 if (Config.StripAll || Config.StripAllGNU)
216 return true;
217
218 if (Config.SymbolsToRemove.matches(Sym.Name)) {
219 // Explicitly removing a referenced symbol is an error.
220 if (Sym.Referenced)
221 return createStringError(
223 "'" + Config.OutputFilename + "': not stripping symbol '" +
224 Sym.Name.str() + "' because it is named in a relocation");
225 return true;
226 }
227
228 if (!Sym.Referenced) {
229 // With --strip-unneeded, GNU objcopy removes all unreferenced local
230 // symbols, and any unreferenced undefined external.
231 // With --strip-unneeded-symbol we strip only specific unreferenced
232 // local symbol instead of removing all of such.
234 Sym.Sym.SectionNumber == 0)
235 if (Config.StripUnneeded ||
236 Config.UnneededSymbolsToRemove.matches(Sym.Name))
237 return true;
238
239 // GNU objcopy keeps referenced local symbols and external symbols
240 // if --discard-all is set, similar to what --strip-unneeded does,
241 // but undefined local symbols are kept when --discard-all is set.
242 if (Config.DiscardMode == DiscardType::All &&
244 Sym.Sym.SectionNumber != 0)
245 return true;
246 }
247
248 return false;
249 };
250
251 // Actually do removals of symbols.
252 if (Error Err = Obj.removeSymbols(ToRemove))
253 return Err;
254
255 if (!Config.SetSectionFlags.empty())
256 for (Section &Sec : Obj.getMutableSections()) {
257 const auto It = Config.SetSectionFlags.find(Sec.Name);
258 if (It != Config.SetSectionFlags.end())
260 It->second.NewFlags, Sec.Header.Characteristics);
261 }
262
263 for (const NewSectionInfo &NewSection : Config.AddSection) {
265 const auto It = Config.SetSectionFlags.find(NewSection.SectionName);
266 if (It != Config.SetSectionFlags.end())
267 Characteristics = flagsToCharacteristics(It->second.NewFlags, 0);
268 else
270
271 addSection(Obj, NewSection.SectionName,
272 ArrayRef(reinterpret_cast<const uint8_t *>(
273 NewSection.SectionData->getBufferStart()),
274 NewSection.SectionData->getBufferSize()),
276 }
277
278 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
279 auto It = llvm::find_if(Obj.getMutableSections(), [&](auto &Sec) {
280 return Sec.Name == NewSection.SectionName;
281 });
282 if (It == Obj.getMutableSections().end())
284 "could not find section with name '%s'",
285 NewSection.SectionName.str().c_str());
286 size_t ContentSize = It->getContents().size();
287 if (!ContentSize)
288 return createStringError(
290 "section '%s' cannot be updated because it does not have contents",
291 NewSection.SectionName.str().c_str());
292 if (ContentSize < NewSection.SectionData->getBufferSize())
293 return createStringError(
295 "new section cannot be larger than previous section");
296 It->setOwnedContents({NewSection.SectionData->getBufferStart(),
297 NewSection.SectionData->getBufferEnd()});
298 }
299
300 if (!Config.AddGnuDebugLink.empty())
301 if (Error E = addGnuDebugLink(Obj, Config.AddGnuDebugLink))
302 return E;
303
306 if (!Obj.IsPE)
307 return createStringError(
309 "'" + Config.OutputFilename +
310 "': unable to set subsystem on a relocatable object file");
317 }
318
319 return Error::success();
320}
321
324 raw_ostream &Out) {
325 COFFReader Reader(In);
326 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
327 if (!ObjOrErr)
328 return createFileError(Config.InputFilename, ObjOrErr.takeError());
329 Object *Obj = ObjOrErr->get();
330 assert(Obj && "Unable to deserialize COFF object");
331 if (Error E = handleArgs(Config, COFFConfig, *Obj))
332 return createFileError(Config.InputFilename, std::move(E));
333 COFFWriter Writer(*Obj, Out);
334 if (Error E = Writer.write())
335 return createFileError(Config.OutputFilename, std::move(E));
336 return Error::success();
337}
338
339} // end namespace coff
340} // end namespace objcopy
341} // end namespace llvm
ReachingDefAnalysis InstSet & ToRemove
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::string Name
RelaxConfig Config
Definition: ELF_riscv.cpp:506
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define I(x, y, z)
Definition: MD5.cpp:58
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
This class represents an Operation in the Expression.
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:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
static 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,...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Expected< std::unique_ptr< Object > > create() const
Definition: COFFReader.cpp:194
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
@ IMAGE_SCN_ALIGN_64BYTES
Definition: COFF.h:320
@ IMAGE_SCN_ALIGN_128BYTES
Definition: COFF.h:321
@ IMAGE_SCN_MEM_SHARED
Definition: COFF.h:333
@ IMAGE_SCN_ALIGN_256BYTES
Definition: COFF.h:322
@ IMAGE_SCN_ALIGN_1024BYTES
Definition: COFF.h:324
@ IMAGE_SCN_ALIGN_1BYTES
Definition: COFF.h:314
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:307
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:302
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:335
@ IMAGE_SCN_MEM_EXECUTE
Definition: COFF.h:334
@ IMAGE_SCN_ALIGN_512BYTES
Definition: COFF.h:323
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_MEM_DISCARDABLE
Definition: COFF.h:330
@ IMAGE_SCN_ALIGN_4096BYTES
Definition: COFF.h:326
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:303
@ IMAGE_SCN_ALIGN_8192BYTES
Definition: COFF.h:327
@ IMAGE_SCN_ALIGN_16BYTES
Definition: COFF.h:318
@ IMAGE_SCN_ALIGN_8BYTES
Definition: COFF.h:317
@ IMAGE_SCN_ALIGN_4BYTES
Definition: COFF.h:316
@ IMAGE_SCN_ALIGN_32BYTES
Definition: COFF.h:319
@ IMAGE_SCN_ALIGN_2BYTES
Definition: COFF.h:315
@ IMAGE_SCN_ALIGN_2048BYTES
Definition: COFF.h:325
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:336
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition: COFF.h:224
Characteristics
Definition: COFF.h:137
static bool isDebugSection(const Section &Sec)
Definition: COFFObjcopy.cpp:31
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 void addSection(Object &Obj, StringRef Name, ArrayRef< uint8_t > Contents, uint32_t Characteristics)
Definition: COFFObjcopy.cpp:61
static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar)
Definition: COFFObjcopy.cpp:98
static Error dumpSection(Object &O, StringRef SectionName, StringRef FileName)
static uint64_t getNextRVA(const Object &Obj)
Definition: COFFObjcopy.cpp:35
static Error handleArgs(const CommonConfig &Config, const COFFConfig &COFFConfig, Object &Obj)
static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile)
Definition: COFFObjcopy.cpp:85
static Expected< std::vector< uint8_t > > createGnuDebugLinkSectionContents(StringRef File)
Definition: COFFObjcopy.cpp:44
void write32le(void *P, uint32_t V)
Definition: Endian.h:468
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1380
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
uint32_t crc32(ArrayRef< uint8_t > Data)
Definition: CRC.cpp:101
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1824
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:1749
std::optional< unsigned > MinorSubsystemVersion
Definition: COFFConfig.h:21
std::optional< unsigned > Subsystem
Definition: COFFConfig.h:19
std::optional< unsigned > MajorSubsystemVersion
Definition: COFFConfig.h:20
std::shared_ptr< MemoryBuffer > SectionData
Definition: CommonConfig.h:203
iterator_range< std::vector< Symbol >::iterator > getMutableSymbols()
Definition: COFFObject.h:112
void truncateSections(function_ref< bool(const Section &)> ToTruncate)
Definition: COFFObject.cpp:120
void addSections(ArrayRef< Section > NewSections)
Definition: COFFObject.cpp:68
object::pe32plus_header PeHeader
Definition: COFFObject.h:104
void removeSections(function_ref< bool(const Section &)> ToRemove)
Definition: COFFObject.cpp:89
iterator_range< std::vector< Section >::iterator > getMutableSections()
Definition: COFFObject.h:128
ArrayRef< Section > getSections() const
Definition: COFFObject.h:125
Error removeSymbols(function_ref< Expected< bool >(const Symbol &)> ToRemove)
Definition: COFFObject.cpp:37
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:454
SectionNumberType SectionNumber
Definition: COFF.h:261
support::ulittle16_t MajorSubsystemVersion
Definition: COFF.h:160
support::ulittle16_t MinorSubsystemVersion
Definition: COFF.h:161
support::ulittle32_t FileAlignment
Definition: COFF.h:155
support::ulittle16_t Subsystem
Definition: COFF.h:166
support::ulittle32_t SectionAlignment
Definition: COFF.h:154