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(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(Ids: 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(Ids: 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(Ids: OPT_continueOnCuIndexOverflow,
145 Ids: 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(Ids: OPT_execFileNames))
163 ExecFilenames.emplace_back(args: A->getValue());
164
165 std::vector<std::string> DWOFilenames;
166 for (const llvm::opt::Arg *A : Args.filtered(Ids: OPT_INPUT))
167 DWOFilenames.emplace_back(args: 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 WithColor::defaultWarningHandler(Warning: make_error<DWPError>(
193 Args: "executable file does not contain any references to dwo files"));
194 return 0;
195 }
196
197 std::string ErrorStr;
198 StringRef Context = "dwarf streamer init";
199
200 auto ErrOrTriple = readTargetTriple(FileName: DWOFilenames.front());
201 if (!ErrOrTriple) {
202 logAllUnhandledErrors(
203 E: handleErrors(E: ErrOrTriple.takeError(),
204 Hs: [&](std::unique_ptr<ECError> EC) -> Error {
205 return createFileError(F: DWOFilenames.front(),
206 E: Error(std::move(EC)));
207 }),
208 OS&: WithColor::error());
209 return 1;
210 }
211
212 // Get the target.
213 const Target *TheTarget =
214 TargetRegistry::lookupTarget(ArchName: "", TheTriple&: *ErrOrTriple, Error&: ErrorStr);
215 if (!TheTarget)
216 return error(Error: ErrorStr, Context);
217 std::string TripleName = ErrOrTriple->getTriple();
218
219 // Create all the MC Objects.
220 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TripleName));
221 if (!MRI)
222 return error(Error: Twine("no register info for target ") + TripleName, Context);
223
224 MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags();
225 std::unique_ptr<MCAsmInfo> MAI(
226 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple: TripleName, Options: MCOptions));
227 if (!MAI)
228 return error(Error: "no asm info for target " + TripleName, Context);
229
230 std::unique_ptr<MCSubtargetInfo> MSTI(
231 TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: "", Features: ""));
232 if (!MSTI)
233 return error(Error: "no subtarget info for target " + TripleName, Context);
234
235 MCContext MC(*ErrOrTriple, MAI.get(), MRI.get(), MSTI.get());
236 std::unique_ptr<MCObjectFileInfo> MOFI(
237 TheTarget->createMCObjectFileInfo(Ctx&: MC, /*PIC=*/false));
238 MC.setObjectFileInfo(MOFI.get());
239
240 MCTargetOptions Options;
241 auto MAB = TheTarget->createMCAsmBackend(STI: *MSTI, MRI: *MRI, Options);
242 if (!MAB)
243 return error(Error: "no asm backend for target " + TripleName, Context);
244
245 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
246 if (!MII)
247 return error(Error: "no instr info info for target " + TripleName, Context);
248
249 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(II: *MII, Ctx&: MC);
250 if (!MCE)
251 return error(Error: "no code emitter for target " + TripleName, Context);
252
253 // Create the output file.
254 std::error_code EC;
255 ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
256 std::optional<buffer_ostream> BOS;
257 raw_pwrite_stream *OS;
258 if (EC)
259 return error(Error: Twine(OutputFilename) + ": " + EC.message(), Context);
260 if (OutFile.os().supportsSeeking()) {
261 OS = &OutFile.os();
262 } else {
263 BOS.emplace(args&: OutFile.os());
264 OS = &*BOS;
265 }
266
267 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
268 T: *ErrOrTriple, Ctx&: MC, TAB: std::unique_ptr<MCAsmBackend>(MAB),
269 OW: MAB->createObjectWriter(OS&: *OS), Emitter: std::unique_ptr<MCCodeEmitter>(MCE),
270 STI: *MSTI));
271 if (!MS)
272 return error(Error: "no object streamer for target " + TripleName, Context);
273
274 if (auto Err = write(Out&: *MS, Inputs: DWOFilenames, OverflowOptValue)) {
275 logAllUnhandledErrors(E: std::move(Err), OS&: WithColor::error());
276 return 1;
277 }
278
279 MS->finish();
280 OutFile.keep();
281 return 0;
282}
283