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/Object/ObjectFile.h"
16#include "llvm/Option/ArgList.h"
17#include "llvm/Option/Option.h"
18#include "llvm/Support/CommandLine.h"
19#include "llvm/Support/Driver.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/ToolOutputFile.h"
22#include <optional>
23
24using namespace llvm;
25using namespace llvm::object;
26
27// Command-line option boilerplate.
28namespace {
29enum ID {
30 OPT_INVALID = 0, // This is not an option ID.
31#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
32#include "Opts.inc"
33#undef OPTION
34};
35
36using namespace llvm::opt;
37#define OPTTABLE_CODE
38#include "Opts.inc"
39
40class DwpOptTable : public opt::OptTable {
41public:
42 DwpOptTable() : OptTable(optionTables()) {}
43};
44} // end anonymous namespace
45
46// Options
47static std::vector<std::string> ExecFilenames;
48static std::string OutputFilename;
49static std::string ContinueOption;
50
51static Expected<SmallVector<std::string, 16>>
52getDWOFilenames(StringRef ExecFilename) {
53 auto ErrOrObj = object::ObjectFile::createObjectFile(ObjectPath: ExecFilename);
54 if (!ErrOrObj)
55 return ErrOrObj.takeError();
56
57 const ObjectFile &Obj = *ErrOrObj.get().getBinary();
58 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
59
60 SmallVector<std::string, 16> DWOPaths;
61 for (const auto &CU : DWARFCtx->compile_units()) {
62 const DWARFDie &Die = CU->getUnitDIE();
63 std::string DWOName = dwarf::toString(
64 V: Die.find(Attrs: {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), Default: "");
65 if (DWOName.empty())
66 continue;
67 std::string DWOCompDir =
68 dwarf::toString(V: Die.find(Attr: dwarf::DW_AT_comp_dir), Default: "");
69 if (!DWOCompDir.empty()) {
70 SmallString<16> DWOPath(DWOName);
71 sys::path::make_absolute(current_directory: DWOCompDir, path&: DWOPath);
72 if (!sys::fs::exists(Path: DWOPath) && sys::fs::exists(Path: DWOName))
73 DWOPaths.push_back(Elt: std::move(DWOName));
74 else
75 DWOPaths.emplace_back(Args: DWOPath.data(), Args: DWOPath.size());
76 } else {
77 DWOPaths.push_back(Elt: std::move(DWOName));
78 }
79 }
80 return std::move(DWOPaths);
81}
82
83static int error(const Twine &Error, const Twine &Context) {
84 errs() << Twine("while processing ") + Context + ":\n";
85 errs() << Twine("error: ") + Error + "\n";
86 return 1;
87}
88
89int llvm_dwp_main(int argc, char **argv, const llvm::ToolContext &) {
90 DwpOptTable Tbl;
91 llvm::BumpPtrAllocator A;
92 llvm::StringSaver Saver{A};
93 OnCuIndexOverflow OverflowOptValue = OnCuIndexOverflow::HardStop;
94 Dwarf64StrOffsetsPromotion Dwarf64StrOffsetsValue =
95 Dwarf64StrOffsetsPromotion::Disabled;
96
97 opt::InputArgList Args =
98 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
99 llvm::errs() << Msg << '\n';
100 std::exit(status: 1);
101 });
102
103 if (Args.hasArg(Ids: OPT_help)) {
104 Tbl.printHelp(OS&: llvm::outs(), Usage: "llvm-dwp [options] <input files>",
105 Title: "merge split dwarf (.dwo) files");
106 std::exit(status: 0);
107 }
108
109 if (Args.hasArg(Ids: OPT_version)) {
110 llvm::cl::PrintVersionMessage();
111 std::exit(status: 0);
112 }
113
114 OutputFilename = Args.getLastArgValue(Id: OPT_outputFileName, Default: "");
115 if (Arg *Arg = Args.getLastArg(Ids: OPT_continueOnCuIndexOverflow,
116 Ids: OPT_continueOnCuIndexOverflow_EQ)) {
117 if (Arg->getOption().matches(ID: OPT_continueOnCuIndexOverflow)) {
118 OverflowOptValue = OnCuIndexOverflow::Continue;
119 } else {
120 ContinueOption = Arg->getValue();
121 if (ContinueOption == "soft-stop") {
122 OverflowOptValue = OnCuIndexOverflow::SoftStop;
123 } else if (ContinueOption == "continue") {
124 OverflowOptValue = OnCuIndexOverflow::Continue;
125 } else {
126 llvm::errs() << "invalid value for --continue-on-cu-index-overflow"
127 << ContinueOption << '\n';
128 exit(status: 1);
129 }
130 }
131 }
132
133 if (Arg *Arg = Args.getLastArg(Ids: OPT_dwarf64StringOffsets,
134 Ids: OPT_dwarf64StringOffsets_EQ)) {
135 if (Arg->getOption().matches(ID: OPT_dwarf64StringOffsets)) {
136 Dwarf64StrOffsetsValue = Dwarf64StrOffsetsPromotion::Enabled;
137 } else {
138 std::string OptValue = Arg->getValue();
139 if (OptValue == "disabled") {
140 Dwarf64StrOffsetsValue = Dwarf64StrOffsetsPromotion::Disabled;
141 } else if (OptValue == "enabled") {
142 Dwarf64StrOffsetsValue = Dwarf64StrOffsetsPromotion::Enabled;
143 } else if (OptValue == "always") {
144 Dwarf64StrOffsetsValue = Dwarf64StrOffsetsPromotion::Always;
145 } else {
146 llvm::errs()
147 << "invalid value for --dwarf64-str-offsets-promotion. Valid "
148 "values are one of: \"enabled\", \"disabled\" or \"always\".\n";
149 exit(status: 1);
150 }
151 }
152 }
153
154 for (const llvm::opt::Arg *A : Args.filtered(Ids: OPT_execFileNames))
155 ExecFilenames.emplace_back(args: A->getValue());
156
157 std::vector<std::string> DWOFilenames;
158 for (const llvm::opt::Arg *A : Args.filtered(Ids: OPT_INPUT))
159 DWOFilenames.emplace_back(args: A->getValue());
160
161 for (const auto &ExecFilename : ExecFilenames) {
162 auto DWOs = getDWOFilenames(ExecFilename);
163 if (!DWOs) {
164 logAllUnhandledErrors(
165 E: handleErrors(E: DWOs.takeError(),
166 Hs: [&](std::unique_ptr<ECError> EC) -> Error {
167 return createFileError(F: ExecFilename,
168 E: Error(std::move(EC)));
169 }),
170 OS&: WithColor::error());
171 return 1;
172 }
173 DWOFilenames.insert(position: DWOFilenames.end(),
174 first: std::make_move_iterator(i: DWOs->begin()),
175 last: std::make_move_iterator(i: DWOs->end()));
176 }
177
178 if (DWOFilenames.empty()) {
179 WithColor::defaultWarningHandler(Warning: make_error<DWPError>(
180 Args: "executable file does not contain any references to dwo files"));
181 return 0;
182 }
183
184 StringRef DiscardPrefix = Args.getLastArgValue(Id: OPT_prioritizeDiscardPath, Default: "");
185 if (OverflowOptValue == OnCuIndexOverflow::SoftStop &&
186 !DiscardPrefix.empty()) {
187 SmallString<256> CanonicalDiscardPrefix(DiscardPrefix);
188 if (std::error_code EC =
189 sys::fs::real_path(path: DiscardPrefix, output&: CanonicalDiscardPrefix)) {
190 WithColor::warning() << "invalid --prioritize-discard-path '"
191 << DiscardPrefix << "': " << EC.message()
192 << "; ignoring option.\n";
193 } else {
194 StringRef PrefixRef(CanonicalDiscardPrefix);
195 auto IsNonDiscarded = [&](const std::string &Name) {
196 SmallString<256> CanonicalDWO;
197 if (sys::fs::real_path(path: Name, output&: CanonicalDWO))
198 return true;
199 StringRef DWORef(CanonicalDWO);
200 if (!DWORef.starts_with(Prefix: PrefixRef))
201 return true;
202 if (DWORef.size() == PrefixRef.size())
203 return false;
204 if (sys::path::is_separator(value: DWORef[PrefixRef.size()]))
205 return false;
206 return true;
207 };
208 std::stable_partition(first: DWOFilenames.begin(), last: DWOFilenames.end(),
209 pred: IsNonDiscarded);
210 }
211 }
212
213 // Create the output file.
214 std::error_code EC;
215 ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
216 std::optional<buffer_ostream> BOS;
217 raw_pwrite_stream *OS;
218 if (EC)
219 return error(Error: Twine(OutputFilename) + ": " + EC.message(),
220 Context: "dwp output init");
221 if (OutFile.os().supportsSeeking()) {
222 OS = &OutFile.os();
223 } else {
224 BOS.emplace(args&: OutFile.os());
225 OS = &*BOS;
226 }
227
228 // Use DWPWriter for direct ELF output
229 DWPWriter Writer;
230
231 if (auto Err = write(Out&: Writer, Inputs: DWOFilenames, OverflowOptValue,
232 StrOffsetsOptValue: Dwarf64StrOffsetsValue, OS)) {
233 logAllUnhandledErrors(E: std::move(Err), OS&: WithColor::error());
234 return 1;
235 }
236
237 OutFile.keep();
238 return 0;
239}
240