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