blob: d30bea0b35f131aff90c8eab9c88ffca43d1a74e [file] [log] [blame]
Martin Storsjoe84a0b52018-12-19 07:24:38 +00001//===- COFFObjcopy.cpp ----------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Martin Storsjoe84a0b52018-12-19 07:24:38 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "COFFObjcopy.h"
10#include "Buffer.h"
11#include "CopyConfig.h"
12#include "Object.h"
13#include "Reader.h"
14#include "Writer.h"
15#include "llvm-objcopy.h"
16
17#include "llvm/Object/Binary.h"
18#include "llvm/Object/COFF.h"
Martin Storsjo10b72962019-01-10 21:28:24 +000019#include "llvm/Support/Errc.h"
Martin Storsjo12b6b802019-01-23 08:25:28 +000020#include "llvm/Support/JamCRC.h"
21#include "llvm/Support/Path.h"
Martin Storsjoe84a0b52018-12-19 07:24:38 +000022#include <cassert>
23
24namespace llvm {
25namespace objcopy {
26namespace coff {
27
28using namespace object;
29using namespace COFF;
30
Martin Storsjo78a0b412019-01-19 19:42:41 +000031static bool isDebugSection(const Section &Sec) {
32 return Sec.Name.startswith(".debug");
33}
34
Martin Storsjo12b6b802019-01-23 08:25:28 +000035static 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,
Martin Storsjo1be91952019-01-23 11:54:51 +000040 Obj.IsPE ? Obj.PeHeader.SectionAlignment : 1);
Martin Storsjo12b6b802019-01-23 08:25:28 +000041}
42
43static uint32_t getCRC32(StringRef Data) {
44 JamCRC CRC;
45 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
46 // The CRC32 value needs to be complemented because the JamCRC dosn't
47 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
48 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
49 return ~CRC.getCRC();
50}
51
52static std::vector<uint8_t> createGnuDebugLinkSectionContents(StringRef File) {
53 ErrorOr<std::unique_ptr<MemoryBuffer>> LinkTargetOrErr =
54 MemoryBuffer::getFile(File);
55 if (!LinkTargetOrErr)
56 error("'" + File + "': " + LinkTargetOrErr.getError().message());
57 auto LinkTarget = std::move(*LinkTargetOrErr);
58 uint32_t CRC32 = getCRC32(LinkTarget->getBuffer());
59
60 StringRef FileName = sys::path::filename(File);
61 size_t CRCPos = alignTo(FileName.size() + 1, 4);
62 std::vector<uint8_t> Data(CRCPos + 4);
63 memcpy(Data.data(), FileName.data(), FileName.size());
64 support::endian::write32le(Data.data() + CRCPos, CRC32);
65 return Data;
66}
67
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +000068// Adds named section with given contents to the object.
69static void addSection(Object &Obj, StringRef Name, ArrayRef<uint8_t> Contents,
70 uint32_t Characteristics) {
71 bool NeedVA = Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ |
72 IMAGE_SCN_MEM_WRITE);
Martin Storsjo12b6b802019-01-23 08:25:28 +000073
Martin Storsjo12b6b802019-01-23 08:25:28 +000074 Section Sec;
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +000075 Sec.setOwnedContents(Contents);
76 Sec.Name = Name;
77 Sec.Header.VirtualSize = NeedVA ? Sec.getContents().size() : 0u;
78 Sec.Header.VirtualAddress = NeedVA ? getNextRVA(Obj) : 0u;
79 Sec.Header.SizeOfRawData =
80 NeedVA ? alignTo(Sec.Header.VirtualSize,
81 Obj.IsPE ? Obj.PeHeader.FileAlignment : 1)
82 : Sec.getContents().size();
Martin Storsjo12b6b802019-01-23 08:25:28 +000083 // Sec.Header.PointerToRawData is filled in by the writer.
84 Sec.Header.PointerToRelocations = 0;
85 Sec.Header.PointerToLinenumbers = 0;
86 // Sec.Header.NumberOfRelocations is filled in by the writer.
87 Sec.Header.NumberOfLinenumbers = 0;
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +000088 Sec.Header.Characteristics = Characteristics;
89
90 Obj.addSections(Sec);
91}
92
93static void addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
94 std::vector<uint8_t> Contents =
95 createGnuDebugLinkSectionContents(DebugLinkFile);
96 addSection(Obj, ".gnu_debuglink", Contents,
97 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ |
98 IMAGE_SCN_MEM_DISCARDABLE);
Martin Storsjo12b6b802019-01-23 08:25:28 +000099}
100
Martin Storsjo10b72962019-01-10 21:28:24 +0000101static Error handleArgs(const CopyConfig &Config, Object &Obj) {
Martin Storsjof9e14342019-01-19 19:42:35 +0000102 // Perform the actual section removals.
103 Obj.removeSections([&Config](const Section &Sec) {
Martin Storsjoe8305172019-01-19 19:42:54 +0000104 // Contrary to --only-keep-debug, --only-section fully removes sections that
105 // aren't mentioned.
106 if (!Config.OnlySection.empty() &&
107 !is_contained(Config.OnlySection, Sec.Name))
108 return true;
109
Martin Storsjo78a0b412019-01-19 19:42:41 +0000110 if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000111 Config.DiscardMode == DiscardType::All || Config.StripUnneeded) {
Martin Storsjo78a0b412019-01-19 19:42:41 +0000112 if (isDebugSection(Sec) &&
113 (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
114 return true;
115 }
116
Martin Storsjof9e14342019-01-19 19:42:35 +0000117 if (is_contained(Config.ToRemove, Sec.Name))
118 return true;
119
120 return false;
121 });
122
Martin Storsjo1868d882019-01-19 19:42:48 +0000123 if (Config.OnlyKeepDebug) {
124 // For --only-keep-debug, we keep all other sections, but remove their
125 // content. The VirtualSize field in the section header is kept intact.
126 Obj.truncateSections([](const Section &Sec) {
127 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
128 ((Sec.Header.Characteristics &
129 (IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA)) != 0);
130 });
131 }
132
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000133 // StripAll removes all symbols and thus also removes all relocations.
134 if (Config.StripAll || Config.StripAllGNU)
Martin Storsjof9e14342019-01-19 19:42:35 +0000135 for (Section &Sec : Obj.getMutableSections())
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000136 Sec.Relocs.clear();
137
Martin Storsjo10b72962019-01-10 21:28:24 +0000138 // If we need to do per-symbol removals, initialize the Referenced field.
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000139 if (Config.StripUnneeded || Config.DiscardMode == DiscardType::All ||
Martin Storsjofb909202019-01-11 14:13:04 +0000140 !Config.SymbolsToRemove.empty())
Martin Storsjo10b72962019-01-10 21:28:24 +0000141 if (Error E = Obj.markSymbols())
142 return E;
143
144 // Actually do removals of symbols.
145 Obj.removeSymbols([&](const Symbol &Sym) {
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000146 // For StripAll, all relocations have been stripped and we remove all
147 // symbols.
148 if (Config.StripAll || Config.StripAllGNU)
149 return true;
150
Martin Storsjo10b72962019-01-10 21:28:24 +0000151 if (is_contained(Config.SymbolsToRemove, Sym.Name)) {
152 // Explicitly removing a referenced symbol is an error.
153 if (Sym.Referenced)
154 reportError(Config.OutputFilename,
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000155 createStringError(llvm::errc::invalid_argument,
156 "not stripping symbol '%s' because it is "
James Henderson5316a0d2019-05-22 13:23:26 +0000157 "named in a relocation",
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000158 Sym.Name.str().c_str()));
Martin Storsjo10b72962019-01-10 21:28:24 +0000159 return true;
160 }
161
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000162 if (!Sym.Referenced) {
163 // With --strip-unneeded, GNU objcopy removes all unreferenced local
164 // symbols, and any unreferenced undefined external.
Eugene Leviant2db10622019-02-13 07:34:54 +0000165 // With --strip-unneeded-symbol we strip only specific unreferenced
166 // local symbol instead of removing all of such.
167 if (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||
168 Sym.Sym.SectionNumber == 0)
169 if (Config.StripUnneeded ||
170 is_contained(Config.UnneededSymbolsToRemove, Sym.Name))
171 return true;
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000172
Martin Storsjofb909202019-01-11 14:13:04 +0000173 // GNU objcopy keeps referenced local symbols and external symbols
174 // if --discard-all is set, similar to what --strip-unneeded does,
175 // but undefined local symbols are kept when --discard-all is set.
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000176 if (Config.DiscardMode == DiscardType::All &&
177 Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000178 Sym.Sym.SectionNumber != 0)
Martin Storsjofb909202019-01-11 14:13:04 +0000179 return true;
180 }
181
Martin Storsjo10b72962019-01-10 21:28:24 +0000182 return false;
183 });
Martin Storsjo12b6b802019-01-23 08:25:28 +0000184
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +0000185 for (const auto &Flag : Config.AddSection) {
186 StringRef SecName, FileName;
187 std::tie(SecName, FileName) = Flag.split("=");
188
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +0000189 auto BufOrErr = MemoryBuffer::getFile(FileName);
190 if (!BufOrErr)
191 return createFileError(FileName, errorCodeToError(BufOrErr.getError()));
192 auto Buf = std::move(*BufOrErr);
193
194 addSection(
195 Obj, SecName,
196 makeArrayRef(reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
197 Buf->getBufferSize()),
198 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES);
199 }
200
Martin Storsjo12b6b802019-01-23 08:25:28 +0000201 if (!Config.AddGnuDebugLink.empty())
202 addGnuDebugLink(Obj, Config.AddGnuDebugLink);
203
James Henderson66a9d0f2019-04-18 09:13:30 +0000204 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
205 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
206 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
Sergey Dmitrievcdeaac52019-07-26 17:06:41 +0000207 !Config.AllocSectionsPrefix.empty() || !Config.DumpSection.empty() ||
208 !Config.KeepSection.empty() || !Config.SymbolsToGlobalize.empty() ||
209 !Config.SymbolsToKeep.empty() || !Config.SymbolsToLocalize.empty() ||
210 !Config.SymbolsToWeaken.empty() || !Config.SymbolsToKeepGlobal.empty() ||
211 !Config.SectionsToRename.empty() || !Config.SetSectionFlags.empty() ||
212 !Config.SymbolsToRename.empty() || Config.ExtractDWO ||
213 Config.KeepFileSymbols || Config.LocalizeHidden || Config.PreserveDates ||
214 Config.StripDWO || Config.StripNonAlloc || Config.StripSections ||
215 Config.Weaken || Config.DecompressDebugSections ||
Eugene Leviant51c1f642019-02-25 14:12:41 +0000216 Config.DiscardMode == DiscardType::Locals ||
Eugene Leviant53350d02019-02-26 09:24:22 +0000217 !Config.SymbolsToAdd.empty() || Config.EntryExpr) {
Martin Storsjo0d19a392019-01-23 11:54:55 +0000218 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000219 "option not supported by llvm-objcopy for COFF");
Martin Storsjo0d19a392019-01-23 11:54:55 +0000220 }
221
Martin Storsjo10b72962019-01-10 21:28:24 +0000222 return Error::success();
223}
224
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000225Error executeObjcopyOnBinary(const CopyConfig &Config, COFFObjectFile &In,
226 Buffer &Out) {
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000227 COFFReader Reader(In);
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000228 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
229 if (!ObjOrErr)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000230 return createFileError(Config.InputFilename, ObjOrErr.takeError());
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000231 Object *Obj = ObjOrErr->get();
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000232 assert(Obj && "Unable to deserialize COFF object");
Martin Storsjo10b72962019-01-10 21:28:24 +0000233 if (Error E = handleArgs(Config, *Obj))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000234 return createFileError(Config.InputFilename, std::move(E));
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000235 COFFWriter Writer(*Obj, Out);
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000236 if (Error E = Writer.write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000237 return createFileError(Config.OutputFilename, std::move(E));
238 return Error::success();
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000239}
240
241} // end namespace coff
242} // end namespace objcopy
243} // end namespace llvm