xref: /openbsd-src/gnu/llvm/llvm/lib/ObjCopy/COFF/COFFObjcopy.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
1*d415bd75Srobert //===- COFFObjcopy.cpp ----------------------------------------------------===//
2*d415bd75Srobert //
3*d415bd75Srobert // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*d415bd75Srobert // See https://llvm.org/LICENSE.txt for license information.
5*d415bd75Srobert // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*d415bd75Srobert //
7*d415bd75Srobert //===----------------------------------------------------------------------===//
8*d415bd75Srobert 
9*d415bd75Srobert #include "llvm/ObjCopy/COFF/COFFObjcopy.h"
10*d415bd75Srobert #include "COFFObject.h"
11*d415bd75Srobert #include "COFFReader.h"
12*d415bd75Srobert #include "COFFWriter.h"
13*d415bd75Srobert #include "llvm/ObjCopy/COFF/COFFConfig.h"
14*d415bd75Srobert #include "llvm/ObjCopy/CommonConfig.h"
15*d415bd75Srobert 
16*d415bd75Srobert #include "llvm/Object/Binary.h"
17*d415bd75Srobert #include "llvm/Object/COFF.h"
18*d415bd75Srobert #include "llvm/Support/CRC.h"
19*d415bd75Srobert #include "llvm/Support/Errc.h"
20*d415bd75Srobert #include "llvm/Support/Path.h"
21*d415bd75Srobert #include <cassert>
22*d415bd75Srobert 
23*d415bd75Srobert namespace llvm {
24*d415bd75Srobert namespace objcopy {
25*d415bd75Srobert namespace coff {
26*d415bd75Srobert 
27*d415bd75Srobert using namespace object;
28*d415bd75Srobert using namespace COFF;
29*d415bd75Srobert 
isDebugSection(const Section & Sec)30*d415bd75Srobert static bool isDebugSection(const Section &Sec) {
31*d415bd75Srobert   return Sec.Name.startswith(".debug");
32*d415bd75Srobert }
33*d415bd75Srobert 
getNextRVA(const Object & Obj)34*d415bd75Srobert static uint64_t getNextRVA(const Object &Obj) {
35*d415bd75Srobert   if (Obj.getSections().empty())
36*d415bd75Srobert     return 0;
37*d415bd75Srobert   const Section &Last = Obj.getSections().back();
38*d415bd75Srobert   return alignTo(Last.Header.VirtualAddress + Last.Header.VirtualSize,
39*d415bd75Srobert                  Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
40*d415bd75Srobert }
41*d415bd75Srobert 
42*d415bd75Srobert static Expected<std::vector<uint8_t>>
createGnuDebugLinkSectionContents(StringRef File)43*d415bd75Srobert createGnuDebugLinkSectionContents(StringRef File) {
44*d415bd75Srobert   ErrorOr<std::unique_ptr<MemoryBuffer>> LinkTargetOrErr =
45*d415bd75Srobert       MemoryBuffer::getFile(File);
46*d415bd75Srobert   if (!LinkTargetOrErr)
47*d415bd75Srobert     return createFileError(File, LinkTargetOrErr.getError());
48*d415bd75Srobert   auto LinkTarget = std::move(*LinkTargetOrErr);
49*d415bd75Srobert   uint32_t CRC32 = llvm::crc32(arrayRefFromStringRef(LinkTarget->getBuffer()));
50*d415bd75Srobert 
51*d415bd75Srobert   StringRef FileName = sys::path::filename(File);
52*d415bd75Srobert   size_t CRCPos = alignTo(FileName.size() + 1, 4);
53*d415bd75Srobert   std::vector<uint8_t> Data(CRCPos + 4);
54*d415bd75Srobert   memcpy(Data.data(), FileName.data(), FileName.size());
55*d415bd75Srobert   support::endian::write32le(Data.data() + CRCPos, CRC32);
56*d415bd75Srobert   return Data;
57*d415bd75Srobert }
58*d415bd75Srobert 
59*d415bd75Srobert // Adds named section with given contents to the object.
addSection(Object & Obj,StringRef Name,ArrayRef<uint8_t> Contents,uint32_t Characteristics)60*d415bd75Srobert static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,
61*d415bd75Srobert                        uint32_t Characteristics) {
62*d415bd75Srobert   bool NeedVA = Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ |
63*d415bd75Srobert                                    IMAGE_SCN_MEM_WRITE);
64*d415bd75Srobert 
65*d415bd75Srobert   Section Sec;
66*d415bd75Srobert   Sec.setOwnedContents(Contents);
67*d415bd75Srobert   Sec.Name = Name;
68*d415bd75Srobert   Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;
69*d415bd75Srobert   Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;
70*d415bd75Srobert   Sec.Header.SizeOfRawData =
71*d415bd75Srobert       NeedVA ? alignTo(Sec.Header.VirtualSize,
72*d415bd75Srobert                        Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)
73*d415bd75Srobert              : Sec.getContents().size();
74*d415bd75Srobert   // Sec.Header.PointerToRawData is filled in by the writer.
75*d415bd75Srobert   Sec.Header.PointerToRelocations = 0;
76*d415bd75Srobert   Sec.Header.PointerToLinenumbers = 0;
77*d415bd75Srobert   // Sec.Header.NumberOfRelocations is filled in by the writer.
78*d415bd75Srobert   Sec.Header.NumberOfLinenumbers = 0;
79*d415bd75Srobert   Sec.Header.Characteristics = Characteristics;
80*d415bd75Srobert 
81*d415bd75Srobert   Obj.addSections(Sec);
82*d415bd75Srobert }
83*d415bd75Srobert 
addGnuDebugLink(Object & Obj,StringRef DebugLinkFile)84*d415bd75Srobert static Error addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
85*d415bd75Srobert   Expected<std::vector<uint8_t>> Contents =
86*d415bd75Srobert       createGnuDebugLinkSectionContents(DebugLinkFile);
87*d415bd75Srobert   if (!Contents)
88*d415bd75Srobert     return Contents.takeError();
89*d415bd75Srobert 
90*d415bd75Srobert   addSection(Obj, ".gnu_debuglink", *Contents,
91*d415bd75Srobert              IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ |
92*d415bd75Srobert                  IMAGE_SCN_MEM_DISCARDABLE);
93*d415bd75Srobert 
94*d415bd75Srobert   return Error::success();
95*d415bd75Srobert }
96*d415bd75Srobert 
flagsToCharacteristics(SectionFlag AllFlags,uint32_t OldChar)97*d415bd75Srobert static uint32_t flagsToCharacteristics(SectionFlag AllFlags, uint32_t OldChar) {
98*d415bd75Srobert   // Need to preserve alignment flags.
99*d415bd75Srobert   const uint32_t PreserveMask =
100*d415bd75Srobert       IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_ALIGN_4BYTES |
101*d415bd75Srobert       IMAGE_SCN_ALIGN_8BYTES | IMAGE_SCN_ALIGN_16BYTES |
102*d415bd75Srobert       IMAGE_SCN_ALIGN_32BYTES | IMAGE_SCN_ALIGN_64BYTES |
103*d415bd75Srobert       IMAGE_SCN_ALIGN_128BYTES | IMAGE_SCN_ALIGN_256BYTES |
104*d415bd75Srobert       IMAGE_SCN_ALIGN_512BYTES | IMAGE_SCN_ALIGN_1024BYTES |
105*d415bd75Srobert       IMAGE_SCN_ALIGN_2048BYTES | IMAGE_SCN_ALIGN_4096BYTES |
106*d415bd75Srobert       IMAGE_SCN_ALIGN_8192BYTES;
107*d415bd75Srobert 
108*d415bd75Srobert   // Setup new section characteristics based on the flags provided in command
109*d415bd75Srobert   // line.
110*d415bd75Srobert   uint32_t NewCharacteristics = (OldChar & PreserveMask) | IMAGE_SCN_MEM_READ;
111*d415bd75Srobert 
112*d415bd75Srobert   if ((AllFlags & SectionFlag::SecAlloc) && !(AllFlags & SectionFlag::SecLoad))
113*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;
114*d415bd75Srobert   if (AllFlags & SectionFlag::SecNoload)
115*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
116*d415bd75Srobert   if (!(AllFlags & SectionFlag::SecReadonly))
117*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_MEM_WRITE;
118*d415bd75Srobert   if (AllFlags & SectionFlag::SecDebug)
119*d415bd75Srobert     NewCharacteristics |=
120*d415bd75Srobert         IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE;
121*d415bd75Srobert   if (AllFlags & SectionFlag::SecCode)
122*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
123*d415bd75Srobert   if (AllFlags & SectionFlag::SecData)
124*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
125*d415bd75Srobert   if (AllFlags & SectionFlag::SecShare)
126*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_MEM_SHARED;
127*d415bd75Srobert   if (AllFlags & SectionFlag::SecExclude)
128*d415bd75Srobert     NewCharacteristics |= IMAGE_SCN_LNK_REMOVE;
129*d415bd75Srobert 
130*d415bd75Srobert   return NewCharacteristics;
131*d415bd75Srobert }
132*d415bd75Srobert 
handleArgs(const CommonConfig & Config,const COFFConfig & COFFConfig,Object & Obj)133*d415bd75Srobert static Error handleArgs(const CommonConfig &Config,
134*d415bd75Srobert                         const COFFConfig &COFFConfig, Object &Obj) {
135*d415bd75Srobert   // Perform the actual section removals.
136*d415bd75Srobert   Obj.removeSections([&Config](const Section &Sec) {
137*d415bd75Srobert     // Contrary to --only-keep-debug, --only-section fully removes sections that
138*d415bd75Srobert     // aren't mentioned.
139*d415bd75Srobert     if (!Config.OnlySection.empty() && !Config.OnlySection.matches(Sec.Name))
140*d415bd75Srobert       return true;
141*d415bd75Srobert 
142*d415bd75Srobert     if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
143*d415bd75Srobert         Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {
144*d415bd75Srobert       if (isDebugSection(Sec) &&
145*d415bd75Srobert           (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
146*d415bd75Srobert         return true;
147*d415bd75Srobert     }
148*d415bd75Srobert 
149*d415bd75Srobert     if (Config.ToRemove.matches(Sec.Name))
150*d415bd75Srobert       return true;
151*d415bd75Srobert 
152*d415bd75Srobert     return false;
153*d415bd75Srobert   });
154*d415bd75Srobert 
155*d415bd75Srobert   if (Config.OnlyKeepDebug) {
156*d415bd75Srobert     // For --only-keep-debug, we keep all other sections, but remove their
157*d415bd75Srobert     // content. The VirtualSize field in the section header is kept intact.
158*d415bd75Srobert     Obj.truncateSections([](const Section &Sec) {
159*d415bd75Srobert       return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
160*d415bd75Srobert              ((Sec.Header.Characteristics &
161*d415bd75Srobert                (IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA)) != 0);
162*d415bd75Srobert     });
163*d415bd75Srobert   }
164*d415bd75Srobert 
165*d415bd75Srobert   // StripAll removes all symbols and thus also removes all relocations.
166*d415bd75Srobert   if (Config.StripAll || Config.StripAllGNU)
167*d415bd75Srobert     for (Section &Sec : Obj.getMutableSections())
168*d415bd75Srobert       Sec.Relocs.clear();
169*d415bd75Srobert 
170*d415bd75Srobert   // If we need to do per-symbol removals, initialize the Referenced field.
171*d415bd75Srobert   if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||
172*d415bd75Srobert       !Config.SymbolsToRemove.empty())
173*d415bd75Srobert     if (Error E = Obj.markSymbols())
174*d415bd75Srobert       return E;
175*d415bd75Srobert 
176*d415bd75Srobert   for (Symbol &Sym : Obj.getMutableSymbols()) {
177*d415bd75Srobert     auto I = Config.SymbolsToRename.find(Sym.Name);
178*d415bd75Srobert     if (I != Config.SymbolsToRename.end())
179*d415bd75Srobert       Sym.Name = I->getValue();
180*d415bd75Srobert   }
181*d415bd75Srobert 
182*d415bd75Srobert   auto ToRemove = [&](const Symbol &Sym) -> Expected<bool> {
183*d415bd75Srobert     // For StripAll, all relocations have been stripped and we remove all
184*d415bd75Srobert     // symbols.
185*d415bd75Srobert     if (Config.StripAll || Config.StripAllGNU)
186*d415bd75Srobert       return true;
187*d415bd75Srobert 
188*d415bd75Srobert     if (Config.SymbolsToRemove.matches(Sym.Name)) {
189*d415bd75Srobert       // Explicitly removing a referenced symbol is an error.
190*d415bd75Srobert       if (Sym.Referenced)
191*d415bd75Srobert         return createStringError(
192*d415bd75Srobert             llvm::errc::invalid_argument,
193*d415bd75Srobert             "'" + Config.OutputFilename + "': not stripping symbol '" +
194*d415bd75Srobert                 Sym.Name.str() + "' because it is named in a relocation");
195*d415bd75Srobert       return true;
196*d415bd75Srobert     }
197*d415bd75Srobert 
198*d415bd75Srobert     if (!Sym.Referenced) {
199*d415bd75Srobert       // With --strip-unneeded, GNU objcopy removes all unreferenced local
200*d415bd75Srobert       // symbols, and any unreferenced undefined external.
201*d415bd75Srobert       // With --strip-unneeded-symbol we strip only specific unreferenced
202*d415bd75Srobert       // local symbol instead of removing all of such.
203*d415bd75Srobert       if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||
204*d415bd75Srobert           Sym.Sym.SectionNumber == 0)
205*d415bd75Srobert         if (Config.StripUnneeded ||
206*d415bd75Srobert             Config.UnneededSymbolsToRemove.matches(Sym.Name))
207*d415bd75Srobert           return true;
208*d415bd75Srobert 
209*d415bd75Srobert       // GNU objcopy keeps referenced local symbols and external symbols
210*d415bd75Srobert       // if --discard-all is set, similar to what --strip-unneeded does,
211*d415bd75Srobert       // but undefined local symbols are kept when --discard-all is set.
212*d415bd75Srobert       if (Config.DiscardMode == DiscardType::All &&
213*d415bd75Srobert           Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&
214*d415bd75Srobert           Sym.Sym.SectionNumber != 0)
215*d415bd75Srobert         return true;
216*d415bd75Srobert     }
217*d415bd75Srobert 
218*d415bd75Srobert     return false;
219*d415bd75Srobert   };
220*d415bd75Srobert 
221*d415bd75Srobert   // Actually do removals of symbols.
222*d415bd75Srobert   if (Error Err = Obj.removeSymbols(ToRemove))
223*d415bd75Srobert     return Err;
224*d415bd75Srobert 
225*d415bd75Srobert   if (!Config.SetSectionFlags.empty())
226*d415bd75Srobert     for (Section &Sec : Obj.getMutableSections()) {
227*d415bd75Srobert       const auto It = Config.SetSectionFlags.find(Sec.Name);
228*d415bd75Srobert       if (It != Config.SetSectionFlags.end())
229*d415bd75Srobert         Sec.Header.Characteristics = flagsToCharacteristics(
230*d415bd75Srobert             It->second.NewFlags, Sec.Header.Characteristics);
231*d415bd75Srobert     }
232*d415bd75Srobert 
233*d415bd75Srobert   for (const NewSectionInfo &NewSection : Config.AddSection) {
234*d415bd75Srobert     uint32_t Characteristics;
235*d415bd75Srobert     const auto It = Config.SetSectionFlags.find(NewSection.SectionName);
236*d415bd75Srobert     if (It != Config.SetSectionFlags.end())
237*d415bd75Srobert       Characteristics = flagsToCharacteristics(It->second.NewFlags, 0);
238*d415bd75Srobert     else
239*d415bd75Srobert       Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES;
240*d415bd75Srobert 
241*d415bd75Srobert     addSection(Obj, NewSection.SectionName,
242*d415bd75Srobert                ArrayRef(reinterpret_cast<const uint8_t *>(
243*d415bd75Srobert                             NewSection.SectionData->getBufferStart()),
244*d415bd75Srobert                         NewSection.SectionData->getBufferSize()),
245*d415bd75Srobert                Characteristics);
246*d415bd75Srobert   }
247*d415bd75Srobert 
248*d415bd75Srobert   for (const NewSectionInfo &NewSection : Config.UpdateSection) {
249*d415bd75Srobert     auto It = llvm::find_if(Obj.getMutableSections(), [&](auto &Sec) {
250*d415bd75Srobert       return Sec.Name == NewSection.SectionName;
251*d415bd75Srobert     });
252*d415bd75Srobert     if (It == Obj.getMutableSections().end())
253*d415bd75Srobert       return createStringError(errc::invalid_argument,
254*d415bd75Srobert                                "could not find section with name '%s'",
255*d415bd75Srobert                                NewSection.SectionName.str().c_str());
256*d415bd75Srobert     size_t ContentSize = It->getContents().size();
257*d415bd75Srobert     if (!ContentSize)
258*d415bd75Srobert       return createStringError(
259*d415bd75Srobert           errc::invalid_argument,
260*d415bd75Srobert           "section '%s' cannot be updated because it does not have contents",
261*d415bd75Srobert           NewSection.SectionName.str().c_str());
262*d415bd75Srobert     if (ContentSize < NewSection.SectionData->getBufferSize())
263*d415bd75Srobert       return createStringError(
264*d415bd75Srobert           errc::invalid_argument,
265*d415bd75Srobert           "new section cannot be larger than previous section");
266*d415bd75Srobert     It->setOwnedContents({NewSection.SectionData->getBufferStart(),
267*d415bd75Srobert                           NewSection.SectionData->getBufferEnd()});
268*d415bd75Srobert   }
269*d415bd75Srobert 
270*d415bd75Srobert   if (!Config.AddGnuDebugLink.empty())
271*d415bd75Srobert     if (Error E = addGnuDebugLink(Obj, Config.AddGnuDebugLink))
272*d415bd75Srobert       return E;
273*d415bd75Srobert 
274*d415bd75Srobert   if (COFFConfig.Subsystem || COFFConfig.MajorSubsystemVersion ||
275*d415bd75Srobert       COFFConfig.MinorSubsystemVersion) {
276*d415bd75Srobert     if (!Obj.IsPE)
277*d415bd75Srobert       return createStringError(
278*d415bd75Srobert           errc::invalid_argument,
279*d415bd75Srobert           "'" + Config.OutputFilename +
280*d415bd75Srobert               "': unable to set subsystem on a relocatable object file");
281*d415bd75Srobert     if (COFFConfig.Subsystem)
282*d415bd75Srobert       Obj.PeHeader.Subsystem = *COFFConfig.Subsystem;
283*d415bd75Srobert     if (COFFConfig.MajorSubsystemVersion)
284*d415bd75Srobert       Obj.PeHeader.MajorSubsystemVersion = *COFFConfig.MajorSubsystemVersion;
285*d415bd75Srobert     if (COFFConfig.MinorSubsystemVersion)
286*d415bd75Srobert       Obj.PeHeader.MinorSubsystemVersion = *COFFConfig.MinorSubsystemVersion;
287*d415bd75Srobert   }
288*d415bd75Srobert 
289*d415bd75Srobert   return Error::success();
290*d415bd75Srobert }
291*d415bd75Srobert 
executeObjcopyOnBinary(const CommonConfig & Config,const COFFConfig & COFFConfig,COFFObjectFile & In,raw_ostream & Out)292*d415bd75Srobert Error executeObjcopyOnBinary(const CommonConfig &Config,
293*d415bd75Srobert                              const COFFConfig &COFFConfig, COFFObjectFile &In,
294*d415bd75Srobert                              raw_ostream &Out) {
295*d415bd75Srobert   COFFReader Reader(In);
296*d415bd75Srobert   Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
297*d415bd75Srobert   if (!ObjOrErr)
298*d415bd75Srobert     return createFileError(Config.InputFilename, ObjOrErr.takeError());
299*d415bd75Srobert   Object *Obj = ObjOrErr->get();
300*d415bd75Srobert   assert(Obj && "Unable to deserialize COFF object");
301*d415bd75Srobert   if (Error E = handleArgs(Config, COFFConfig, *Obj))
302*d415bd75Srobert     return createFileError(Config.InputFilename, std::move(E));
303*d415bd75Srobert   COFFWriter Writer(*Obj, Out);
304*d415bd75Srobert   if (Error E = Writer.write())
305*d415bd75Srobert     return createFileError(Config.OutputFilename, std::move(E));
306*d415bd75Srobert   return Error::success();
307*d415bd75Srobert }
308*d415bd75Srobert 
309*d415bd75Srobert } // end namespace coff
310*d415bd75Srobert } // end namespace objcopy
311*d415bd75Srobert } // end namespace llvm
312