LLVM 20.0.0git
Debuginfod.cpp
Go to the documentation of this file.
1//===-- llvm/Debuginfod/Debuginfod.cpp - Debuginfod client library --------===//
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///
11/// This file contains several definitions for the debuginfod client and server.
12/// For the client, this file defines the fetchInfo function. For the server,
13/// this file defines the DebuginfodLogEntry and DebuginfodServer structs, as
14/// well as the DebuginfodLog, DebuginfodCollection classes. The fetchInfo
15/// function retrieves any of the three supported artifact types: (executable,
16/// debuginfo, source file) associated with a build-id from debuginfod servers.
17/// If a source file is to be fetched, its absolute path must be specified in
18/// the Description argument to fetchInfo. The DebuginfodLogEntry,
19/// DebuginfodLog, and DebuginfodCollection are used by the DebuginfodServer to
20/// scan the local filesystem for binaries and serve the debuginfod protocol.
21///
22//===----------------------------------------------------------------------===//
23
26#include "llvm/ADT/StringRef.h"
31#include "llvm/Object/BuildID.h"
35#include "llvm/Support/Errc.h"
36#include "llvm/Support/Error.h"
39#include "llvm/Support/Path.h"
41#include "llvm/Support/xxhash.h"
42
43#include <atomic>
44#include <optional>
45#include <thread>
46
47namespace llvm {
48
50
51namespace {
52std::optional<SmallVector<StringRef>> DebuginfodUrls;
53// Many Readers/Single Writer lock protecting the global debuginfod URL list.
54llvm::sys::RWMutex UrlsMutex;
55} // namespace
56
58 return utostr(xxh3_64bits(S));
59}
60
61// Returns a binary BuildID as a normalized hex string.
62// Uses lowercase for compatibility with common debuginfod servers.
63static std::string buildIDToString(BuildIDRef ID) {
64 return llvm::toHex(ID, /*LowerCase=*/true);
65}
66
69}
70
72 std::shared_lock<llvm::sys::RWMutex> ReadGuard(UrlsMutex);
73 if (!DebuginfodUrls) {
74 // Only read from the environment variable if the user hasn't already
75 // set the value.
76 ReadGuard.unlock();
77 std::unique_lock<llvm::sys::RWMutex> WriteGuard(UrlsMutex);
78 DebuginfodUrls = SmallVector<StringRef>();
79 if (const char *DebuginfodUrlsEnv = std::getenv("DEBUGINFOD_URLS")) {
80 StringRef(DebuginfodUrlsEnv)
81 .split(DebuginfodUrls.value(), " ", -1, false);
82 }
83 WriteGuard.unlock();
84 ReadGuard.lock();
85 }
86 return DebuginfodUrls.value();
87}
88
89// Set the default debuginfod URL list, override the environment variable.
91 std::unique_lock<llvm::sys::RWMutex> WriteGuard(UrlsMutex);
92 DebuginfodUrls = URLs;
93}
94
95/// Finds a default local file caching directory for the debuginfod client,
96/// first checking DEBUGINFOD_CACHE_PATH.
98 if (const char *CacheDirectoryEnv = std::getenv("DEBUGINFOD_CACHE_PATH"))
99 return CacheDirectoryEnv;
100
101 SmallString<64> CacheDirectory;
102 if (!sys::path::cache_directory(CacheDirectory))
103 return createStringError(
104 errc::io_error, "Unable to determine appropriate cache directory.");
105 sys::path::append(CacheDirectory, "llvm-debuginfod", "client");
106 return std::string(CacheDirectory);
107}
108
109std::chrono::milliseconds getDefaultDebuginfodTimeout() {
110 long Timeout;
111 const char *DebuginfodTimeoutEnv = std::getenv("DEBUGINFOD_TIMEOUT");
112 if (DebuginfodTimeoutEnv &&
113 to_integer(StringRef(DebuginfodTimeoutEnv).trim(), Timeout, 10))
114 return std::chrono::milliseconds(Timeout * 1000);
115
116 return std::chrono::milliseconds(90 * 1000);
117}
118
119/// The following functions fetch a debuginfod artifact to a file in a local
120/// cache and return the cached file path. They first search the local cache,
121/// followed by the debuginfod servers.
122
123std::string getDebuginfodSourceUrlPath(BuildIDRef ID,
124 StringRef SourceFilePath) {
125 SmallString<64> UrlPath;
126 sys::path::append(UrlPath, sys::path::Style::posix, "buildid",
127 buildIDToString(ID), "source",
128 sys::path::convert_to_slash(SourceFilePath));
129 return std::string(UrlPath);
130}
131
133 StringRef SourceFilePath) {
134 std::string UrlPath = getDebuginfodSourceUrlPath(ID, SourceFilePath);
135 return getCachedOrDownloadArtifact(getDebuginfodCacheKey(UrlPath), UrlPath);
136}
137
138std::string getDebuginfodExecutableUrlPath(BuildIDRef ID) {
139 SmallString<64> UrlPath;
140 sys::path::append(UrlPath, sys::path::Style::posix, "buildid",
141 buildIDToString(ID), "executable");
142 return std::string(UrlPath);
143}
144
146 std::string UrlPath = getDebuginfodExecutableUrlPath(ID);
147 return getCachedOrDownloadArtifact(getDebuginfodCacheKey(UrlPath), UrlPath);
148}
149
150std::string getDebuginfodDebuginfoUrlPath(BuildIDRef ID) {
151 SmallString<64> UrlPath;
152 sys::path::append(UrlPath, sys::path::Style::posix, "buildid",
153 buildIDToString(ID), "debuginfo");
154 return std::string(UrlPath);
155}
156
158 std::string UrlPath = getDebuginfodDebuginfoUrlPath(ID);
159 return getCachedOrDownloadArtifact(getDebuginfodCacheKey(UrlPath), UrlPath);
160}
161
162// General fetching function.
164 StringRef UrlPath) {
165 SmallString<10> CacheDir;
166
168 if (!CacheDirOrErr)
169 return CacheDirOrErr.takeError();
170 CacheDir = *CacheDirOrErr;
171
172 return getCachedOrDownloadArtifact(UniqueKey, UrlPath, CacheDir,
175}
176
177namespace {
178
179/// A simple handler which streams the returned data to a cache file. The cache
180/// file is only created if a 200 OK status is observed.
181class StreamedHTTPResponseHandler : public HTTPResponseHandler {
182 using CreateStreamFn =
183 std::function<Expected<std::unique_ptr<CachedFileStream>>()>;
184 CreateStreamFn CreateStream;
185 HTTPClient &Client;
186 std::unique_ptr<CachedFileStream> FileStream;
187
188public:
189 StreamedHTTPResponseHandler(CreateStreamFn CreateStream, HTTPClient &Client)
190 : CreateStream(CreateStream), Client(Client) {}
191 virtual ~StreamedHTTPResponseHandler() = default;
192
193 Error handleBodyChunk(StringRef BodyChunk) override;
194};
195
196} // namespace
197
198Error StreamedHTTPResponseHandler::handleBodyChunk(StringRef BodyChunk) {
199 if (!FileStream) {
200 unsigned Code = Client.responseCode();
201 if (Code && Code != 200)
202 return Error::success();
203 Expected<std::unique_ptr<CachedFileStream>> FileStreamOrError =
204 CreateStream();
205 if (!FileStreamOrError)
206 return FileStreamOrError.takeError();
207 FileStream = std::move(*FileStreamOrError);
208 }
209 *FileStream->OS << BodyChunk;
210 return Error::success();
211}
212
213// An over-accepting simplification of the HTTP RFC 7230 spec.
214static bool isHeader(StringRef S) {
217 std::tie(Name, Value) = S.split(':');
218 if (Name.empty() || Value.empty())
219 return false;
220 return all_of(Name, [](char C) { return llvm::isPrint(C) && C != ' '; }) &&
221 all_of(Value, [](char C) { return llvm::isPrint(C) || C == '\t'; });
222}
223
225 const char *Filename = getenv("DEBUGINFOD_HEADERS_FILE");
226 if (!Filename)
227 return {};
229 MemoryBuffer::getFile(Filename, /*IsText=*/true);
230 if (!HeadersFile)
231 return {};
232
234 uint64_t LineNumber = 0;
235 for (StringRef Line : llvm::split((*HeadersFile)->getBuffer(), '\n')) {
236 LineNumber++;
237 if (!Line.empty() && Line.back() == '\r')
238 Line = Line.drop_back();
239 if (!isHeader(Line)) {
240 if (!all_of(Line, llvm::isSpace))
242 << "could not parse debuginfod header: " << Filename << ':'
243 << LineNumber << '\n';
244 continue;
245 }
246 Headers.emplace_back(Line);
247 }
248 return Headers;
249}
250
252 StringRef UniqueKey, StringRef UrlPath, StringRef CacheDirectoryPath,
253 ArrayRef<StringRef> DebuginfodUrls, std::chrono::milliseconds Timeout) {
254 SmallString<64> AbsCachedArtifactPath;
255 sys::path::append(AbsCachedArtifactPath, CacheDirectoryPath,
256 "llvmcache-" + UniqueKey);
257
258 Expected<FileCache> CacheOrErr =
259 localCache("Debuginfod-client", ".debuginfod-client", CacheDirectoryPath);
260 if (!CacheOrErr)
261 return CacheOrErr.takeError();
262
263 FileCache Cache = *CacheOrErr;
264 // We choose an arbitrary Task parameter as we do not make use of it.
265 unsigned Task = 0;
266 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, UniqueKey, "");
267 if (!CacheAddStreamOrErr)
268 return CacheAddStreamOrErr.takeError();
269 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
270 if (!CacheAddStream)
271 return std::string(AbsCachedArtifactPath);
272 // The artifact was not found in the local cache, query the debuginfod
273 // servers.
276 "No working HTTP client is available.");
277
279 return createStringError(
281 "A working HTTP client is available, but it is not initialized. To "
282 "allow Debuginfod to make HTTP requests, call HTTPClient::initialize() "
283 "at the beginning of main.");
284
285 HTTPClient Client;
286 Client.setTimeout(Timeout);
287 for (StringRef ServerUrl : DebuginfodUrls) {
288 SmallString<64> ArtifactUrl;
289 sys::path::append(ArtifactUrl, sys::path::Style::posix, ServerUrl, UrlPath);
290
291 // Perform the HTTP request and if successful, write the response body to
292 // the cache.
293 {
294 StreamedHTTPResponseHandler Handler(
295 [&]() { return CacheAddStream(Task, ""); }, Client);
296 HTTPRequest Request(ArtifactUrl);
297 Request.Headers = getHeaders();
298 Error Err = Client.perform(Request, Handler);
299 if (Err)
300 return std::move(Err);
301
302 unsigned Code = Client.responseCode();
303 if (Code && Code != 200)
304 continue;
305 }
306
307 Expected<CachePruningPolicy> PruningPolicyOrErr =
308 parseCachePruningPolicy(std::getenv("DEBUGINFOD_CACHE_POLICY"));
309 if (!PruningPolicyOrErr)
310 return PruningPolicyOrErr.takeError();
311 pruneCache(CacheDirectoryPath, *PruningPolicyOrErr);
312
313 // Return the path to the artifact on disk.
314 return std::string(AbsCachedArtifactPath);
315 }
316
317 return createStringError(errc::argument_out_of_domain, "build id not found");
318}
319
321 : Message(Message.str()) {}
322
323void DebuginfodLog::push(const Twine &Message) {
324 push(DebuginfodLogEntry(Message));
325}
326
328 {
329 std::lock_guard<std::mutex> Guard(QueueMutex);
330 LogEntryQueue.push(Entry);
331 }
332 QueueCondition.notify_one();
333}
334
336 {
337 std::unique_lock<std::mutex> Guard(QueueMutex);
338 // Wait for messages to be pushed into the queue.
339 QueueCondition.wait(Guard, [&] { return !LogEntryQueue.empty(); });
340 }
341 std::lock_guard<std::mutex> Guard(QueueMutex);
342 if (!LogEntryQueue.size())
343 llvm_unreachable("Expected message in the queue.");
344
345 DebuginfodLogEntry Entry = LogEntryQueue.front();
346 LogEntryQueue.pop();
347 return Entry;
348}
349
351 DebuginfodLog &Log,
353 double MinInterval)
354 : Log(Log), Pool(Pool), MinInterval(MinInterval) {
355 for (StringRef Path : PathsRef)
356 Paths.push_back(Path.str());
357}
358
360 std::lock_guard<sys::Mutex> Guard(UpdateMutex);
361 if (UpdateTimer.isRunning())
362 UpdateTimer.stopTimer();
363 UpdateTimer.clear();
364 for (const std::string &Path : Paths) {
365 Log.push("Updating binaries at path " + Path);
366 if (Error Err = findBinaries(Path))
367 return Err;
368 }
369 Log.push("Updated collection");
370 UpdateTimer.startTimer();
371 return Error::success();
372}
373
374Expected<bool> DebuginfodCollection::updateIfStale() {
375 if (!UpdateTimer.isRunning())
376 return false;
377 UpdateTimer.stopTimer();
378 double Time = UpdateTimer.getTotalTime().getWallTime();
379 UpdateTimer.startTimer();
380 if (Time < MinInterval)
381 return false;
382 if (Error Err = update())
383 return std::move(Err);
384 return true;
385}
386
388 while (true) {
389 if (Error Err = update())
390 return Err;
391 std::this_thread::sleep_for(Interval);
392 }
393 llvm_unreachable("updateForever loop should never end");
394}
395
396static bool hasELFMagic(StringRef FilePath) {
398 std::error_code EC = identify_magic(FilePath, Type);
399 if (EC)
400 return false;
401 switch (Type) {
402 case file_magic::elf:
407 return true;
408 default:
409 return false;
410 }
411}
412
413Error DebuginfodCollection::findBinaries(StringRef Path) {
414 std::error_code EC;
415 sys::fs::recursive_directory_iterator I(Twine(Path), EC), E;
416 std::mutex IteratorMutex;
417 ThreadPoolTaskGroup IteratorGroup(Pool);
418 for (unsigned WorkerIndex = 0; WorkerIndex < Pool.getMaxConcurrency();
419 WorkerIndex++) {
420 IteratorGroup.async([&, this]() -> void {
421 std::string FilePath;
422 while (true) {
423 {
424 // Check if iteration is over or there is an error during iteration
425 std::lock_guard<std::mutex> Guard(IteratorMutex);
426 if (I == E || EC)
427 return;
428 // Grab a file path from the directory iterator and advance the
429 // iterator.
430 FilePath = I->path();
431 I.increment(EC);
432 }
433
434 // Inspect the file at this path to determine if it is debuginfo.
435 if (!hasELFMagic(FilePath))
436 continue;
437
438 Expected<object::OwningBinary<object::Binary>> BinOrErr =
439 object::createBinary(FilePath);
440
441 if (!BinOrErr) {
442 consumeError(BinOrErr.takeError());
443 continue;
444 }
445 object::Binary *Bin = std::move(BinOrErr.get().getBinary());
446 if (!Bin->isObject())
447 continue;
448
449 // TODO: Support non-ELF binaries
450 object::ELFObjectFileBase *Object =
451 dyn_cast<object::ELFObjectFileBase>(Bin);
452 if (!Object)
453 continue;
454
455 BuildIDRef ID = getBuildID(Object);
456 if (ID.empty())
457 continue;
458
459 std::string IDString = buildIDToString(ID);
460 if (Object->hasDebugInfo()) {
461 std::lock_guard<sys::RWMutex> DebugBinariesGuard(DebugBinariesMutex);
462 (void)DebugBinaries.try_emplace(IDString, std::move(FilePath));
463 } else {
464 std::lock_guard<sys::RWMutex> BinariesGuard(BinariesMutex);
465 (void)Binaries.try_emplace(IDString, std::move(FilePath));
466 }
467 }
468 });
469 }
470 IteratorGroup.wait();
471 std::unique_lock<std::mutex> Guard(IteratorMutex);
472 if (EC)
473 return errorCodeToError(EC);
474 return Error::success();
475}
476
477Expected<std::optional<std::string>>
478DebuginfodCollection::getBinaryPath(BuildIDRef ID) {
479 Log.push("getting binary path of ID " + buildIDToString(ID));
480 std::shared_lock<sys::RWMutex> Guard(BinariesMutex);
481 auto Loc = Binaries.find(buildIDToString(ID));
482 if (Loc != Binaries.end()) {
483 std::string Path = Loc->getValue();
484 return Path;
485 }
486 return std::nullopt;
487}
488
489Expected<std::optional<std::string>>
490DebuginfodCollection::getDebugBinaryPath(BuildIDRef ID) {
491 Log.push("getting debug binary path of ID " + buildIDToString(ID));
492 std::shared_lock<sys::RWMutex> Guard(DebugBinariesMutex);
493 auto Loc = DebugBinaries.find(buildIDToString(ID));
494 if (Loc != DebugBinaries.end()) {
495 std::string Path = Loc->getValue();
496 return Path;
497 }
498 return std::nullopt;
499}
500
502 {
503 // Check collection; perform on-demand update if stale.
504 Expected<std::optional<std::string>> PathOrErr = getBinaryPath(ID);
505 if (!PathOrErr)
506 return PathOrErr.takeError();
507 std::optional<std::string> Path = *PathOrErr;
508 if (!Path) {
509 Expected<bool> UpdatedOrErr = updateIfStale();
510 if (!UpdatedOrErr)
511 return UpdatedOrErr.takeError();
512 if (*UpdatedOrErr) {
513 // Try once more.
514 PathOrErr = getBinaryPath(ID);
515 if (!PathOrErr)
516 return PathOrErr.takeError();
517 Path = *PathOrErr;
518 }
519 }
520 if (Path)
521 return *Path;
522 }
523
524 // Try federation.
526 if (!PathOrErr)
527 consumeError(PathOrErr.takeError());
528
529 // Fall back to debug binary.
530 return findDebugBinaryPath(ID);
531}
532
534 // Check collection; perform on-demand update if stale.
535 Expected<std::optional<std::string>> PathOrErr = getDebugBinaryPath(ID);
536 if (!PathOrErr)
537 return PathOrErr.takeError();
538 std::optional<std::string> Path = *PathOrErr;
539 if (!Path) {
540 Expected<bool> UpdatedOrErr = updateIfStale();
541 if (!UpdatedOrErr)
542 return UpdatedOrErr.takeError();
543 if (*UpdatedOrErr) {
544 // Try once more.
545 PathOrErr = getBinaryPath(ID);
546 if (!PathOrErr)
547 return PathOrErr.takeError();
548 Path = *PathOrErr;
549 }
550 }
551 if (Path)
552 return *Path;
553
554 // Try federation.
556}
557
559 DebuginfodCollection &Collection)
560 : Log(Log), Collection(Collection) {
561 cantFail(
562 Server.get(R"(/buildid/(.*)/debuginfo)", [&](HTTPServerRequest Request) {
563 Log.push("GET " + Request.UrlPath);
564 std::string IDString;
565 if (!tryGetFromHex(Request.UrlPathMatches[0], IDString)) {
566 Request.setResponse(
567 {404, "text/plain", "Build ID is not a hex string\n"});
568 return;
569 }
570 object::BuildID ID(IDString.begin(), IDString.end());
572 if (Error Err = PathOrErr.takeError()) {
573 consumeError(std::move(Err));
574 Request.setResponse({404, "text/plain", "Build ID not found\n"});
575 return;
576 }
577 streamFile(Request, *PathOrErr);
578 }));
579 cantFail(
580 Server.get(R"(/buildid/(.*)/executable)", [&](HTTPServerRequest Request) {
581 Log.push("GET " + Request.UrlPath);
582 std::string IDString;
583 if (!tryGetFromHex(Request.UrlPathMatches[0], IDString)) {
584 Request.setResponse(
585 {404, "text/plain", "Build ID is not a hex string\n"});
586 return;
587 }
588 object::BuildID ID(IDString.begin(), IDString.end());
589 Expected<std::string> PathOrErr = Collection.findBinaryPath(ID);
590 if (Error Err = PathOrErr.takeError()) {
591 consumeError(std::move(Err));
592 Request.setResponse({404, "text/plain", "Build ID not found\n"});
593 return;
594 }
595 streamFile(Request, *PathOrErr);
596 }));
597}
598
599} // namespace llvm
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains several declarations for the debuginfod client and server.
std::string Name
This file contains the declarations of the HTTPClient library for issuing HTTP requests and handling ...
#define I(x, y, z)
Definition: MD5.cpp:58
std::pair< uint64_t, uint64_t > Interval
if(PassOpts->AAPipeline)
This file contains some functions that are useful when dealing with strings.
Tracks a collection of debuginfod artifacts on the local filesystem.
Definition: Debuginfod.h:124
DebuginfodCollection(ArrayRef< StringRef > Paths, DebuginfodLog &Log, ThreadPoolInterface &Pool, double MinInterval)
Definition: Debuginfod.cpp:350
Expected< std::string > findBinaryPath(object::BuildIDRef)
Definition: Debuginfod.cpp:501
Error updateForever(std::chrono::milliseconds Interval)
Definition: Debuginfod.cpp:387
Expected< std::string > findDebugBinaryPath(object::BuildIDRef)
Definition: Debuginfod.cpp:533
DebuginfodLogEntry pop()
Definition: Debuginfod.cpp:335
void push(DebuginfodLogEntry Entry)
Definition: Debuginfod.cpp:327
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
A reusable client that can perform HTTPRequests through a network socket.
Definition: HTTPClient.h:53
static bool isAvailable()
Returns true only if LLVM has been compiled with a working HTTPClient.
Definition: HTTPClient.cpp:145
static bool IsInitialized
Definition: HTTPClient.h:62
unsigned responseCode()
Returns the last received response code or zero if none.
Definition: HTTPClient.cpp:158
Error perform(const HTTPRequest &Request, HTTPResponseHandler &Handler)
Performs the Request, passing response data to the Handler.
Definition: HTTPClient.cpp:153
void setTimeout(std::chrono::milliseconds Timeout)
Sets the timeout for the entire request, in milliseconds.
Definition: HTTPClient.cpp:151
Error get(StringRef UrlPathPattern, HTTPRequestHandler Handler)
Registers a URL pattern routing rule.
Definition: HTTPServer.cpp:175
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition: StringMap.h:368
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:685
This defines the abstract base interface for a ThreadPool allowing asynchronous parallel execution on...
Definition: ThreadPool.h:49
virtual unsigned getMaxConcurrency() const =0
Returns the maximum number of worker this pool can eventually grow to.
double getWallTime() const
Definition: Timer.h:43
bool isRunning() const
Check if the timer is currently running.
Definition: Timer.h:116
void stopTimer()
Stop the timer.
Definition: Timer.cpp:197
void clear()
Clear the timer state.
Definition: Timer.cpp:205
void startTimer()
Start the timer running.
Definition: Timer.cpp:190
TimeRecord getTotalTime() const
Return the duration for which this timer has been running.
Definition: Timer.h:133
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
static raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition: WithColor.cpp:85
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BuildIDRef getBuildID(const ObjectFile *Obj)
Returns the build ID, if any, contained in the given object file.
Definition: BuildID.cpp:56
ArrayRef< uint8_t > BuildIDRef
A reference to a BuildID in binary form.
Definition: BuildID.h:28
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:45
NodeAddr< CodeNode * > Code
Definition: RDFGraph.h:388
bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition: Path.cpp:569
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
Expected< std::string > getCachedOrDownloadExecutable(object::BuildIDRef ID)
Fetches an executable by searching the default local cache directory and server URLs.
std::string getDebuginfodCacheKey(StringRef UrlPath)
Returns the cache key for a given debuginfod URL path.
Definition: Debuginfod.cpp:57
uint64_t xxh3_64bits(ArrayRef< uint8_t > data)
Definition: xxhash.cpp:553
static bool isHeader(StringRef S)
Definition: Debuginfod.cpp:214
SmallVector< StringRef > getDefaultDebuginfodUrls()
Finds default array of Debuginfod server URLs by checking DEBUGINFOD_URLS environment variable.
Definition: Debuginfod.cpp:71
std::string getDebuginfodSourceUrlPath(object::BuildIDRef ID, StringRef SourceFilePath)
Get the full URL path for a source request of a given BuildID and file path.
std::function< Expected< std::unique_ptr< CachedFileStream > >(unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition: Caching.h:42
Expected< std::string > getCachedOrDownloadDebuginfo(object::BuildIDRef ID)
Fetches a debug binary by searching the default local cache directory and server URLs.
static std::string buildIDToString(BuildIDRef ID)
Definition: Debuginfod.cpp:63
std::string getDebuginfodExecutableUrlPath(object::BuildIDRef ID)
Get the full URL path for an executable request of a given BuildID.
Expected< CachePruningPolicy > parseCachePruningPolicy(StringRef PolicyStr)
Parse the given string as a cache pruning policy.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
@ argument_out_of_domain
Expected< std::string > getCachedOrDownloadArtifact(StringRef UniqueKey, StringRef UrlPath)
Fetches any debuginfod artifact using the default local cache directory and server URLs.
Definition: Debuginfod.cpp:163
std::string getDebuginfodDebuginfoUrlPath(object::BuildIDRef ID)
Get the full URL path for a debug binary request of a given BuildID.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
Expected< std::string > getCachedOrDownloadSource(object::BuildIDRef ID, StringRef SourceFilePath)
Fetches a specified source file by searching the default local cache directory and server URLs.
bool pruneCache(StringRef Path, CachePruningPolicy Policy, const std::vector< std::unique_ptr< MemoryBuffer > > &Files={})
Peform pruning using the supplied policy, returns true if pruning occurred, i.e.
std::chrono::milliseconds getDefaultDebuginfodTimeout()
Finds a default timeout for debuginfod HTTP requests.
Definition: Debuginfod.cpp:109
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
static bool hasELFMagic(StringRef FilePath)
Definition: Debuginfod.cpp:396
bool streamFile(HTTPServerRequest &Request, StringRef FilePath)
Sets the response to stream the file at FilePath, if available, and otherwise an HTTP 404 error respo...
Definition: HTTPServer.cpp:37
static SmallVector< std::string, 0 > getHeaders()
Definition: Debuginfod.cpp:224
void setDefaultDebuginfodUrls(const SmallVector< StringRef > &URLs)
Sets the list of debuginfod server URLs to query.
Definition: Debuginfod.cpp:90
std::function< Expected< AddStreamFn >(unsigned Task, StringRef Key, const Twine &ModuleName)> FileCache
This is the type of a file cache.
Definition: Caching.h:58
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
Expected< FileCache > localCache(const Twine &CacheNameRef, const Twine &TempFilePrefixRef, const Twine &CacheDirectoryPathRef, AddBufferFn AddBuffer=[](size_t Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB) {})
Create a local file system cache which uses the given cache name, temporary file prefix,...
Definition: Caching.cpp:29
bool canUseDebuginfod()
Returns false if a debuginfod lookup can be determined to have no chance of succeeding.
Definition: Debuginfod.cpp:67
Expected< std::string > getDefaultDebuginfodCacheDirectory()
Finds a default local file caching directory for the debuginfod client, first checking DEBUGINFOD_CAC...
Definition: Debuginfod.cpp:97
DebuginfodServer(DebuginfodLog &Log, DebuginfodCollection &Collection)
Definition: Debuginfod.cpp:558
DebuginfodCollection & Collection
Definition: Debuginfod.h:158
A stateless description of an outbound HTTP request.
Definition: HTTPClient.h:30
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:20
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:27
@ elf_shared_object
ELF dynamically linked shared lib.
Definition: Magic.h:29
@ elf_executable
ELF Executable image.
Definition: Magic.h:28
@ elf_core
ELF core image.
Definition: Magic.h:30
@ elf
ELF Unknown type.
Definition: Magic.h:26