1//===-- llvm-dwp.cpp - Split DWARF merging tool for llvm ------------------===//
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// A utility for merging DWARF 5 Split DWARF .dwo files into .dwp (DWARF
10// package files).
11//
12//===----------------------------------------------------------------------===//
13#include "llvm/DWP/DWP.h"
14#include "llvm/DWP/DWPError.h"
15#include "llvm/DWP/DWPStringPool.h"
16#include "llvm/MC/MCAsmBackend.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCCodeEmitter.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCObjectWriter.h"
22#include "llvm/MC/MCRegisterInfo.h"
23#include "llvm/MC/MCSubtargetInfo.h"
24#include "llvm/MC/MCTargetOptionsCommandFlags.h"
25#include "llvm/MC/TargetRegistry.h"
26#include "llvm/Option/ArgList.h"
27#include "llvm/Option/Option.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/FileSystem.h"
30#include "llvm/Support/LLVMDriver.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/TargetSelect.h"
33#include "llvm/Support/ToolOutputFile.h"
34#include <optional>
35
36using namespace llvm;
37using namespace llvm::object;
38
39static mc::RegisterMCTargetOptionsFlags MCTargetOptionsFlags;
40
41// Command-line option boilerplate.
42namespace {
43enum ID {
44 OPT_INVALID = 0, // This is not an option ID.
45#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
46#include "Opts.inc"
47#undef OPTION
48};
49
50#define OPTTABLE_STR_TABLE_CODE
51#include "Opts.inc"
52#undef OPTTABLE_STR_TABLE_CODE
53
54#define OPTTABLE_PREFIXES_TABLE_CODE
55#include "Opts.inc"
56#undef OPTTABLE_PREFIXES_TABLE_CODE
57
58using namespace llvm::opt;
59static constexpr opt::OptTable::Info InfoTable[] = {
60#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
61#include "Opts.inc"
62#undef OPTION
63};
64
65class DwpOptTable : public opt::GenericOptTable {
66public:
67 DwpOptTable()
68 : GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable) {}
69};
70} // end anonymous namespace
71
72// Options
73static std::vector<std::string> ExecFilenames;
74static std::string OutputFilename;
75static std::string ContinueOption;
76
77static Expected<SmallVector<std::string, 16>>
78getDWOFilenames(StringRef ExecFilename) {
79 auto ErrOrObj = object::ObjectFile::createObjectFile(ObjectPath: ExecFilename);
80 if (!ErrOrObj)
81 return ErrOrObj.takeError();
82
83 const ObjectFile &Obj = *ErrOrObj.get().getBinary();
84 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
85
86 SmallVector<std::string, 16> DWOPaths;
87 for (const auto &CU : DWARFCtx->compile_units()) {
88 const DWARFDie &Die = CU->getUnitDIE();
89 std::string DWOName = dwarf::toString(
90 V: Die.find(Attrs: {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), Default: "");
91 if (DWOName.empty())
92 continue;
93 std::string DWOCompDir =
94 dwarf::toString(V: Die.find(Attr: dwarf::DW_AT_comp_dir), Default: "");
95 if (!DWOCompDir.empty()) {
96 SmallString<16> DWOPath(DWOName);
97 sys::fs::make_absolute(current_directory: DWOCompDir, path&: DWOPath);
98 if (!sys::fs::exists(Path: DWOPath) && sys::fs::exists(Path: DWOName))
99 DWOPaths.push_back(Elt: std::move(DWOName));
100 else
101 DWOPaths.emplace_back(Args: DWOPath.data(), Args: DWOPath.size());
102 } else {
103 DWOPaths.push_back(Elt: std::move(DWOName));
104 }
105 }
106 return std::move(DWOPaths);
107}
108
109static int error(const Twine &Error, const Twine &Context) {
110 errs() << Twine("while processing ") + Context + ":\n";
111 errs() << Twine("error: ") + Error + "\n";
112 return 1;
113}
114
115static Expected<Triple> readTargetTriple(StringRef FileName) {
116 auto ErrOrObj = object::ObjectFile::createObjectFile(ObjectPath: FileName);
117 if (!ErrOrObj)
118 return ErrOrObj.takeError();
119
120 return ErrOrObj->getBinary()->makeTriple();
121}
122
123int llvm_dwp_main(int argc, char **argv, const llvm::ToolContext &) {
124 DwpOptTable Tbl;
125 llvm::BumpPtrAllocator A;
126 llvm::StringSaver Saver{A};
127 OnCuIndexOverflow OverflowOptValue = OnCuIndexOverflow::HardStop;
128 opt::InputArgList Args =
129 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
130 llvm::errs() << Msg << '\n';
131 std::exit(status: 1);
132 });
133
134 if (Args.hasArg(Ids: OPT_help)) {
135 Tbl.printHelp(OS&: llvm::outs(), Usage: "llvm-dwp [options] <input files>",
136 Title: "merge split dwarf (.dwo) files");
137 std::exit(status: 0);
138 }
139
140 if (Args.hasArg(Ids: OPT_version)) {
141 llvm::cl::PrintVersionMessage();
142 std::exit(status: 0);
143 }
144
145 OutputFilename = Args.getLastArgValue(Id: OPT_outputFileName, Default: "");
146 if (Arg *Arg = Args.getLastArg(Ids: OPT_continueOnCuIndexOverflow,
147 Ids: OPT_continueOnCuIndexOverflow_EQ)) {
148 if (Arg->getOption().matches(ID: OPT_continueOnCuIndexOverflow)) {
149 OverflowOptValue = OnCuIndexOverflow::Continue;
150 } else {
151 ContinueOption = Arg->getValue();
152 if (ContinueOption == "soft-stop") {
153 OverflowOptValue = OnCuIndexOverflow::SoftStop;
154 } else if (ContinueOption == "continue") {
155 OverflowOptValue = OnCuIndexOverflow::Continue;
156 } else {
157 llvm::errs() << "invalid value for --continue-on-cu-index-overflow"
158 << ContinueOption << '\n';
159 exit(status: 1);
160 }
161 }
162 }
163
164 for (const llvm::opt::Arg *A : Args.filtered(Ids: OPT_execFileNames))
165 ExecFilenames.emplace_back(args: A->getValue());
166
167 std::vector<std::string> DWOFilenames;
168 for (const llvm::opt::Arg *A : Args.filtered(Ids: OPT_INPUT))
169 DWOFilenames.emplace_back(args: A->getValue());
170
171 llvm::InitializeAllTargetInfos();
172 llvm::InitializeAllTargetMCs();
173 llvm::InitializeAllTargets();
174 llvm::InitializeAllAsmPrinters();
175
176 for (const auto &ExecFilename : ExecFilenames) {
177 auto DWOs = getDWOFilenames(ExecFilename);
178 if (!DWOs) {
179 logAllUnhandledErrors(
180 E: handleErrors(E: DWOs.takeError(),
181 Hs: [&](std::unique_ptr<ECError> EC) -> Error {
182 return createFileError(F: ExecFilename,
183 E: Error(std::move(EC)));
184 }),
185 OS&: WithColor::error());
186 return 1;
187 }
188 DWOFilenames.insert(position: DWOFilenames.end(),
189 first: std::make_move_iterator(i: DWOs->begin()),
190 last: std::make_move_iterator(i: DWOs->end()));
191 }
192
193 if (DWOFilenames.empty()) {
194 WithColor::defaultWarningHandler(Warning: make_error<DWPError>(
195 Args: "executable file does not contain any references to dwo files"));
196 return 0;
197 }
198
199 std::string ErrorStr;
200 StringRef Context = "dwarf streamer init";
201
202 auto ErrOrTriple = readTargetTriple(FileName: DWOFilenames.front());
203 if (!ErrOrTriple) {
204 logAllUnhandledErrors(
205 E: handleErrors(E: ErrOrTriple.takeError(),
206 Hs: [&](std::unique_ptr<ECError> EC) -> Error {
207 return createFileError(F: DWOFilenames.front(),
208 E: Error(std::move(EC)));
209 }),
210 OS&: WithColor::error());
211 return 1;
212 }
213
214 // Get the target.
215 const Target *TheTarget =
216 TargetRegistry::lookupTarget(ArchName: "", TheTriple&: *ErrOrTriple, Error&: ErrorStr);
217 if (!TheTarget)
218 return error(Error: ErrorStr, Context);
219 std::string TripleName = ErrOrTriple->getTriple();
220
221 // Create all the MC Objects.
222 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TripleName));
223 if (!MRI)
224 return error(Error: Twine("no register info for target ") + TripleName, Context);
225
226 MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags();
227 std::unique_ptr<MCAsmInfo> MAI(
228 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple: TripleName, Options: MCOptions));
229 if (!MAI)
230 return error(Error: "no asm info for target " + TripleName, Context);
231
232 std::unique_ptr<MCSubtargetInfo> MSTI(
233 TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: "", Features: ""));
234 if (!MSTI)
235 return error(Error: "no subtarget info for target " + TripleName, Context);
236
237 MCContext MC(*ErrOrTriple, MAI.get(), MRI.get(), MSTI.get());
238 std::unique_ptr<MCObjectFileInfo> MOFI(
239 TheTarget->createMCObjectFileInfo(Ctx&: MC, /*PIC=*/false));
240 MC.setObjectFileInfo(MOFI.get());
241
242 MCTargetOptions Options;
243 auto MAB = TheTarget->createMCAsmBackend(STI: *MSTI, MRI: *MRI, Options);
244 if (!MAB)
245 return error(Error: "no asm backend for target " + TripleName, Context);
246
247 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
248 if (!MII)
249 return error(Error: "no instr info info for target " + TripleName, Context);
250
251 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(II: *MII, Ctx&: MC);
252 if (!MCE)
253 return error(Error: "no code emitter for target " + TripleName, Context);
254
255 // Create the output file.
256 std::error_code EC;
257 ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
258 std::optional<buffer_ostream> BOS;
259 raw_pwrite_stream *OS;
260 if (EC)
261 return error(Error: Twine(OutputFilename) + ": " + EC.message(), Context);
262 if (OutFile.os().supportsSeeking()) {
263 OS = &OutFile.os();
264 } else {
265 BOS.emplace(args&: OutFile.os());
266 OS = &*BOS;
267 }
268
269 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
270 T: *ErrOrTriple, Ctx&: MC, TAB: std::unique_ptr<MCAsmBackend>(MAB),
271 OW: MAB->createObjectWriter(OS&: *OS), Emitter: std::unique_ptr<MCCodeEmitter>(MCE),
272 STI: *MSTI));
273 if (!MS)
274 return error(Error: "no object streamer for target " + TripleName, Context);
275
276 if (auto Err = write(Out&: *MS, Inputs: DWOFilenames, OverflowOptValue)) {
277 logAllUnhandledErrors(E: std::move(Err), OS&: WithColor::error());
278 return 1;
279 }
280
281 MS->finish();
282 OutFile.keep();
283 return 0;
284}
285