LLVM 17.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
16#include "llvm/Object/Binary.h"
17#include "llvm/Object/COFF.h"
18#include "llvm/Support/CRC.h"
19#include "llvm/Support/Errc.h"
20#include "llvm/Support/Path.h"
21#include <cassert>
22
23namespace llvm {
24namespace objcopy {
25namespace coff {
26
27using namespace object;
28using namespace COFF;
29
30static bool isDebugSection(const Section &Sec) {
31 return Sec.Name.startswith(".debug");
32}
33
34static uint64_t getNextRVA(const Object &Obj) {
35 if (Obj.getSections().empty())
36 return 0;
37 const Section &Last = Obj.getSections().back();
38 return alignTo(Last.Header.VirtualAddress + Last.Header.VirtualSize,
39 Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
40}
41
46 if (!LinkTargetOrErr)
47 return createFileError(File, LinkTargetOrErr.getError());
48 auto LinkTarget = std::move(*LinkTargetOrErr);
49 uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer()));
50
52 size_t CRCPos = alignTo(FileName.size() + 1, 4);
53 std::vector<uint8_t> Data(CRCPos + 4);
54 memcpy(Data.data(), FileName.data(), FileName.size());
55 support::endian::write32le(Data.data() + CRCPos, CRC32);
56 return Data;
57}
58
59// Adds named section with given contents to the object.
60static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,
64
65 Section Sec;
66 Sec.setOwnedContents(Contents);
67 Sec.Name = Name;
68 Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;
69 Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;
70 Sec.Header.SizeOfRawData =
71 NeedVA ? alignTo(Sec.Header.VirtualSize,
72 Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)
73 : Sec.getContents().size();
74 // Sec.Header.PointerToRawData is filled in by the writer.
75 Sec.Header.PointerToRelocations = 0;
76 Sec.Header.PointerToLinenumbers = 0;
77 // Sec.Header.NumberOfRelocations is filled in by the writer.
78 Sec.Header.NumberOfLinenumbers = 0;
79 Sec.Header.Characteristics = Characteristics;
80
81 Obj.addSections(Sec);
82}
83
84static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
87 if (!Contents)
88 return Contents.takeError();
89
90 addSection(Obj, ".gnu_debuglink", *Contents,
93
94 return Error::success();
95}
96
98 // Need to preserve alignment flags.
99 const uint32_t PreserveMask =
107
108 // Setup new section characteristics based on the flags provided in command
109 // line.
110 uint32_t NewCharacteristics = (OldChar & PreserveMask) | IMAGE_SCN_MEM_READ;
111
112 if ((AllFlags & SectionFlag::SecAlloc) && !(AllFlags & SectionFlag::SecLoad))
113 NewCharacteristics |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
114 if (AllFlags & SectionFlag::SecNoload)
115 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
116 if (!(AllFlags & SectionFlag::SecReadonly))
117 NewCharacteristics |= IMAGE_SCN_MEM_WRITE;
118 if (AllFlags & SectionFlag::SecDebug)
119 NewCharacteristics |=
121 if (AllFlags & SectionFlag::SecCode)
122 NewCharacteristics |= IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
123 if (AllFlags & SectionFlag::SecData)
124 NewCharacteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
125 if (AllFlags & SectionFlag::SecShare)
126 NewCharacteristics |= IMAGE_SCN_MEM_SHARED;
127 if (AllFlags & SectionFlag::SecExclude)
128 NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
129
130 return NewCharacteristics;
131}
132
133static Error handleArgs(const CommonConfig &Config,
134 const COFFConfig &COFFConfig, Object &Obj) {
135 // Perform the actual section removals.
136 Obj.removeSections([&Config](const Section &Sec) {
137 // Contrary to --only-keep-debug, --only-section fully removes sections that
138 // aren't mentioned.
139 if (!Config.OnlySection.empty() && !Config.OnlySection.matches(Sec.Name))
140 return true;
141
142 if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
143 Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {
144 if (isDebugSection(Sec) &&
145 (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
146 return true;
147 }
148
149 if (Config.ToRemove.matches(Sec.Name))
150 return true;
151
152 return false;
153 });
154
155 if (Config.OnlyKeepDebug) {
156 // For --only-keep-debug, we keep all other sections, but remove their
157 // content. The VirtualSize field in the section header is kept intact.
158 Obj.truncateSections([](const Section &Sec) {
159 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
160 ((Sec.Header.Characteristics &
162 });
163 }
164
165 // StripAll removes all symbols and thus also removes all relocations.
166 if (Config.StripAll || Config.StripAllGNU)
167 for (Section &Sec : Obj.getMutableSections())
168 Sec.Relocs.clear();
169
170 // If we need to do per-symbol removals, initialize the Referenced field.
171 if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||
172 !Config.SymbolsToRemove.empty())
173 if (Error E = Obj.markSymbols())
174 return E;
175
176 for (Symbol &Sym : Obj.getMutableSymbols()) {
177 auto I = Config.SymbolsToRename.find(Sym.Name);
178 if (I != Config.SymbolsToRename.end())
179 Sym.Name = I->getValue();
180 }
181
182 auto ToRemove = [&](const Symbol &Sym) -> Expected<bool> {
183 // For StripAll, all relocations have been stripped and we remove all
184 // symbols.
185 if (Config.StripAll || Config.StripAllGNU)
186 return true;
187
188 if (Config.SymbolsToRemove.matches(Sym.Name)) {
189 // Explicitly removing a referenced symbol is an error.
190 if (Sym.Referenced)
191 return createStringError(
193 "'" + Config.OutputFilename + "': not stripping symbol '" +
194 Sym.Name.str() + "' because it is named in a relocation");
195 return true;
196 }
197
198 if (!Sym.Referenced) {
199 // With --strip-unneeded, GNU objcopy removes all unreferenced local
200 // symbols, and any unreferenced undefined external.
201 // With --strip-unneeded-symbol we strip only specific unreferenced
202 // local symbol instead of removing all of such.
203 if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||
204 Sym.Sym.SectionNumber == 0)
205 if (Config.StripUnneeded ||
206 Config.UnneededSymbolsToRemove.matches(Sym.Name))
207 return true;
208
209 // GNU objcopy keeps referenced local symbols and external symbols
210 // if --discard-all is set, similar to what --strip-unneeded does,
211 // but undefined local symbols are kept when --discard-all is set.
212 if (Config.DiscardMode == DiscardType::All &&
213 Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&
214 Sym.Sym.SectionNumber != 0)
215 return true;
216 }
217
218 return false;
219 };
220
221 // Actually do removals of symbols.
222 if (Error Err = Obj.removeSymbols(ToRemove))
223 return Err;
224
225 if (!Config.SetSectionFlags.empty())
226 for (Section &Sec : Obj.getMutableSections()) {
227 const auto It = Config.SetSectionFlags.find(Sec.Name);
228 if (It != Config.SetSectionFlags.end())
230 It->second.NewFlags, Sec.Header.Characteristics);
231 }
232
233 for (const NewSectionInfo &NewSection : Config.AddSection) {
235 const auto It = Config.SetSectionFlags.find(NewSection.SectionName);
236 if (It != Config.SetSectionFlags.end())
237 Characteristics = flagsToCharacteristics(It->second.NewFlags, 0);
238 else
240
241 addSection(Obj, NewSection.SectionName,
242 ArrayRef(reinterpret_cast<const uint8_t *>(
243 NewSection.SectionData->getBufferStart()),
244 NewSection.SectionData->getBufferSize()),
246 }
247
248 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
249 auto It = llvm::find_if(Obj.getMutableSections(), [&](auto &Sec) {
250 return Sec.Name == NewSection.SectionName;
251 });
252 if (It == Obj.getMutableSections().end())
254 "could not find section with name '%s'",
255 NewSection.SectionName.str().c_str());
256 size_t ContentSize = It->getContents().size();
257 if (!ContentSize)
258 return createStringError(
260 "section '%s' cannot be updated because it does not have contents",
261 NewSection.SectionName.str().c_str());
262 if (ContentSize < NewSection.SectionData->getBufferSize())
263 return createStringError(
265 "new section cannot be larger than previous section");
266 It->setOwnedContents({NewSection.SectionData->getBufferStart(),
267 NewSection.SectionData->getBufferEnd()});
268 }
269
270 if (!Config.AddGnuDebugLink.empty())
271 if (Error E = addGnuDebugLink(Obj, Config.AddGnuDebugLink))
272 return E;
273
276 if (!Obj.IsPE)
277 return createStringError(
279 "'" + Config.OutputFilename +
280 "': unable to set subsystem on a relocatable object file");
287 }
288
289 return Error::success();
290}
291
294 raw_ostream &Out) {
295 COFFReader Reader(In);
296 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
297 if (!ObjOrErr)
298 return createFileError(Config.InputFilename, ObjOrErr.takeError());
299 Object *Obj = ObjOrErr->get();
300 assert(Obj && "Unable to deserialize COFF object");
301 if (Error E = handleArgs(Config, COFFConfig, *Obj))
302 return createFileError(Config.InputFilename, std::move(E));
303 COFFWriter Writer(*Obj, Out);
304 if (Error E = Writer.write())
305 return createFileError(Config.OutputFilename, std::move(E));
306 return Error::success();
307}
308
309} // end namespace coff
310} // end namespace objcopy
311} // end namespace llvm
ReachingDefAnalysis InstSet & ToRemove
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
if(VerifyEach)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:153
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
Tagged union holding either a T or a Error.
Definition: Error.h:470
Error takeError()
Take ownership of the stored error.
Definition: Error.h:597
reference get()
Returns a reference to the stored T value.
Definition: Error.h:567
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:222
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
bool matches(StringRef S) const
Definition: CommonConfig.h:150
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:306
@ IMAGE_SCN_ALIGN_128BYTES
Definition: COFF.h:307
@ IMAGE_SCN_MEM_SHARED
Definition: COFF.h:319
@ IMAGE_SCN_ALIGN_256BYTES
Definition: COFF.h:308
@ IMAGE_SCN_ALIGN_1024BYTES
Definition: COFF.h:310
@ IMAGE_SCN_ALIGN_1BYTES
Definition: COFF.h:300
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:293
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:288
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:321
@ IMAGE_SCN_MEM_EXECUTE
Definition: COFF.h:320
@ IMAGE_SCN_ALIGN_512BYTES
Definition: COFF.h:309
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:290
@ IMAGE_SCN_MEM_DISCARDABLE
Definition: COFF.h:316
@ IMAGE_SCN_ALIGN_4096BYTES
Definition: COFF.h:312
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:289
@ IMAGE_SCN_ALIGN_8192BYTES
Definition: COFF.h:313
@ IMAGE_SCN_ALIGN_16BYTES
Definition: COFF.h:304
@ IMAGE_SCN_ALIGN_8BYTES
Definition: COFF.h:303
@ IMAGE_SCN_ALIGN_4BYTES
Definition: COFF.h:302
@ IMAGE_SCN_ALIGN_32BYTES
Definition: COFF.h:305
@ IMAGE_SCN_ALIGN_2BYTES
Definition: COFF.h:301
@ IMAGE_SCN_ALIGN_2048BYTES
Definition: COFF.h:311
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:322
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition: COFF.h:210
Characteristics
Definition: COFF.h:123
static bool isDebugSection(const Section &Sec)
Definition: COFFObjcopy.cpp:30
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:60
static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar)
Definition: COFFObjcopy.cpp:97
static uint64_t getNextRVA(const Object &Obj)
Definition: COFFObjcopy.cpp:34
static Error handleArgs(const CommonConfig &Config, const COFFConfig &COFFConfig, Object &Obj)
static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile)
Definition: COFFObjcopy.cpp:84
static Expected< std::vector< uint8_t > > createGnuDebugLinkSectionContents(StringRef File)
Definition: COFFObjcopy.cpp:43
void write32le(void *P, uint32_t V)
Definition: Endian.h:416
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:577
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:1327
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1246
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
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:1846
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::vector< NewSectionInfo > UpdateSection
Definition: CommonConfig.h:224
StringMap< SectionFlagsUpdate > SetSectionFlags
Definition: CommonConfig.h:243
NameMatcher UnneededSymbolsToRemove
Definition: CommonConfig.h:236
std::vector< NewSectionInfo > AddSection
Definition: CommonConfig.h:222
StringMap< StringRef > SymbolsToRename
Definition: CommonConfig.h:245
std::shared_ptr< MemoryBuffer > SectionData
Definition: CommonConfig.h:197
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
support::ulittle32_t Characteristics
Definition: COFF.h:450
support::ulittle16_t MajorSubsystemVersion
Definition: COFF.h:156
support::ulittle16_t MinorSubsystemVersion
Definition: COFF.h:157
support::ulittle32_t FileAlignment
Definition: COFF.h:151
support::ulittle16_t Subsystem
Definition: COFF.h:162
support::ulittle32_t SectionAlignment
Definition: COFF.h:150