162cfcf62SDimitry Andric //===-- llvm-dwp.cpp - Split DWARF merging tool for llvm ------------------===//
262cfcf62SDimitry Andric //
362cfcf62SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
462cfcf62SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
562cfcf62SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
662cfcf62SDimitry Andric //
762cfcf62SDimitry Andric //===----------------------------------------------------------------------===//
862cfcf62SDimitry Andric //
962cfcf62SDimitry Andric // A utility for merging DWARF 5 Split DWARF .dwo files into .dwp (DWARF
1062cfcf62SDimitry Andric // package files).
1162cfcf62SDimitry Andric //
1262cfcf62SDimitry Andric //===----------------------------------------------------------------------===//
13fe6060f1SDimitry Andric #include "llvm/DWP/DWP.h"
14fe6060f1SDimitry Andric #include "llvm/DWP/DWPError.h"
15fe6060f1SDimitry Andric #include "llvm/DWP/DWPStringPool.h"
1662cfcf62SDimitry Andric #include "llvm/MC/MCAsmBackend.h"
1762cfcf62SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
1862cfcf62SDimitry Andric #include "llvm/MC/MCCodeEmitter.h"
1962cfcf62SDimitry Andric #include "llvm/MC/MCContext.h"
2062cfcf62SDimitry Andric #include "llvm/MC/MCInstrInfo.h"
2162cfcf62SDimitry Andric #include "llvm/MC/MCObjectWriter.h"
2281ad6265SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
2381ad6265SDimitry Andric #include "llvm/MC/MCSubtargetInfo.h"
245ffd83dbSDimitry Andric #include "llvm/MC/MCTargetOptionsCommandFlags.h"
25349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
2606c3fb27SDimitry Andric #include "llvm/Option/ArgList.h"
2706c3fb27SDimitry Andric #include "llvm/Option/Option.h"
285ffd83dbSDimitry Andric #include "llvm/Support/CommandLine.h"
2962cfcf62SDimitry Andric #include "llvm/Support/FileSystem.h"
305f757f3fSDimitry Andric #include "llvm/Support/LLVMDriver.h"
3181ad6265SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
3262cfcf62SDimitry Andric #include "llvm/Support/TargetSelect.h"
3362cfcf62SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
34bdd1243dSDimitry Andric #include <optional>
3562cfcf62SDimitry Andric 
3662cfcf62SDimitry Andric using namespace llvm;
3762cfcf62SDimitry Andric using namespace llvm::object;
3862cfcf62SDimitry Andric 
395ffd83dbSDimitry Andric static mc::RegisterMCTargetOptionsFlags MCTargetOptionsFlags;
405ffd83dbSDimitry Andric 
4106c3fb27SDimitry Andric // Command-line option boilerplate.
4206c3fb27SDimitry Andric namespace {
4306c3fb27SDimitry Andric enum ID {
4406c3fb27SDimitry Andric   OPT_INVALID = 0, // This is not an option ID.
455f757f3fSDimitry Andric #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
4606c3fb27SDimitry Andric #include "Opts.inc"
4706c3fb27SDimitry Andric #undef OPTION
4806c3fb27SDimitry Andric };
4962cfcf62SDimitry Andric 
5006c3fb27SDimitry Andric #define PREFIX(NAME, VALUE)                                                    \
5106c3fb27SDimitry Andric   static constexpr StringLiteral NAME##_init[] = VALUE;                        \
5206c3fb27SDimitry Andric   static constexpr ArrayRef<StringLiteral> NAME(NAME##_init,                   \
5306c3fb27SDimitry Andric                                                 std::size(NAME##_init) - 1);
5406c3fb27SDimitry Andric #include "Opts.inc"
5506c3fb27SDimitry Andric #undef PREFIX
5662cfcf62SDimitry Andric 
575f757f3fSDimitry Andric using namespace llvm::opt;
5806c3fb27SDimitry Andric static constexpr opt::OptTable::Info InfoTable[] = {
595f757f3fSDimitry Andric #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
6006c3fb27SDimitry Andric #include "Opts.inc"
6106c3fb27SDimitry Andric #undef OPTION
6206c3fb27SDimitry Andric };
6306c3fb27SDimitry Andric 
6406c3fb27SDimitry Andric class DwpOptTable : public opt::GenericOptTable {
6506c3fb27SDimitry Andric public:
DwpOptTable()6606c3fb27SDimitry Andric   DwpOptTable() : GenericOptTable(InfoTable) {}
6706c3fb27SDimitry Andric };
6806c3fb27SDimitry Andric } // end anonymous namespace
6906c3fb27SDimitry Andric 
7006c3fb27SDimitry Andric // Options
7106c3fb27SDimitry Andric static std::vector<std::string> ExecFilenames;
7206c3fb27SDimitry Andric static std::string OutputFilename;
735f757f3fSDimitry Andric static std::string ContinueOption;
7462cfcf62SDimitry Andric 
7562cfcf62SDimitry Andric static Expected<SmallVector<std::string, 16>>
getDWOFilenames(StringRef ExecFilename)7662cfcf62SDimitry Andric getDWOFilenames(StringRef ExecFilename) {
7762cfcf62SDimitry Andric   auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename);
7862cfcf62SDimitry Andric   if (!ErrOrObj)
7962cfcf62SDimitry Andric     return ErrOrObj.takeError();
8062cfcf62SDimitry Andric 
8162cfcf62SDimitry Andric   const ObjectFile &Obj = *ErrOrObj.get().getBinary();
8262cfcf62SDimitry Andric   std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
8362cfcf62SDimitry Andric 
8462cfcf62SDimitry Andric   SmallVector<std::string, 16> DWOPaths;
8562cfcf62SDimitry Andric   for (const auto &CU : DWARFCtx->compile_units()) {
8662cfcf62SDimitry Andric     const DWARFDie &Die = CU->getUnitDIE();
8762cfcf62SDimitry Andric     std::string DWOName = dwarf::toString(
8862cfcf62SDimitry Andric         Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
8962cfcf62SDimitry Andric     if (DWOName.empty())
9062cfcf62SDimitry Andric       continue;
9162cfcf62SDimitry Andric     std::string DWOCompDir =
9262cfcf62SDimitry Andric         dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
9362cfcf62SDimitry Andric     if (!DWOCompDir.empty()) {
94d409305fSDimitry Andric       SmallString<16> DWOPath(std::move(DWOName));
95d409305fSDimitry Andric       sys::fs::make_absolute(DWOCompDir, DWOPath);
96bdd1243dSDimitry Andric       if (!sys::fs::exists(DWOPath) && sys::fs::exists(DWOName))
97bdd1243dSDimitry Andric         DWOPaths.push_back(std::move(DWOName));
98bdd1243dSDimitry Andric       else
9962cfcf62SDimitry Andric         DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
10062cfcf62SDimitry Andric     } else {
10162cfcf62SDimitry Andric       DWOPaths.push_back(std::move(DWOName));
10262cfcf62SDimitry Andric     }
10362cfcf62SDimitry Andric   }
10462cfcf62SDimitry Andric   return std::move(DWOPaths);
10562cfcf62SDimitry Andric }
10662cfcf62SDimitry Andric 
error(const Twine & Error,const Twine & Context)10762cfcf62SDimitry Andric static int error(const Twine &Error, const Twine &Context) {
10862cfcf62SDimitry Andric   errs() << Twine("while processing ") + Context + ":\n";
10962cfcf62SDimitry Andric   errs() << Twine("error: ") + Error + "\n";
11062cfcf62SDimitry Andric   return 1;
11162cfcf62SDimitry Andric }
11262cfcf62SDimitry Andric 
readTargetTriple(StringRef FileName)113e8d8bef9SDimitry Andric static Expected<Triple> readTargetTriple(StringRef FileName) {
114e8d8bef9SDimitry Andric   auto ErrOrObj = object::ObjectFile::createObjectFile(FileName);
115e8d8bef9SDimitry Andric   if (!ErrOrObj)
116e8d8bef9SDimitry Andric     return ErrOrObj.takeError();
117e8d8bef9SDimitry Andric 
118e8d8bef9SDimitry Andric   return ErrOrObj->getBinary()->makeTriple();
119e8d8bef9SDimitry Andric }
120e8d8bef9SDimitry Andric 
llvm_dwp_main(int argc,char ** argv,const llvm::ToolContext &)1215f757f3fSDimitry Andric int llvm_dwp_main(int argc, char **argv, const llvm::ToolContext &) {
12206c3fb27SDimitry Andric   DwpOptTable Tbl;
12306c3fb27SDimitry Andric   llvm::BumpPtrAllocator A;
12406c3fb27SDimitry Andric   llvm::StringSaver Saver{A};
1255f757f3fSDimitry Andric   OnCuIndexOverflow OverflowOptValue = OnCuIndexOverflow::HardStop;
12606c3fb27SDimitry Andric   opt::InputArgList Args =
12706c3fb27SDimitry Andric       Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) {
12806c3fb27SDimitry Andric         llvm::errs() << Msg << '\n';
12906c3fb27SDimitry Andric         std::exit(1);
13006c3fb27SDimitry Andric       });
13106c3fb27SDimitry Andric 
13206c3fb27SDimitry Andric   if (Args.hasArg(OPT_help)) {
13306c3fb27SDimitry Andric     Tbl.printHelp(llvm::outs(), "llvm-dwp [options] <input files>",
13406c3fb27SDimitry Andric                   "merge split dwarf (.dwo) files");
13506c3fb27SDimitry Andric     std::exit(0);
13606c3fb27SDimitry Andric   }
13706c3fb27SDimitry Andric 
13806c3fb27SDimitry Andric   if (Args.hasArg(OPT_version)) {
13906c3fb27SDimitry Andric     llvm::cl::PrintVersionMessage();
14006c3fb27SDimitry Andric     std::exit(0);
14106c3fb27SDimitry Andric   }
14206c3fb27SDimitry Andric 
14306c3fb27SDimitry Andric   OutputFilename = Args.getLastArgValue(OPT_outputFileName, "");
144*cb14a3feSDimitry Andric   if (Arg *Arg = Args.getLastArg(OPT_continueOnCuIndexOverflow,
145*cb14a3feSDimitry Andric                                  OPT_continueOnCuIndexOverflow_EQ)) {
146*cb14a3feSDimitry Andric     if (Arg->getOption().matches(OPT_continueOnCuIndexOverflow)) {
147*cb14a3feSDimitry Andric       OverflowOptValue = OnCuIndexOverflow::Continue;
148*cb14a3feSDimitry Andric     } else {
149*cb14a3feSDimitry Andric       ContinueOption = Arg->getValue();
1505f757f3fSDimitry Andric       if (ContinueOption == "soft-stop") {
1515f757f3fSDimitry Andric         OverflowOptValue = OnCuIndexOverflow::SoftStop;
152*cb14a3feSDimitry Andric       } else if (ContinueOption == "continue") {
1535f757f3fSDimitry Andric         OverflowOptValue = OnCuIndexOverflow::Continue;
154*cb14a3feSDimitry Andric       } else {
155*cb14a3feSDimitry Andric         llvm::errs() << "invalid value for --continue-on-cu-index-overflow"
156*cb14a3feSDimitry Andric                      << ContinueOption << '\n';
157*cb14a3feSDimitry Andric         exit(1);
158*cb14a3feSDimitry Andric       }
1595f757f3fSDimitry Andric     }
1605f757f3fSDimitry Andric   }
16106c3fb27SDimitry Andric 
16206c3fb27SDimitry Andric   for (const llvm::opt::Arg *A : Args.filtered(OPT_execFileNames))
16306c3fb27SDimitry Andric     ExecFilenames.emplace_back(A->getValue());
16406c3fb27SDimitry Andric 
16506c3fb27SDimitry Andric   std::vector<std::string> DWOFilenames;
16606c3fb27SDimitry Andric   for (const llvm::opt::Arg *A : Args.filtered(OPT_INPUT))
16706c3fb27SDimitry Andric     DWOFilenames.emplace_back(A->getValue());
16862cfcf62SDimitry Andric 
16962cfcf62SDimitry Andric   llvm::InitializeAllTargetInfos();
17062cfcf62SDimitry Andric   llvm::InitializeAllTargetMCs();
17162cfcf62SDimitry Andric   llvm::InitializeAllTargets();
17262cfcf62SDimitry Andric   llvm::InitializeAllAsmPrinters();
17362cfcf62SDimitry Andric 
174e8d8bef9SDimitry Andric   for (const auto &ExecFilename : ExecFilenames) {
175e8d8bef9SDimitry Andric     auto DWOs = getDWOFilenames(ExecFilename);
176e8d8bef9SDimitry Andric     if (!DWOs) {
177bdd1243dSDimitry Andric       logAllUnhandledErrors(
178bdd1243dSDimitry Andric           handleErrors(DWOs.takeError(),
179bdd1243dSDimitry Andric                        [&](std::unique_ptr<ECError> EC) -> Error {
180bdd1243dSDimitry Andric                          return createFileError(ExecFilename,
181bdd1243dSDimitry Andric                                                 Error(std::move(EC)));
182bdd1243dSDimitry Andric                        }),
183bdd1243dSDimitry Andric           WithColor::error());
184e8d8bef9SDimitry Andric       return 1;
185e8d8bef9SDimitry Andric     }
186e8d8bef9SDimitry Andric     DWOFilenames.insert(DWOFilenames.end(),
187e8d8bef9SDimitry Andric                         std::make_move_iterator(DWOs->begin()),
188e8d8bef9SDimitry Andric                         std::make_move_iterator(DWOs->end()));
189e8d8bef9SDimitry Andric   }
190e8d8bef9SDimitry Andric 
191e8d8bef9SDimitry Andric   if (DWOFilenames.empty())
192e8d8bef9SDimitry Andric     return 0;
193e8d8bef9SDimitry Andric 
19462cfcf62SDimitry Andric   std::string ErrorStr;
19562cfcf62SDimitry Andric   StringRef Context = "dwarf streamer init";
19662cfcf62SDimitry Andric 
197e8d8bef9SDimitry Andric   auto ErrOrTriple = readTargetTriple(DWOFilenames.front());
198e8d8bef9SDimitry Andric   if (!ErrOrTriple) {
199bdd1243dSDimitry Andric     logAllUnhandledErrors(
200bdd1243dSDimitry Andric         handleErrors(ErrOrTriple.takeError(),
201bdd1243dSDimitry Andric                      [&](std::unique_ptr<ECError> EC) -> Error {
202bdd1243dSDimitry Andric                        return createFileError(DWOFilenames.front(),
203bdd1243dSDimitry Andric                                               Error(std::move(EC)));
204bdd1243dSDimitry Andric                      }),
205bdd1243dSDimitry Andric         WithColor::error());
206e8d8bef9SDimitry Andric     return 1;
207e8d8bef9SDimitry Andric   }
20862cfcf62SDimitry Andric 
20962cfcf62SDimitry Andric   // Get the target.
21062cfcf62SDimitry Andric   const Target *TheTarget =
211e8d8bef9SDimitry Andric       TargetRegistry::lookupTarget("", *ErrOrTriple, ErrorStr);
21262cfcf62SDimitry Andric   if (!TheTarget)
21362cfcf62SDimitry Andric     return error(ErrorStr, Context);
214e8d8bef9SDimitry Andric   std::string TripleName = ErrOrTriple->getTriple();
21562cfcf62SDimitry Andric 
21662cfcf62SDimitry Andric   // Create all the MC Objects.
21762cfcf62SDimitry Andric   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
21862cfcf62SDimitry Andric   if (!MRI)
21962cfcf62SDimitry Andric     return error(Twine("no register info for target ") + TripleName, Context);
22062cfcf62SDimitry Andric 
2215ffd83dbSDimitry Andric   MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags();
22262cfcf62SDimitry Andric   std::unique_ptr<MCAsmInfo> MAI(
22362cfcf62SDimitry Andric       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
22462cfcf62SDimitry Andric   if (!MAI)
22562cfcf62SDimitry Andric     return error("no asm info for target " + TripleName, Context);
22662cfcf62SDimitry Andric 
22762cfcf62SDimitry Andric   std::unique_ptr<MCSubtargetInfo> MSTI(
22862cfcf62SDimitry Andric       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
22962cfcf62SDimitry Andric   if (!MSTI)
23062cfcf62SDimitry Andric     return error("no subtarget info for target " + TripleName, Context);
23162cfcf62SDimitry Andric 
232fe6060f1SDimitry Andric   MCContext MC(*ErrOrTriple, MAI.get(), MRI.get(), MSTI.get());
233fe6060f1SDimitry Andric   std::unique_ptr<MCObjectFileInfo> MOFI(
234fe6060f1SDimitry Andric       TheTarget->createMCObjectFileInfo(MC, /*PIC=*/false));
235fe6060f1SDimitry Andric   MC.setObjectFileInfo(MOFI.get());
236fe6060f1SDimitry Andric 
23762cfcf62SDimitry Andric   MCTargetOptions Options;
23862cfcf62SDimitry Andric   auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
23962cfcf62SDimitry Andric   if (!MAB)
24062cfcf62SDimitry Andric     return error("no asm backend for target " + TripleName, Context);
24162cfcf62SDimitry Andric 
24262cfcf62SDimitry Andric   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
24362cfcf62SDimitry Andric   if (!MII)
24462cfcf62SDimitry Andric     return error("no instr info info for target " + TripleName, Context);
24562cfcf62SDimitry Andric 
24681ad6265SDimitry Andric   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, MC);
24762cfcf62SDimitry Andric   if (!MCE)
24862cfcf62SDimitry Andric     return error("no code emitter for target " + TripleName, Context);
24962cfcf62SDimitry Andric 
25062cfcf62SDimitry Andric   // Create the output file.
25162cfcf62SDimitry Andric   std::error_code EC;
25262cfcf62SDimitry Andric   ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
253bdd1243dSDimitry Andric   std::optional<buffer_ostream> BOS;
25462cfcf62SDimitry Andric   raw_pwrite_stream *OS;
25562cfcf62SDimitry Andric   if (EC)
25662cfcf62SDimitry Andric     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
25762cfcf62SDimitry Andric   if (OutFile.os().supportsSeeking()) {
25862cfcf62SDimitry Andric     OS = &OutFile.os();
25962cfcf62SDimitry Andric   } else {
26062cfcf62SDimitry Andric     BOS.emplace(OutFile.os());
261bdd1243dSDimitry Andric     OS = &*BOS;
26262cfcf62SDimitry Andric   }
26362cfcf62SDimitry Andric 
26462cfcf62SDimitry Andric   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
265e8d8bef9SDimitry Andric       *ErrOrTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
26662cfcf62SDimitry Andric       MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI,
26762cfcf62SDimitry Andric       MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
26862cfcf62SDimitry Andric       /*DWARFMustBeAtTheEnd*/ false));
26962cfcf62SDimitry Andric   if (!MS)
27062cfcf62SDimitry Andric     return error("no object streamer for target " + TripleName, Context);
27162cfcf62SDimitry Andric 
2725f757f3fSDimitry Andric   if (auto Err = write(*MS, DWOFilenames, OverflowOptValue)) {
27362cfcf62SDimitry Andric     logAllUnhandledErrors(std::move(Err), WithColor::error());
27462cfcf62SDimitry Andric     return 1;
27562cfcf62SDimitry Andric   }
27662cfcf62SDimitry Andric 
27781ad6265SDimitry Andric   MS->finish();
27862cfcf62SDimitry Andric   OutFile.keep();
27962cfcf62SDimitry Andric   return 0;
28062cfcf62SDimitry Andric }
281