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/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/InitLLVM.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "llvm/Support/ToolOutputFile.h"
32 #include <optional>
33 
34 using namespace llvm;
35 using namespace llvm::object;
36 
37 static mc::RegisterMCTargetOptionsFlags MCTargetOptionsFlags;
38 
39 cl::OptionCategory DwpCategory("Specific Options");
40 static cl::list<std::string>
41     InputFiles(cl::Positional, cl::desc("<input files>"), cl::cat(DwpCategory));
42 
43 static cl::list<std::string> ExecFilenames(
44     "e",
45     cl::desc(
46         "Specify the executable/library files to get the list of *.dwo from"),
47     cl::value_desc("filename"), cl::cat(DwpCategory));
48 
49 static cl::opt<std::string> OutputFilename(cl::Required, "o",
50                                            cl::desc("Specify the output file."),
51                                            cl::value_desc("filename"),
52                                            cl::cat(DwpCategory));
53 
54 static Expected<SmallVector<std::string, 16>>
55 getDWOFilenames(StringRef ExecFilename) {
56   auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename);
57   if (!ErrOrObj)
58     return ErrOrObj.takeError();
59 
60   const ObjectFile &Obj = *ErrOrObj.get().getBinary();
61   std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
62 
63   SmallVector<std::string, 16> DWOPaths;
64   for (const auto &CU : DWARFCtx->compile_units()) {
65     const DWARFDie &Die = CU->getUnitDIE();
66     std::string DWOName = dwarf::toString(
67         Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
68     if (DWOName.empty())
69       continue;
70     std::string DWOCompDir =
71         dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
72     if (!DWOCompDir.empty()) {
73       SmallString<16> DWOPath(std::move(DWOName));
74       sys::fs::make_absolute(DWOCompDir, DWOPath);
75       if (!sys::fs::exists(DWOPath) && sys::fs::exists(DWOName))
76         DWOPaths.push_back(std::move(DWOName));
77       else
78         DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
79     } else {
80       DWOPaths.push_back(std::move(DWOName));
81     }
82   }
83   return std::move(DWOPaths);
84 }
85 
86 static int error(const Twine &Error, const Twine &Context) {
87   errs() << Twine("while processing ") + Context + ":\n";
88   errs() << Twine("error: ") + Error + "\n";
89   return 1;
90 }
91 
92 static Expected<Triple> readTargetTriple(StringRef FileName) {
93   auto ErrOrObj = object::ObjectFile::createObjectFile(FileName);
94   if (!ErrOrObj)
95     return ErrOrObj.takeError();
96 
97   return ErrOrObj->getBinary()->makeTriple();
98 }
99 
100 int main(int argc, char **argv) {
101   InitLLVM X(argc, argv);
102 
103   cl::HideUnrelatedOptions({&DwpCategory, &getColorCategory()});
104   cl::ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files\n");
105 
106   llvm::InitializeAllTargetInfos();
107   llvm::InitializeAllTargetMCs();
108   llvm::InitializeAllTargets();
109   llvm::InitializeAllAsmPrinters();
110 
111   std::vector<std::string> DWOFilenames = InputFiles;
112   for (const auto &ExecFilename : ExecFilenames) {
113     auto DWOs = getDWOFilenames(ExecFilename);
114     if (!DWOs) {
115       logAllUnhandledErrors(
116           handleErrors(DWOs.takeError(),
117                        [&](std::unique_ptr<ECError> EC) -> Error {
118                          return createFileError(ExecFilename,
119                                                 Error(std::move(EC)));
120                        }),
121           WithColor::error());
122       return 1;
123     }
124     DWOFilenames.insert(DWOFilenames.end(),
125                         std::make_move_iterator(DWOs->begin()),
126                         std::make_move_iterator(DWOs->end()));
127   }
128 
129   if (DWOFilenames.empty())
130     return 0;
131 
132   std::string ErrorStr;
133   StringRef Context = "dwarf streamer init";
134 
135   auto ErrOrTriple = readTargetTriple(DWOFilenames.front());
136   if (!ErrOrTriple) {
137     logAllUnhandledErrors(
138         handleErrors(ErrOrTriple.takeError(),
139                      [&](std::unique_ptr<ECError> EC) -> Error {
140                        return createFileError(DWOFilenames.front(),
141                                               Error(std::move(EC)));
142                      }),
143         WithColor::error());
144     return 1;
145   }
146 
147   // Get the target.
148   const Target *TheTarget =
149       TargetRegistry::lookupTarget("", *ErrOrTriple, ErrorStr);
150   if (!TheTarget)
151     return error(ErrorStr, Context);
152   std::string TripleName = ErrOrTriple->getTriple();
153 
154   // Create all the MC Objects.
155   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
156   if (!MRI)
157     return error(Twine("no register info for target ") + TripleName, Context);
158 
159   MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags();
160   std::unique_ptr<MCAsmInfo> MAI(
161       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
162   if (!MAI)
163     return error("no asm info for target " + TripleName, Context);
164 
165   std::unique_ptr<MCSubtargetInfo> MSTI(
166       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
167   if (!MSTI)
168     return error("no subtarget info for target " + TripleName, Context);
169 
170   MCContext MC(*ErrOrTriple, MAI.get(), MRI.get(), MSTI.get());
171   std::unique_ptr<MCObjectFileInfo> MOFI(
172       TheTarget->createMCObjectFileInfo(MC, /*PIC=*/false));
173   MC.setObjectFileInfo(MOFI.get());
174 
175   MCTargetOptions Options;
176   auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
177   if (!MAB)
178     return error("no asm backend for target " + TripleName, Context);
179 
180   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
181   if (!MII)
182     return error("no instr info info for target " + TripleName, Context);
183 
184   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, MC);
185   if (!MCE)
186     return error("no code emitter for target " + TripleName, Context);
187 
188   // Create the output file.
189   std::error_code EC;
190   ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
191   std::optional<buffer_ostream> BOS;
192   raw_pwrite_stream *OS;
193   if (EC)
194     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
195   if (OutFile.os().supportsSeeking()) {
196     OS = &OutFile.os();
197   } else {
198     BOS.emplace(OutFile.os());
199     OS = &*BOS;
200   }
201 
202   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
203       *ErrOrTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
204       MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI,
205       MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
206       /*DWARFMustBeAtTheEnd*/ false));
207   if (!MS)
208     return error("no object streamer for target " + TripleName, Context);
209 
210   if (auto Err = write(*MS, DWOFilenames)) {
211     logAllUnhandledErrors(std::move(Err), WithColor::error());
212     return 1;
213   }
214 
215   MS->finish();
216   OutFile.keep();
217   return 0;
218 }
219