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

source code of llvm/tools/llvm-dwp/llvm-dwp.cpp