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