xref: /llvm-project/llvm/tools/llvm-dwp/llvm-dwp.cpp (revision dd647e3e608ed0b2bac7c588d5859b80ef4a5976)
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 
36 using namespace llvm;
37 using namespace llvm::object;
38 
39 static mc::RegisterMCTargetOptionsFlags MCTargetOptionsFlags;
40 
41 // Command-line option boilerplate.
42 namespace {
43 enum 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 
58 using namespace llvm::opt;
59 static constexpr opt::OptTable::Info InfoTable[] = {
60 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
61 #include "Opts.inc"
62 #undef OPTION
63 };
64 
65 class DwpOptTable : public opt::GenericOptTable {
66 public:
67   DwpOptTable()
68       : GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable) {}
69 };
70 } // end anonymous namespace
71 
72 // Options
73 static std::vector<std::string> ExecFilenames;
74 static std::string OutputFilename;
75 static std::string ContinueOption;
76 
77 static Expected<SmallVector<std::string, 16>>
78 getDWOFilenames(StringRef ExecFilename) {
79   auto ErrOrObj = object::ObjectFile::createObjectFile(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         Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
91     if (DWOName.empty())
92       continue;
93     std::string DWOCompDir =
94         dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
95     if (!DWOCompDir.empty()) {
96       SmallString<16> DWOPath(DWOName);
97       sys::fs::make_absolute(DWOCompDir, DWOPath);
98       if (!sys::fs::exists(DWOPath) && sys::fs::exists(DWOName))
99         DWOPaths.push_back(std::move(DWOName));
100       else
101         DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
102     } else {
103       DWOPaths.push_back(std::move(DWOName));
104     }
105   }
106   return std::move(DWOPaths);
107 }
108 
109 static 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 
115 static Expected<Triple> readTargetTriple(StringRef FileName) {
116   auto ErrOrObj = object::ObjectFile::createObjectFile(FileName);
117   if (!ErrOrObj)
118     return ErrOrObj.takeError();
119 
120   return ErrOrObj->getBinary()->makeTriple();
121 }
122 
123 int 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, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) {
130         llvm::errs() << Msg << '\n';
131         std::exit(1);
132       });
133 
134   if (Args.hasArg(OPT_help)) {
135     Tbl.printHelp(llvm::outs(), "llvm-dwp [options] <input files>",
136                   "merge split dwarf (.dwo) files");
137     std::exit(0);
138   }
139 
140   if (Args.hasArg(OPT_version)) {
141     llvm::cl::PrintVersionMessage();
142     std::exit(0);
143   }
144 
145   OutputFilename = Args.getLastArgValue(OPT_outputFileName, "");
146   if (Arg *Arg = Args.getLastArg(OPT_continueOnCuIndexOverflow,
147                                  OPT_continueOnCuIndexOverflow_EQ)) {
148     if (Arg->getOption().matches(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(1);
160       }
161     }
162   }
163 
164   for (const llvm::opt::Arg *A : Args.filtered(OPT_execFileNames))
165     ExecFilenames.emplace_back(A->getValue());
166 
167   std::vector<std::string> DWOFilenames;
168   for (const llvm::opt::Arg *A : Args.filtered(OPT_INPUT))
169     DWOFilenames.emplace_back(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           handleErrors(DWOs.takeError(),
181                        [&](std::unique_ptr<ECError> EC) -> Error {
182                          return createFileError(ExecFilename,
183                                                 Error(std::move(EC)));
184                        }),
185           WithColor::error());
186       return 1;
187     }
188     DWOFilenames.insert(DWOFilenames.end(),
189                         std::make_move_iterator(DWOs->begin()),
190                         std::make_move_iterator(DWOs->end()));
191   }
192 
193   if (DWOFilenames.empty()) {
194     WithColor::defaultWarningHandler(make_error<DWPError>(
195         "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(DWOFilenames.front());
203   if (!ErrOrTriple) {
204     logAllUnhandledErrors(
205         handleErrors(ErrOrTriple.takeError(),
206                      [&](std::unique_ptr<ECError> EC) -> Error {
207                        return createFileError(DWOFilenames.front(),
208                                               Error(std::move(EC)));
209                      }),
210         WithColor::error());
211     return 1;
212   }
213 
214   // Get the target.
215   const Target *TheTarget =
216       TargetRegistry::lookupTarget("", *ErrOrTriple, ErrorStr);
217   if (!TheTarget)
218     return error(ErrorStr, Context);
219   std::string TripleName = ErrOrTriple->getTriple();
220 
221   // Create all the MC Objects.
222   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
223   if (!MRI)
224     return 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, TripleName, MCOptions));
229   if (!MAI)
230     return error("no asm info for target " + TripleName, Context);
231 
232   std::unique_ptr<MCSubtargetInfo> MSTI(
233       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
234   if (!MSTI)
235     return 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(MC, /*PIC=*/false));
240   MC.setObjectFileInfo(MOFI.get());
241 
242   MCTargetOptions Options;
243   auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
244   if (!MAB)
245     return error("no asm backend for target " + TripleName, Context);
246 
247   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
248   if (!MII)
249     return error("no instr info info for target " + TripleName, Context);
250 
251   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, MC);
252   if (!MCE)
253     return 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(Twine(OutputFilename) + ": " + EC.message(), Context);
262   if (OutFile.os().supportsSeeking()) {
263     OS = &OutFile.os();
264   } else {
265     BOS.emplace(OutFile.os());
266     OS = &*BOS;
267   }
268 
269   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
270       *ErrOrTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
271       MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE),
272       *MSTI));
273   if (!MS)
274     return error("no object streamer for target " + TripleName, Context);
275 
276   if (auto Err = write(*MS, DWOFilenames, OverflowOptValue)) {
277     logAllUnhandledErrors(std::move(Err), WithColor::error());
278     return 1;
279   }
280 
281   MS->finish();
282   OutFile.keep();
283   return 0;
284 }
285