20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/HTTP/HTTPClient.h"
24#include "llvm/HTTP/StreamedHTTPResponseHandler.h"
25#include "llvm/Support/Caching.h"
26#include "llvm/Support/Endian.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/raw_ostream.h"
42#define LLDB_PROPERTIES_symbollocatorsymstore
43#include "SymbolLocatorSymStoreProperties.inc"
46#define LLDB_PROPERTIES_symbollocatorsymstore
47#include "SymbolLocatorSymStorePropertiesEnum.inc"
52 static llvm::StringRef GetSettingName() {
57 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
58 m_collection_sp->Initialize(g_symbollocatorsymstore_properties_def);
61 Args GetURLs()
const {
63 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertySymStoreURLs, urls);
67 std::string GetCachePath()
const {
68 OptionValueString *s =
69 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
76 uint64_t GetTimeout()
const {
77 const uint32_t idx = ePropertyTimeout;
78 return GetPropertyAtIndexAs<uint64_t>(
79 idx, g_symbollocatorsymstore_properties[idx].default_uint_value);
82 std::optional<std::string> GetTLSCertFingerprint()
const {
83 OptionValueString *s =
84 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
85 ePropertyTLSCertFingerprint);
91 if (val.size() != 64 || !llvm::all_of(val, llvm::isHexDigit)) {
93 "plugin.symbol-locator.symstore.tls-cert-fingerprint: expected a "
94 "64-character hex string (SHA-256), but got '{0}', ignoring",
105 static PluginProperties g_settings;
116 llvm::HTTPClient::initialize();
119 if (std::error_code ec = llvm::sys::fs::create_directories(default_cache)) {
121 "default SymStore cache directory '{0}' is not accessible: {1}",
122 default_cache, ec.message()));
128 debugger, PluginProperties::GetSettingName())) {
129 constexpr bool is_global_setting =
true;
132 "Properties for the SymStore Symbol Locator plug-in.",
139 llvm::HTTPClient::cleanup();
143 return "Symbol locator for PDB in SymStore";
154 entry.
source = source.str();
155 entry.
cache = std::nullopt;
160 llvm::StringRef cache) {
162 entry.
source = source.str();
163 entry.
cache = cache.str();
167std::vector<SymbolLocatorSymStore::LookupEntry> GetGlobalLookupOrder() {
168 std::vector<SymbolLocatorSymStore::LookupEntry> result;
170 const char *sym_path = std::getenv(
"_NT_SYMBOL_PATH");
172 result.push_back(std::move(entry));
174 const char *alt_path = std::getenv(
"_NT_ALT_SYMBOL_PATH");
176 result.push_back(std::move(entry));
179 result.push_back(MakeLookupEntry(url.ref()));
184std::optional<SymbolLocatorSymStore::LookupEntry>
185ParseSrvEntry(llvm::StringRef entry) {
186 llvm::SmallVector<llvm::StringRef, 4> parts;
187 entry.trim().split(parts,
'*');
190 switch (parts.size()) {
192 return MakeLookupEntry(parts[1]);
195 if (parts[1].empty())
196 return MakeLookupEntry(parts[2],
198 return MakeLookupEntry(parts[2], parts[1]);
205std::optional<std::string> ParseCacheEntry(llvm::StringRef entry) {
206 llvm::SmallVector<llvm::StringRef, 2> parts;
207 entry.trim().split(parts,
'*');
210 if (parts.size() > 2)
214 llvm::StringRef value;
215 if (parts.size() == 2)
216 value = parts.back();
232std::string FormatSymStoreKey(
const UUID &uuid) {
233 llvm::ArrayRef<uint8_t> bytes = uuid.
GetBytes();
234 uint32_t age = llvm::support::endian::read32be(bytes.data() + 16);
235 constexpr bool lower_case =
false;
236 return llvm::toHex(bytes.slice(0, 16), lower_case) + std::to_string(age);
239bool HasUnsafeCharacters(llvm::StringRef s) {
240 for (
unsigned char c : s) {
242 if ((c >=
'A' && c <=
'Z') || (c >=
'a' && c <=
'z') ||
243 (c >=
'0' && c <=
'9') || c ==
'-' || c ==
'.' || c ==
'_' ||
252 return s ==
"." || s ==
"..";
255std::optional<FileSpec>
256RequestFileFromSymStoreServerHTTP(llvm::StringRef base_url, llvm::StringRef key,
257 llvm::StringRef pdb_name) {
258 using namespace llvm::sys;
261 if (HasUnsafeCharacters(pdb_name)) {
263 "rejecting HTTP lookup for PDB file due to unsafe characters in "
269 if (!llvm::HTTPClient::isAvailable()) {
271 "HTTP client is not available for SymStore download");
277 llvm::SmallString<128> tmp_model;
278 constexpr bool erase_on_reboot =
true;
279 path::system_temp_directory(erase_on_reboot, tmp_model);
280 path::append(tmp_model,
281 llvm::formatv(
"lldb_symstore_{0}_{1}.%%%%%%", key, pdb_name));
283 llvm::SmallString<128> tmp_file;
284 if (std::error_code ec = fs::createUniqueFile(tmp_model, tmp_file)) {
286 "failed to create a temporary file to download '{0}' into: {1}",
287 pdb_name, ec.message()));
292 llvm::scope_exit remove_tmp_file([&] { fs::remove(tmp_file.str()); });
295 std::string source_url =
296 llvm::formatv(
"{0}/{1}/{2}/{1}", base_url, pdb_name, key);
298 llvm::HTTPClient client;
302 llvm::StreamedHTTPResponseHandler Handler(
303 [dest = tmp_file.str().str()]()
304 -> llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> {
306 auto os = std::make_unique<llvm::raw_fd_ostream>(dest, ec);
308 return llvm::createStringError(ec,
"Failed to open file for writing");
309 return std::make_unique<llvm::CachedFileStream>(std::move(os), dest);
313 llvm::HTTPRequest request(source_url);
314 request.PinnedCertFingerprint =
316 if (llvm::Error Err = client.perform(request, Handler)) {
317 Err = llvm::joinErrors(std::move(Err), Handler.abort());
319 llvm::formatv(
"failed to download from SymStore '{0}': {1}", source_url,
320 llvm::toString(std::move(Err))));
323 if (llvm::Error Err = Handler.commit()) {
325 llvm::formatv(
"failed to download from SymStore '{0}': {1}", source_url,
326 llvm::toString(std::move(Err))));
330 unsigned responseCode = client.responseCode();
331 switch (responseCode) {
333 remove_tmp_file.release();
339 "failed to download from SymStore '{0}': response code {1}", source_url,
345std::optional<FileSpec> FindFileInLocalSymStore(llvm::StringRef root_dir,
347 llvm::StringRef pdb_name) {
348 llvm::SmallString<256> path;
349 llvm::sys::path::append(path, root_dir, pdb_name, key, pdb_name);
362 DownloadLock(llvm::StringRef cache, llvm::StringRef key,
363 llvm::StringRef pdb_name)
364 : m_key(llvm::formatv(
"{0}/{1}/{2}", cache, key, pdb_name)) {
366 std::lock_guard<std::mutex> guard(GetMapMutex());
367 std::shared_ptr<Entry> &entry = GetMap()[m_key];
369 entry = std::make_shared<Entry>();
372 m_entry->mutex.lock();
376 m_entry->mutex.unlock();
377 std::lock_guard<std::mutex> guard(GetMapMutex());
379 auto it = GetMap().find(m_key);
380 if (it != GetMap().end() && it->second.use_count() == 1)
384 DownloadLock(
const DownloadLock &) =
delete;
385 DownloadLock &operator=(
const DownloadLock &) =
delete;
392 static std::mutex &GetMapMutex() {
393 static std::mutex g_mutex;
397 static llvm::StringMap<std::shared_ptr<Entry>> &GetMap() {
398 static llvm::StringMap<std::shared_ptr<Entry>> g_map;
403 std::shared_ptr<Entry> m_entry;
406std::optional<FileSpec> MoveToLocalSymStore(llvm::StringRef cache,
408 llvm::StringRef pdb_name,
411 llvm::SmallString<256> dest_dir;
412 llvm::sys::path::append(dest_dir, cache, pdb_name, key);
413 if (std::error_code ec = llvm::sys::fs::create_directories(dest_dir)) {
415 llvm::formatv(
"failed to create SymStore cache directory '{0}': {1}",
416 dest_dir, ec.message()));
420 llvm::SmallString<256> dest;
421 llvm::sys::path::append(dest, dest_dir, pdb_name);
422 std::error_code ec = llvm::sys::fs::rename(tmp_file.
GetPath(), dest);
427 if (ec == std::errc::cross_device_link) {
428 llvm::SmallString<256> staged;
429 if ((ec = llvm::sys::fs::createUniqueFile(dest +
".%%%%%%", staged))) {
431 "failed to create a temporary file in SymStore cache '{0}': {1}",
432 dest_dir, ec.message()));
435 llvm::scope_exit remove_staged([&] { llvm::sys::fs::remove(staged); });
436 if (!(ec = llvm::sys::fs::copy_file(tmp_file.
GetPath(), staged)) &&
437 !(ec = llvm::sys::fs::rename(staged, dest))) {
438 remove_staged.release();
439 llvm::sys::fs::remove(tmp_file.
GetPath());
444 llvm::formatv(
"failed to move '{0}' to SymStore cache '{1}': {2}",
445 tmp_file.
GetPath(), dest, ec.message()));
452std::string SelectSymStoreCache(std::optional<std::string> sympath_cache) {
453 llvm::SmallVector<std::string, 2> candidates;
457 assert(!sympath_cache->empty() &&
"Empty entries resolve to default cache");
458 candidates.push_back(*sympath_cache);
465 for (
const auto &path : candidates) {
466 if (llvm::sys::fs::is_directory(path))
468 if (std::error_code ec = llvm::sys::fs::create_directories(path)) {
469 LLDB_LOG(log,
"Ignoring invalid SymStore cache directory '{0}': {1}",
480std::optional<FileSpec>
482 llvm::StringRef key, llvm::StringRef pdb_name) {
484 llvm::StringRef url = entry.
source;
485 if (url.starts_with(
"http://") || url.starts_with(
"https://")) {
486 std::string cache_path = SelectSymStoreCache(entry.
cache);
491 DownloadLock lock(cache_path, key, pdb_name);
494 if (
auto spec = FindFileInLocalSymStore(cache_path, key, pdb_name)) {
495 LLDB_LOG(log,
"Found {0} in SymStore cache {1}", pdb_name, cache_path);
500 if (
auto tmp_file = RequestFileFromSymStoreServerHTTP(url, key, pdb_name)) {
501 LLDB_LOG(log,
"Downloaded {0} from SymStore {1}", pdb_name, url);
502 auto spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
507 spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
511 LLDB_LOG(log,
"Added {0} to SymStore cache {1}", pdb_name, cache_path);
518 llvm::StringRef file = entry.
source;
519 if (file.starts_with(
"file://"))
520 file = file.drop_front(7);
521 if (
auto spec = FindFileInLocalSymStore(file, key, pdb_name)) {
522 LLDB_LOG(log,
"Found {0} in local SymStore {1}", pdb_name, file);
540 if (pdb_name.empty()) {
541 LLDB_LOG(log,
"Failed to resolve symbol PDB module: PDB name empty");
545 LLDB_LOG(log,
"LocateExecutableSymbolFile {0} with UUID {1}", pdb_name,
548 LLDB_LOG(log,
"Failed to resolve symbol PDB module: UUID invalid");
552 std::string key = FormatSymStoreKey(uuid);
553 for (
const LookupEntry &entry : GetGlobalLookupOrder()) {
554 if (
auto spec = LocateSymStoreEntry(entry, key, pdb_name))
561std::vector<SymbolLocatorSymStore::LookupEntry>
566 std::vector<LookupEntry> result;
567 std::optional<std::string> implicit_cache;
568 llvm::SmallVector<llvm::StringRef, 2> entries;
569 val.split(entries,
';');
571 for (llvm::StringRef raw : entries) {
572 llvm::StringRef entry = raw.trim();
578 if (entry.starts_with_insensitive(
"cache*")) {
579 if (
auto cache = ParseCacheEntry(entry))
580 implicit_cache = *cache;
586 if (entry.starts_with_insensitive(
"symsrv*")) {
588 llvm::formatv(
"ignoring unsupported entry in env: {0}", entry));
594 if (entry.starts_with_insensitive(
"srv*")) {
595 if (
auto lookup_entry = ParseSrvEntry(entry)) {
596 if (!lookup_entry->cache && implicit_cache)
597 lookup_entry->cache = implicit_cache;
598 result.push_back(*lookup_entry);
604 result.push_back(MakeLookupEntry(entry));
612 llvm::SmallString<128> cache_dir;
613 if (llvm::sys::path::cache_directory(cache_dir)) {
614 llvm::sys::path::append(cache_dir,
"lldb",
"symstore");
615 return cache_dir.str().str();
618 constexpr bool erase_on_reboot =
false;
619 llvm::sys::path::system_temp_directory(erase_on_reboot, cache_dir);
620 llvm::sys::path::append(cache_dir,
"lldb",
"symstore");
621 return cache_dir.str().str();
static PluginProperties & GetGlobalPluginProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_PLUGIN_DEFINE(PluginName)
static PluginProperties & GetGlobalPluginProperties()
A class to manage flag bits.
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
llvm::StringRef GetFilename() const
Filename string const get accessor.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
static FileSystem & Instance()
static ModuleListProperties & GetGlobalModuleListProperties()
FileSpec & GetSymbolFileSpec()
llvm::StringRef GetCurrentValueAsRef() const
const char * GetCurrentValue() const
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForSymbolLocatorPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
static bool CreateSettingForSymbolLocatorPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
This plugin implements lookup in Microsoft SymStore instances.
static void DebuggerInitialize(Debugger &debugger)
static lldb_private::SymbolLocator * CreateInstance()
static llvm::StringRef GetPluginNameStatic()
static llvm::StringRef GetPluginDescriptionStatic()
static std::optional< FileSpec > LocateExecutableSymbolFile(const ModuleSpec &module_spec, const FileSpecList &default_search_paths)
static std::string GetSystemDefaultCachePath()
static std::vector< LookupEntry > ParseEnvSymbolPaths(llvm::StringRef val)
Represents UUID's of various sizes.
llvm::ArrayRef< uint8_t > GetBytes() const
std::string GetAsString(llvm::StringRef separator="-") const
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
std::optional< std::string > cache