Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.cpp
35258 views
1
//===- llvm-objcopy.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 "ObjcopyOptions.h"
10
#include "llvm/ADT/STLExtras.h"
11
#include "llvm/ADT/SmallVector.h"
12
#include "llvm/ADT/StringRef.h"
13
#include "llvm/ADT/Twine.h"
14
#include "llvm/BinaryFormat/ELF.h"
15
#include "llvm/ObjCopy/COFF/COFFConfig.h"
16
#include "llvm/ObjCopy/COFF/COFFObjcopy.h"
17
#include "llvm/ObjCopy/CommonConfig.h"
18
#include "llvm/ObjCopy/ELF/ELFConfig.h"
19
#include "llvm/ObjCopy/ELF/ELFObjcopy.h"
20
#include "llvm/ObjCopy/MachO/MachOConfig.h"
21
#include "llvm/ObjCopy/MachO/MachOObjcopy.h"
22
#include "llvm/ObjCopy/ObjCopy.h"
23
#include "llvm/ObjCopy/wasm/WasmConfig.h"
24
#include "llvm/ObjCopy/wasm/WasmObjcopy.h"
25
#include "llvm/Object/Archive.h"
26
#include "llvm/Object/ArchiveWriter.h"
27
#include "llvm/Object/Binary.h"
28
#include "llvm/Object/COFF.h"
29
#include "llvm/Object/ELFObjectFile.h"
30
#include "llvm/Object/ELFTypes.h"
31
#include "llvm/Object/Error.h"
32
#include "llvm/Object/MachO.h"
33
#include "llvm/Object/MachOUniversal.h"
34
#include "llvm/Object/Wasm.h"
35
#include "llvm/Option/Arg.h"
36
#include "llvm/Option/ArgList.h"
37
#include "llvm/Option/Option.h"
38
#include "llvm/Support/Casting.h"
39
#include "llvm/Support/CommandLine.h"
40
#include "llvm/Support/Errc.h"
41
#include "llvm/Support/Error.h"
42
#include "llvm/Support/ErrorHandling.h"
43
#include "llvm/Support/ErrorOr.h"
44
#include "llvm/Support/FileUtilities.h"
45
#include "llvm/Support/LLVMDriver.h"
46
#include "llvm/Support/Memory.h"
47
#include "llvm/Support/Path.h"
48
#include "llvm/Support/Process.h"
49
#include "llvm/Support/SmallVectorMemoryBuffer.h"
50
#include "llvm/Support/StringSaver.h"
51
#include "llvm/Support/WithColor.h"
52
#include "llvm/Support/raw_ostream.h"
53
#include "llvm/TargetParser/Host.h"
54
#include <algorithm>
55
#include <cassert>
56
#include <cstdlib>
57
#include <memory>
58
#include <system_error>
59
#include <utility>
60
61
using namespace llvm;
62
using namespace llvm::objcopy;
63
using namespace llvm::object;
64
65
// The name this program was invoked as.
66
static StringRef ToolName;
67
68
static ErrorSuccess reportWarning(Error E) {
69
assert(E);
70
WithColor::warning(errs(), ToolName) << toString(std::move(E)) << '\n';
71
return Error::success();
72
}
73
74
static Expected<DriverConfig> getDriverConfig(ArrayRef<const char *> Args) {
75
StringRef Stem = sys::path::stem(ToolName);
76
auto Is = [=](StringRef Tool) {
77
// We need to recognize the following filenames:
78
//
79
// llvm-objcopy -> objcopy
80
// strip-10.exe -> strip
81
// powerpc64-unknown-freebsd13-objcopy -> objcopy
82
// llvm-install-name-tool -> install-name-tool
83
auto I = Stem.rfind_insensitive(Tool);
84
return I != StringRef::npos &&
85
(I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
86
};
87
88
if (Is("bitcode-strip") || Is("bitcode_strip"))
89
return parseBitcodeStripOptions(Args, reportWarning);
90
else if (Is("strip"))
91
return parseStripOptions(Args, reportWarning);
92
else if (Is("install-name-tool") || Is("install_name_tool"))
93
return parseInstallNameToolOptions(Args);
94
else
95
return parseObjcopyOptions(Args, reportWarning);
96
}
97
98
/// The function executeObjcopyOnIHex does the dispatch based on the format
99
/// of the output specified by the command line options.
100
static Error executeObjcopyOnIHex(ConfigManager &ConfigMgr, MemoryBuffer &In,
101
raw_ostream &Out) {
102
// TODO: support output formats other than ELF.
103
Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
104
if (!ELFConfig)
105
return ELFConfig.takeError();
106
107
return elf::executeObjcopyOnIHex(ConfigMgr.getCommonConfig(), *ELFConfig, In,
108
Out);
109
}
110
111
/// The function executeObjcopyOnRawBinary does the dispatch based on the format
112
/// of the output specified by the command line options.
113
static Error executeObjcopyOnRawBinary(ConfigManager &ConfigMgr,
114
MemoryBuffer &In, raw_ostream &Out) {
115
const CommonConfig &Config = ConfigMgr.getCommonConfig();
116
switch (Config.OutputFormat) {
117
case FileFormat::ELF:
118
// FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the
119
// output format is binary/ihex or it's not given. This behavior differs from
120
// GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details.
121
case FileFormat::Binary:
122
case FileFormat::IHex:
123
case FileFormat::Unspecified:
124
case FileFormat::SREC:
125
Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
126
if (!ELFConfig)
127
return ELFConfig.takeError();
128
129
return elf::executeObjcopyOnRawBinary(Config, *ELFConfig, In, Out);
130
}
131
132
llvm_unreachable("unsupported output format");
133
}
134
135
/// The function executeObjcopy does the higher level dispatch based on the type
136
/// of input (raw binary, archive or single object file) and takes care of the
137
/// format-agnostic modifications, i.e. preserving dates.
138
static Error executeObjcopy(ConfigManager &ConfigMgr) {
139
CommonConfig &Config = ConfigMgr.Common;
140
141
Expected<FilePermissionsApplier> PermsApplierOrErr =
142
FilePermissionsApplier::create(Config.InputFilename);
143
if (!PermsApplierOrErr)
144
return PermsApplierOrErr.takeError();
145
146
std::function<Error(raw_ostream & OutFile)> ObjcopyFunc;
147
148
OwningBinary<llvm::object::Binary> BinaryHolder;
149
std::unique_ptr<MemoryBuffer> MemoryBufferHolder;
150
151
if (Config.InputFormat == FileFormat::Binary ||
152
Config.InputFormat == FileFormat::IHex) {
153
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
154
MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
155
if (!BufOrErr)
156
return createFileError(Config.InputFilename, BufOrErr.getError());
157
MemoryBufferHolder = std::move(*BufOrErr);
158
159
if (Config.InputFormat == FileFormat::Binary)
160
ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
161
// Handle FileFormat::Binary.
162
return executeObjcopyOnRawBinary(ConfigMgr, *MemoryBufferHolder,
163
OutFile);
164
};
165
else
166
ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
167
// Handle FileFormat::IHex.
168
return executeObjcopyOnIHex(ConfigMgr, *MemoryBufferHolder, OutFile);
169
};
170
} else {
171
Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
172
createBinary(Config.InputFilename);
173
if (!BinaryOrErr)
174
return createFileError(Config.InputFilename, BinaryOrErr.takeError());
175
BinaryHolder = std::move(*BinaryOrErr);
176
177
if (Archive *Ar = dyn_cast<Archive>(BinaryHolder.getBinary())) {
178
// Handle Archive.
179
if (Error E = executeObjcopyOnArchive(ConfigMgr, *Ar))
180
return E;
181
} else {
182
// Handle llvm::object::Binary.
183
ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
184
return executeObjcopyOnBinary(ConfigMgr, *BinaryHolder.getBinary(),
185
OutFile);
186
};
187
}
188
}
189
190
if (ObjcopyFunc) {
191
if (Config.SplitDWO.empty()) {
192
// Apply transformations described by Config and store result into
193
// Config.OutputFilename using specified ObjcopyFunc function.
194
if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
195
return E;
196
} else {
197
Config.ExtractDWO = true;
198
Config.StripDWO = false;
199
// Copy .dwo tables from the Config.InputFilename into Config.SplitDWO
200
// file using specified ObjcopyFunc function.
201
if (Error E = writeToOutput(Config.SplitDWO, ObjcopyFunc))
202
return E;
203
Config.ExtractDWO = false;
204
Config.StripDWO = true;
205
// Apply transformations described by Config, remove .dwo tables and
206
// store result into Config.OutputFilename using specified ObjcopyFunc
207
// function.
208
if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
209
return E;
210
}
211
}
212
213
if (Error E =
214
PermsApplierOrErr->apply(Config.OutputFilename, Config.PreserveDates))
215
return E;
216
217
if (!Config.SplitDWO.empty())
218
if (Error E =
219
PermsApplierOrErr->apply(Config.SplitDWO, Config.PreserveDates,
220
static_cast<sys::fs::perms>(0666)))
221
return E;
222
223
return Error::success();
224
}
225
226
int llvm_objcopy_main(int argc, char **argv, const llvm::ToolContext &) {
227
ToolName = argv[0];
228
229
// Expand response files.
230
// TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp,
231
// into a separate function in the CommandLine library and call that function
232
// here. This is duplicated code.
233
SmallVector<const char *, 20> NewArgv(argv, argv + argc);
234
BumpPtrAllocator A;
235
StringSaver Saver(A);
236
cl::ExpandResponseFiles(Saver,
237
Triple(sys::getProcessTriple()).isOSWindows()
238
? cl::TokenizeWindowsCommandLine
239
: cl::TokenizeGNUCommandLine,
240
NewArgv);
241
242
auto Args = ArrayRef(NewArgv).drop_front();
243
Expected<DriverConfig> DriverConfig = getDriverConfig(Args);
244
245
if (!DriverConfig) {
246
logAllUnhandledErrors(DriverConfig.takeError(),
247
WithColor::error(errs(), ToolName));
248
return 1;
249
}
250
for (ConfigManager &ConfigMgr : DriverConfig->CopyConfigs) {
251
if (Error E = executeObjcopy(ConfigMgr)) {
252
logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
253
return 1;
254
}
255
}
256
257
return 0;
258
}
259
260