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
9#include "llvm/ObjCopy/COFF/COFFObjcopy.h"
10#include "COFFObject.h"
11#include "COFFReader.h"
12#include "COFFWriter.h"
13#include "llvm/ObjCopy/COFF/COFFConfig.h"
14#include "llvm/ObjCopy/CommonConfig.h"
15
16#include "llvm/ADT/StringExtras.h"
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(Prefix: ".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(UniqueId: Sym.TargetSectionId);
42 return Sec && Sec->Name == Sym.Name &&
43 (Sec->Header.Characteristics & IMAGE_SCN_LNK_COMDAT);
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(Value: Last.Header.VirtualAddress + Last.Header.VirtualSize,
53 Align: Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
54}
55
56static Expected<std::vector<uint8_t>>
57createGnuDebugLinkSectionContents(StringRef File) {
58 ErrorOr<std::unique_ptr<MemoryBuffer>> LinkTargetOrErr =
59 MemoryBuffer::getFile(Filename: File);
60 if (!LinkTargetOrErr)
61 return createFileError(F: File, EC: LinkTargetOrErr.getError());
62 auto LinkTarget = std::move(*LinkTargetOrErr);
63 uint32_t CRC32 = llvm::crc32(Data: arrayRefFromStringRef(Input: LinkTarget->getBuffer()));
64
65 StringRef FileName = sys::path::filename(path: File);
66 size_t CRCPos = alignTo(Value: FileName.size() + 1, Align: 4);
67 std::vector<uint8_t> Data(CRCPos + 4);
68 memcpy(dest: Data.data(), src: FileName.data(), n: FileName.size());
69 support::endian::write32le(P: Data.data() + CRCPos, V: 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,
75 uint32_t Characteristics) {
76 bool NeedVA = Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ |
77 IMAGE_SCN_MEM_WRITE);
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(Value: Sec.Header.VirtualSize,
86 Align: 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(NewSections: Sec);
96}
97
98static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
99 Expected<std::vector<uint8_t>> Contents =
100 createGnuDebugLinkSectionContents(File: DebugLinkFile);
101 if (!Contents)
102 return Contents.takeError();
103
104 addSection(Obj, Name: ".gnu_debuglink", Contents: *Contents,
105 Characteristics: IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ |
106 IMAGE_SCN_MEM_DISCARDABLE);
107
108 return Error::success();
109}
110
111static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar) {
112 // Need to preserve alignment flags.
113 const uint32_t PreserveMask =
114 IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_ALIGN_4BYTES |
115 IMAGE_SCN_ALIGN_8BYTES | IMAGE_SCN_ALIGN_16BYTES |
116 IMAGE_SCN_ALIGN_32BYTES | IMAGE_SCN_ALIGN_64BYTES |
117 IMAGE_SCN_ALIGN_128BYTES | IMAGE_SCN_ALIGN_256BYTES |
118 IMAGE_SCN_ALIGN_512BYTES | IMAGE_SCN_ALIGN_1024BYTES |
119 IMAGE_SCN_ALIGN_2048BYTES | IMAGE_SCN_ALIGN_4096BYTES |
120 IMAGE_SCN_ALIGN_8192BYTES;
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 |=
134 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE;
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
147static Error dumpSection(Object &O, StringRef SectionName, StringRef FileName) {
148 for (const coff::Section &Section : O.getSections()) {
149 if (Section.Name != SectionName)
150 continue;
151
152 ArrayRef<uint8_t> Contents = Section.getContents();
153
154 std::unique_ptr<FileOutputBuffer> Buffer;
155 if (auto B = FileOutputBuffer::create(FilePath: FileName, Size: Contents.size()))
156 Buffer = std::move(*B);
157 else
158 return B.takeError();
159
160 llvm::copy(Range&: Contents, Out: Buffer->getBufferStart());
161 if (Error E = Buffer->commit())
162 return E;
163
164 return Error::success();
165 }
166 return createStringError(EC: object_error::parse_failed, Fmt: "section '%s' not found",
167 Vals: 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(Separator: '=');
174 if (Error E = dumpSection(O&: Obj, SectionName: Section, FileName: File))
175 return E;
176 }
177
178 // Perform the actual section removals.
179 Obj.removeSections(ToRemove: [&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(S: 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) &&
188 (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
189 return true;
190 }
191
192 if (Config.ToRemove.matches(S: 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(ToTruncate: [DebugDir](const Section &Sec) {
206 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
207 !(DebugDir && DebugDir->Size > 0 &&
208 DebugDir->RelativeVirtualAddress >= Sec.Header.VirtualAddress &&
209 DebugDir->RelativeVirtualAddress <
210 Sec.Header.VirtualAddress + Sec.Header.SizeOfRawData) &&
211 ((Sec.Header.Characteristics &
212 (IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA)) != 0);
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(Key: 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(S: Sym.Name)) {
240 // Explicitly removing a referenced symbol is an error.
241 if (Sym.Referenced)
242 return createStringError(EC: llvm::errc::invalid_argument,
243 S: "'" + 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(S: 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(Key: Sec.Name);
282 if (It != Config.SetSectionFlags.end())
283 Sec.Header.Characteristics = flagsToCharacteristics(
284 AllFlags: It->second.NewFlags, OldChar: Sec.Header.Characteristics);
285 }
286
287 for (const NewSectionInfo &NewSection : Config.AddSection) {
288 uint32_t Characteristics;
289 const auto It = Config.SetSectionFlags.find(Key: NewSection.SectionName);
290 if (It != Config.SetSectionFlags.end())
291 Characteristics = flagsToCharacteristics(AllFlags: It->second.NewFlags, OldChar: 0);
292 else
293 Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES;
294
295 addSection(Obj, Name: NewSection.SectionName,
296 Contents: ArrayRef(reinterpret_cast<const uint8_t *>(
297 NewSection.SectionData->getBufferStart()),
298 NewSection.SectionData->getBufferSize()),
299 Characteristics);
300 }
301
302 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
303 auto It = llvm::find_if(Range: Obj.getMutableSections(), P: [&](auto &Sec) {
304 return Sec.Name == NewSection.SectionName;
305 });
306 if (It == Obj.getMutableSections().end())
307 return createStringError(EC: errc::invalid_argument,
308 Fmt: "could not find section with name '%s'",
309 Vals: NewSection.SectionName.str().c_str());
310 size_t ContentSize = It->getContents().size();
311 if (!ContentSize)
312 return createStringError(
313 EC: errc::invalid_argument,
314 Fmt: "section '%s' cannot be updated because it does not have contents",
315 Vals: NewSection.SectionName.str().c_str());
316 if (ContentSize < NewSection.SectionData->getBufferSize())
317 return createStringError(
318 EC: errc::invalid_argument,
319 S: "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, DebugLinkFile: Config.AddGnuDebugLink))
326 return E;
327
328 if (COFFConfig.Subsystem || COFFConfig.MajorSubsystemVersion ||
329 COFFConfig.MinorSubsystemVersion) {
330 if (!Obj.IsPE)
331 return createStringError(
332 EC: errc::invalid_argument,
333 S: "'" + Config.OutputFilename +
334 "': unable to set subsystem on a relocatable object file");
335 if (COFFConfig.Subsystem)
336 Obj.PeHeader.Subsystem = *COFFConfig.Subsystem;
337 if (COFFConfig.MajorSubsystemVersion)
338 Obj.PeHeader.MajorSubsystemVersion = *COFFConfig.MajorSubsystemVersion;
339 if (COFFConfig.MinorSubsystemVersion)
340 Obj.PeHeader.MinorSubsystemVersion = *COFFConfig.MinorSubsystemVersion;
341 }
342
343 return Error::success();
344}
345
346Error executeObjcopyOnBinary(const CommonConfig &Config,
347 const COFFConfig &COFFConfig, COFFObjectFile &In,
348 raw_ostream &Out) {
349 COFFReader Reader(In);
350 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
351 if (!ObjOrErr)
352 return createFileError(F: Config.InputFilename, E: ObjOrErr.takeError());
353 Object *Obj = ObjOrErr->get();
354 assert(Obj && "Unable to deserialize COFF object");
355 if (Error E = handleArgs(Config, COFFConfig, Obj&: *Obj))
356 return createFileError(F: Config.InputFilename, E: std::move(E));
357 COFFWriter Writer(*Obj, Out);
358 if (Error E = Writer.write())
359 return createFileError(F: Config.OutputFilename, E: std::move(E));
360 return Error::success();
361}
362
363} // end namespace coff
364} // end namespace objcopy
365} // end namespace llvm
366