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 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 
57 using namespace llvm::opt;
58 static constexpr opt::OptTable::Info InfoTable[] = {
59 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
60 #include "Opts.inc"
61 #undef OPTION
62 };
63 
64 class DwpOptTable : public opt::GenericOptTable {
65 public:
66   DwpOptTable() : GenericOptTable(InfoTable) {}
67 };
68 } // end anonymous namespace
69 
70 // Options
71 static std::vector<std::string> ExecFilenames;
72 static std::string OutputFilename;
73 static std::string ContinueOption;
74 
75 static Expected<SmallVector<std::string, 16>>
76 getDWOFilenames(StringRef ExecFilename) {
77   auto ErrOrObj = object::ObjectFile::createObjectFile(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         Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
89     if (DWOName.empty())
90       continue;
91     std::string DWOCompDir =
92         dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
93     if (!DWOCompDir.empty()) {
94       SmallString<16> DWOPath(std::move(DWOName));
95       sys::fs::make_absolute(DWOCompDir, DWOPath);
96       if (!sys::fs::exists(DWOPath) && sys::fs::exists(DWOName))
97         DWOPaths.push_back(std::move(DWOName));
98       else
99         DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
100     } else {
101       DWOPaths.push_back(std::move(DWOName));
102     }
103   }
104   return std::move(DWOPaths);
105 }
106 
107 static 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 
113 static Expected<Triple> readTargetTriple(StringRef FileName) {
114   auto ErrOrObj = object::ObjectFile::createObjectFile(FileName);
115   if (!ErrOrObj)
116     return ErrOrObj.takeError();
117 
118   return ErrOrObj->getBinary()->makeTriple();
119 }
120 
121 int 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, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) {
128         llvm::errs() << Msg << '\n';
129         std::exit(1);
130       });
131 
132   if (Args.hasArg(OPT_help)) {
133     Tbl.printHelp(llvm::outs(), "llvm-dwp [options] <input files>",
134                   "merge split dwarf (.dwo) files");
135     std::exit(0);
136   }
137 
138   if (Args.hasArg(OPT_version)) {
139     llvm::cl::PrintVersionMessage();
140     std::exit(0);
141   }
142 
143   OutputFilename = Args.getLastArgValue(OPT_outputFileName, "");
144   if (Arg *Arg = Args.getLastArg(OPT_continueOnCuIndexOverflow,
145                                  OPT_continueOnCuIndexOverflow_EQ)) {
146     if (Arg->getOption().matches(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(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           handleErrors(DWOs.takeError(),
179                        [&](std::unique_ptr<ECError> EC) -> Error {
180                          return createFileError(ExecFilename,
181                                                 Error(std::move(EC)));
182                        }),
183           WithColor::error());
184       return 1;
185     }
186     DWOFilenames.insert(DWOFilenames.end(),
187                         std::make_move_iterator(DWOs->begin()),
188                         std::make_move_iterator(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(DWOFilenames.front());
198   if (!ErrOrTriple) {
199     logAllUnhandledErrors(
200         handleErrors(ErrOrTriple.takeError(),
201                      [&](std::unique_ptr<ECError> EC) -> Error {
202                        return createFileError(DWOFilenames.front(),
203                                               Error(std::move(EC)));
204                      }),
205         WithColor::error());
206     return 1;
207   }
208 
209   // Get the target.
210   const Target *TheTarget =
211       TargetRegistry::lookupTarget("", *ErrOrTriple, ErrorStr);
212   if (!TheTarget)
213     return error(ErrorStr, Context);
214   std::string TripleName = ErrOrTriple->getTriple();
215 
216   // Create all the MC Objects.
217   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
218   if (!MRI)
219     return 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, TripleName, MCOptions));
224   if (!MAI)
225     return error("no asm info for target " + TripleName, Context);
226 
227   std::unique_ptr<MCSubtargetInfo> MSTI(
228       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
229   if (!MSTI)
230     return 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(MC, /*PIC=*/false));
235   MC.setObjectFileInfo(MOFI.get());
236 
237   MCTargetOptions Options;
238   auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
239   if (!MAB)
240     return error("no asm backend for target " + TripleName, Context);
241 
242   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
243   if (!MII)
244     return error("no instr info info for target " + TripleName, Context);
245 
246   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, MC);
247   if (!MCE)
248     return 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(Twine(OutputFilename) + ": " + EC.message(), Context);
257   if (OutFile.os().supportsSeeking()) {
258     OS = &OutFile.os();
259   } else {
260     BOS.emplace(OutFile.os());
261     OS = &*BOS;
262   }
263 
264   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
265       *ErrOrTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
266       MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI,
267       MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
268       /*DWARFMustBeAtTheEnd*/ false));
269   if (!MS)
270     return error("no object streamer for target " + TripleName, Context);
271 
272   if (auto Err = write(*MS, DWOFilenames, OverflowOptValue)) {
273     logAllUnhandledErrors(std::move(Err), WithColor::error());
274     return 1;
275   }
276 
277   MS->finish();
278   OutFile.keep();
279   return 0;
280 }
281