1//===-- llvm-debuginfod-find.cpp - Simple CLI for libdebuginfod-client ----===//
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/// \file
10/// This file contains the llvm-debuginfod-find tool. This tool
11/// queries the debuginfod servers in the DEBUGINFOD_URLS environment
12/// variable (delimited by space (" ")) for the executable,
13/// debuginfo, or specified source file of the binary matching the
14/// given build-id.
15///
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Debuginfod/BuildIDFetcher.h"
21#include "llvm/Debuginfod/Debuginfod.h"
22#include "llvm/HTTP/HTTPClient.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/Option.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Driver.h"
27#include "llvm/Support/InitLLVM.h"
28
29using namespace llvm;
30
31// Command-line option boilerplate.
32namespace {
33enum ID {
34 OPT_INVALID = 0, // This is not an option ID.
35#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
36#include "Opts.inc"
37#undef OPTION
38};
39
40using namespace llvm::opt;
41#define OPTTABLE_CODE
42#include "Opts.inc"
43
44class DebuginfodFindOptTable : public opt::OptTable {
45public:
46 DebuginfodFindOptTable() : OptTable(optionTables()) {}
47};
48
49} // end anonymous namespace
50
51static std::string InputBuildID;
52static bool FetchExecutable;
53static bool FetchDebuginfo;
54static std::string FetchSource;
55static bool DumpToStdout;
56static std::vector<std::string> DebugFileDirectory;
57
58static void parseArgs(int argc, char **argv) {
59 DebuginfodFindOptTable Tbl;
60 llvm::BumpPtrAllocator A;
61 llvm::StringSaver Saver{A};
62 opt::InputArgList Args =
63 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
64 llvm::errs() << Msg << '\n';
65 std::exit(status: 1);
66 });
67
68 if (Args.hasArg(Ids: OPT_help)) {
69 Tbl.printHelp(
70 OS&: llvm::outs(), Usage: "llvm-debuginfod-find [options] <input build_id>",
71 Title: "llvm-debuginfod-find: Fetch debuginfod artifacts\n\n"
72 "This program is a frontend to the debuginfod client library. The "
73 "cache directory, request timeout (in seconds), and debuginfod server "
74 "urls are set by these environment variables:\n"
75 "DEBUGINFOD_CACHE_PATH (default set by sys::path::cache_directory)\n"
76 "DEBUGINFOD_TIMEOUT (defaults to 90s)\n"
77 "DEBUGINFOD_URLS=[comma separated URLs] (defaults to empty)");
78 std::exit(status: 0);
79 }
80
81 InputBuildID = Args.getLastArgValue(Id: OPT_INPUT);
82
83 FetchExecutable = Args.hasArg(Ids: OPT_fetch_executable);
84 FetchDebuginfo = Args.hasArg(Ids: OPT_fetch_debuginfo);
85 DumpToStdout = Args.hasArg(Ids: OPT_dump_to_stdout);
86 FetchSource = Args.getLastArgValue(Id: OPT_fetch_source, Default: "");
87 DebugFileDirectory = Args.getAllArgValues(Id: OPT_debug_file_directory);
88}
89
90[[noreturn]] static void helpExit() {
91 errs() << "Must specify exactly one of --executable, "
92 "--source=/path/to/file, or --debuginfo.\n";
93 exit(status: 1);
94}
95
96ExitOnError ExitOnDebuginfodFindError;
97
98static std::string fetchDebugInfo(object::BuildIDRef BuildID);
99
100int llvm_debuginfod_find_main(int argc, char **argv,
101 const llvm::ToolContext &) {
102 // InitLLVM X(argc, argv);
103 HTTPClient::initialize();
104 parseArgs(argc, argv);
105
106 if (FetchExecutable + FetchDebuginfo + (FetchSource != "") != 1)
107 helpExit();
108
109 std::string IDString;
110 if (!tryGetFromHex(Input: InputBuildID, Output&: IDString)) {
111 errs() << "Build ID " << InputBuildID << " is not a hex string.\n";
112 exit(status: 1);
113 }
114 object::BuildID ID(IDString.begin(), IDString.end());
115
116 std::string Path;
117 if (FetchSource != "")
118 Path =
119 ExitOnDebuginfodFindError(getCachedOrDownloadSource(ID, SourceFilePath: FetchSource));
120 else if (FetchExecutable)
121 Path = ExitOnDebuginfodFindError(getCachedOrDownloadExecutable(ID));
122 else if (FetchDebuginfo)
123 Path = fetchDebugInfo(BuildID: ID);
124 else
125 llvm_unreachable("We have already checked that exactly one of the above "
126 "conditions is true.");
127
128 if (DumpToStdout) {
129 // Print the contents of the artifact.
130 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
131 Filename: Path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
132 ExitOnDebuginfodFindError(errorCodeToError(EC: Buf.getError()));
133 outs() << Buf.get()->getBuffer();
134 } else
135 // Print the path to the cached artifact file.
136 outs() << Path << "\n";
137
138 return 0;
139}
140
141// Find a debug file in local build ID directories and via debuginfod.
142std::string fetchDebugInfo(object::BuildIDRef BuildID) {
143 Expected<std::string> Path =
144 DebuginfodFetcher(DebugFileDirectory).fetch(BuildID);
145 if (Path)
146 return *Path;
147 errs() << "Build ID " << llvm::toHex(Input: BuildID, /*Lowercase=*/LowerCase: true) << ": "
148 << toString(E: Path.takeError()) << "\n";
149 exit(status: 1);
150}
151