blob: c12bb3454de63367d6ecc46d6133c1b99747cc3a [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
68static void addGnuDebugLink(Object &Obj, StringRef DebugLinkFile) {
69 uint32_t StartRVA = getNextRVA(Obj);
70
71 std::vector<Section> Sections;
72 Section Sec;
73 Sec.setOwnedContents(createGnuDebugLinkSectionContents(DebugLinkFile));
74 Sec.Name = ".gnu_debuglink";
75 Sec.Header.VirtualSize = Sec.getContents().size();
76 Sec.Header.VirtualAddress = StartRVA;
Martin Storsjo1be91952019-01-23 11:54:51 +000077 Sec.Header.SizeOfRawData = alignTo(Sec.Header.VirtualSize,
78 Obj.IsPE ? Obj.PeHeader.FileAlignment : 1);
Martin Storsjo12b6b802019-01-23 08:25:28 +000079 // Sec.Header.PointerToRawData is filled in by the writer.
80 Sec.Header.PointerToRelocations = 0;
81 Sec.Header.PointerToLinenumbers = 0;
82 // Sec.Header.NumberOfRelocations is filled in by the writer.
83 Sec.Header.NumberOfLinenumbers = 0;
84 Sec.Header.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA |
85 IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE;
86 Sections.push_back(Sec);
87 Obj.addSections(Sections);
88}
89
Martin Storsjo10b72962019-01-10 21:28:24 +000090static Error handleArgs(const CopyConfig &Config, Object &Obj) {
Martin Storsjof9e14342019-01-19 19:42:35 +000091 // Perform the actual section removals.
92 Obj.removeSections([&Config](const Section &Sec) {
Martin Storsjoe8305172019-01-19 19:42:54 +000093 // Contrary to --only-keep-debug, --only-section fully removes sections that
94 // aren't mentioned.
95 if (!Config.OnlySection.empty() &&
96 !is_contained(Config.OnlySection, Sec.Name))
97 return true;
98
Martin Storsjo78a0b412019-01-19 19:42:41 +000099 if (Config.StripDebug || Config.StripAll || Config.StripAllGNU ||
100 Config.DiscardAll || Config.StripUnneeded) {
101 if (isDebugSection(Sec) &&
102 (Sec.Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
103 return true;
104 }
105
Martin Storsjof9e14342019-01-19 19:42:35 +0000106 if (is_contained(Config.ToRemove, Sec.Name))
107 return true;
108
109 return false;
110 });
111
Martin Storsjo1868d882019-01-19 19:42:48 +0000112 if (Config.OnlyKeepDebug) {
113 // For --only-keep-debug, we keep all other sections, but remove their
114 // content. The VirtualSize field in the section header is kept intact.
115 Obj.truncateSections([](const Section &Sec) {
116 return !isDebugSection(Sec) && Sec.Name != ".buildid" &&
117 ((Sec.Header.Characteristics &
118 (IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA)) != 0);
119 });
120 }
121
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000122 // StripAll removes all symbols and thus also removes all relocations.
123 if (Config.StripAll || Config.StripAllGNU)
Martin Storsjof9e14342019-01-19 19:42:35 +0000124 for (Section &Sec : Obj.getMutableSections())
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000125 Sec.Relocs.clear();
126
Martin Storsjo10b72962019-01-10 21:28:24 +0000127 // If we need to do per-symbol removals, initialize the Referenced field.
Martin Storsjofb909202019-01-11 14:13:04 +0000128 if (Config.StripUnneeded || Config.DiscardAll ||
129 !Config.SymbolsToRemove.empty())
Martin Storsjo10b72962019-01-10 21:28:24 +0000130 if (Error E = Obj.markSymbols())
131 return E;
132
133 // Actually do removals of symbols.
134 Obj.removeSymbols([&](const Symbol &Sym) {
Martin Storsjof51f5ea2019-01-15 09:34:55 +0000135 // For StripAll, all relocations have been stripped and we remove all
136 // symbols.
137 if (Config.StripAll || Config.StripAllGNU)
138 return true;
139
Martin Storsjo10b72962019-01-10 21:28:24 +0000140 if (is_contained(Config.SymbolsToRemove, Sym.Name)) {
141 // Explicitly removing a referenced symbol is an error.
142 if (Sym.Referenced)
143 reportError(Config.OutputFilename,
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000144 createStringError(llvm::errc::invalid_argument,
145 "not stripping symbol '%s' because it is "
146 "named in a relocation.",
147 Sym.Name.str().c_str()));
Martin Storsjo10b72962019-01-10 21:28:24 +0000148 return true;
149 }
150
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000151 if (!Sym.Referenced) {
152 // With --strip-unneeded, GNU objcopy removes all unreferenced local
153 // symbols, and any unreferenced undefined external.
154 if (Config.StripUnneeded &&
155 (Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC ||
156 Sym.Sym.SectionNumber == 0))
Martin Storsjofb909202019-01-11 14:13:04 +0000157 return true;
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000158
Martin Storsjofb909202019-01-11 14:13:04 +0000159 // GNU objcopy keeps referenced local symbols and external symbols
160 // if --discard-all is set, similar to what --strip-unneeded does,
161 // but undefined local symbols are kept when --discard-all is set.
Martin Storsjo4b0694b2019-01-14 18:56:47 +0000162 if (Config.DiscardAll && Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC &&
163 Sym.Sym.SectionNumber != 0)
Martin Storsjofb909202019-01-11 14:13:04 +0000164 return true;
165 }
166
Martin Storsjo10b72962019-01-10 21:28:24 +0000167 return false;
168 });
Martin Storsjo12b6b802019-01-23 08:25:28 +0000169
170 if (!Config.AddGnuDebugLink.empty())
171 addGnuDebugLink(Obj, Config.AddGnuDebugLink);
172
Martin Storsjo0d19a392019-01-23 11:54:55 +0000173 if (!Config.BuildIdLinkDir.empty() || Config.BuildIdLinkInput ||
174 Config.BuildIdLinkOutput || !Config.SplitDWO.empty() ||
175 !Config.SymbolsPrefix.empty() || !Config.AddSection.empty() ||
176 !Config.DumpSection.empty() || !Config.KeepSection.empty() ||
177 !Config.SymbolsToGlobalize.empty() || !Config.SymbolsToKeep.empty() ||
178 !Config.SymbolsToLocalize.empty() || !Config.SymbolsToWeaken.empty() ||
179 !Config.SymbolsToKeepGlobal.empty() || !Config.SectionsToRename.empty() ||
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000180 !Config.SetSectionFlags.empty() || !Config.SymbolsToRename.empty() ||
181 Config.ExtractDWO || Config.KeepFileSymbols || Config.LocalizeHidden ||
182 Config.PreserveDates || Config.StripDWO || Config.StripNonAlloc ||
183 Config.StripSections || Config.Weaken || Config.DecompressDebugSections) {
Martin Storsjo0d19a392019-01-23 11:54:55 +0000184 return createStringError(llvm::errc::invalid_argument,
185 "Option not supported by llvm-objcopy for COFF");
186 }
187
Martin Storsjo10b72962019-01-10 21:28:24 +0000188 return Error::success();
189}
190
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000191Error executeObjcopyOnBinary(const CopyConfig &Config, COFFObjectFile &In,
192 Buffer &Out) {
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000193 COFFReader Reader(In);
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000194 Expected<std::unique_ptr<Object>> ObjOrErr = Reader.create();
195 if (!ObjOrErr)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000196 return createFileError(Config.InputFilename, ObjOrErr.takeError());
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000197 Object *Obj = ObjOrErr->get();
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000198 assert(Obj && "Unable to deserialize COFF object");
Martin Storsjo10b72962019-01-10 21:28:24 +0000199 if (Error E = handleArgs(Config, *Obj))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000200 return createFileError(Config.InputFilename, std::move(E));
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000201 COFFWriter Writer(*Obj, Out);
Martin Storsjo0a5d5b12018-12-30 20:35:43 +0000202 if (Error E = Writer.write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000203 return createFileError(Config.OutputFilename, std::move(E));
204 return Error::success();
Martin Storsjoe84a0b52018-12-19 07:24:38 +0000205}
206
207} // end namespace coff
208} // end namespace objcopy
209} // end namespace llvm