20#include "llvm/ADT/StringExtras.h"
21#include "llvm/HTTP/HTTPClient.h"
22#include "llvm/HTTP/StreamedHTTPResponseHandler.h"
23#include "llvm/Support/Caching.h"
24#include "llvm/Support/Endian.h"
25#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/raw_ostream.h"
37#define LLDB_PROPERTIES_symbollocatorsymstore
38#include "SymbolLocatorSymStoreProperties.inc"
41#define LLDB_PROPERTIES_symbollocatorsymstore
42#include "SymbolLocatorSymStorePropertiesEnum.inc"
47 static llvm::StringRef GetSettingName() {
52 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
53 m_collection_sp->Initialize(g_symbollocatorsymstore_properties_def);
56 Args GetURLs()
const {
58 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertySymStoreURLs, urls);
62 std::string GetCachePath()
const {
63 OptionValueString *s =
64 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
71 uint64_t GetTimeout()
const {
72 const uint32_t idx = ePropertyTimeout;
73 return GetPropertyAtIndexAs<uint64_t>(
74 idx, g_symbollocatorsymstore_properties[idx].default_uint_value);
77 std::optional<std::string> GetTLSCertFingerprint()
const {
78 OptionValueString *s =
79 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
80 ePropertyTLSCertFingerprint);
86 if (val.size() != 64 || !llvm::all_of(val, llvm::isHexDigit)) {
88 "plugin.symbol-locator.symstore.tls-cert-fingerprint: expected a "
89 "64-character hex string (SHA-256), but got '{0}', ignoring",
100 static PluginProperties g_settings;
111 llvm::HTTPClient::initialize();
114 if (std::error_code ec = llvm::sys::fs::create_directories(default_cache)) {
116 "default SymStore cache directory '{0}' is not accessible: {1}",
117 default_cache, ec.message()));
123 debugger, PluginProperties::GetSettingName())) {
124 constexpr bool is_global_setting =
true;
127 "Properties for the SymStore Symbol Locator plug-in.",
134 llvm::HTTPClient::cleanup();
138 return "Symbol locator for PDB in SymStore";
149 entry.
source = source.str();
150 entry.
cache = std::nullopt;
155 llvm::StringRef cache) {
157 entry.
source = source.str();
158 entry.
cache = cache.str();
162std::vector<SymbolLocatorSymStore::LookupEntry> GetGlobalLookupOrder() {
163 std::vector<SymbolLocatorSymStore::LookupEntry> result;
165 const char *sym_path = std::getenv(
"_NT_SYMBOL_PATH");
167 result.push_back(std::move(entry));
169 const char *alt_path = std::getenv(
"_NT_ALT_SYMBOL_PATH");
171 result.push_back(std::move(entry));
174 result.push_back(MakeLookupEntry(url.ref()));
179std::optional<SymbolLocatorSymStore::LookupEntry>
180ParseSrvEntry(llvm::StringRef entry) {
181 llvm::SmallVector<llvm::StringRef, 4> parts;
182 entry.trim().split(parts,
'*');
185 switch (parts.size()) {
187 return MakeLookupEntry(parts[1]);
190 if (parts[1].empty())
191 return MakeLookupEntry(parts[2],
193 return MakeLookupEntry(parts[2], parts[1]);
200std::optional<std::string> ParseCacheEntry(llvm::StringRef entry) {
201 llvm::SmallVector<llvm::StringRef, 2> parts;
202 entry.trim().split(parts,
'*');
205 if (parts.size() > 2)
209 llvm::StringRef value;
210 if (parts.size() == 2)
211 value = parts.back();
227std::string FormatSymStoreKey(
const UUID &uuid) {
228 llvm::ArrayRef<uint8_t> bytes = uuid.
GetBytes();
229 uint32_t age = llvm::support::endian::read32be(bytes.data() + 16);
230 constexpr bool lower_case =
false;
231 return llvm::toHex(bytes.slice(0, 16), lower_case) + std::to_string(age);
234bool HasUnsafeCharacters(llvm::StringRef s) {
235 for (
unsigned char c : s) {
237 if ((c >=
'A' && c <=
'Z') || (c >=
'a' && c <=
'z') ||
238 (c >=
'0' && c <=
'9') || c ==
'-' || c ==
'.' || c ==
'_' ||
247 return s ==
"." || s ==
"..";
250std::optional<FileSpec>
251RequestFileFromSymStoreServerHTTP(llvm::StringRef base_url, llvm::StringRef key,
252 llvm::StringRef pdb_name) {
253 using namespace llvm::sys;
256 if (HasUnsafeCharacters(pdb_name)) {
258 "rejecting HTTP lookup for PDB file due to unsafe characters in "
265 llvm::SmallString<128> tmp_file;
266 constexpr bool erase_on_reboot =
true;
267 path::system_temp_directory(erase_on_reboot, tmp_file);
268 path::append(tmp_file, llvm::formatv(
"lldb_symstore_{0}_{1}", key, pdb_name));
271 std::string source_url =
272 llvm::formatv(
"{0}/{1}/{2}/{1}", base_url, pdb_name, key);
274 if (!llvm::HTTPClient::isAvailable()) {
276 "HTTP client is not available for SymStore download");
280 llvm::HTTPClient client;
284 llvm::StreamedHTTPResponseHandler Handler(
285 [dest = tmp_file.str().str()]()
286 -> llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> {
288 auto os = std::make_unique<llvm::raw_fd_ostream>(dest, ec);
290 return llvm::createStringError(ec,
"Failed to open file for writing");
291 return std::make_unique<llvm::CachedFileStream>(std::move(os), dest);
295 llvm::HTTPRequest request(source_url);
296 request.PinnedCertFingerprint =
298 if (llvm::Error Err = client.perform(request, Handler)) {
300 llvm::formatv(
"failed to download from SymStore '{0}': {1}", source_url,
301 llvm::toString(std::move(Err))));
304 if (llvm::Error Err = Handler.commit()) {
306 llvm::formatv(
"failed to download from SymStore '{0}': {1}", source_url,
307 llvm::toString(std::move(Err))));
311 unsigned responseCode = client.responseCode();
312 switch (responseCode) {
319 "failed to download from SymStore '{0}': response code {1}", source_url,
325std::optional<FileSpec> FindFileInLocalSymStore(llvm::StringRef root_dir,
327 llvm::StringRef pdb_name) {
328 llvm::SmallString<256> path;
329 llvm::sys::path::append(path, root_dir, pdb_name, key, pdb_name);
337std::optional<FileSpec> MoveToLocalSymStore(llvm::StringRef cache,
339 llvm::StringRef pdb_name,
342 llvm::SmallString<256> dest_dir;
343 llvm::sys::path::append(dest_dir, cache, pdb_name, key);
344 if (std::error_code ec = llvm::sys::fs::create_directories(dest_dir)) {
346 llvm::formatv(
"failed to create SymStore cache directory '{0}': {1}",
347 dest_dir, ec.message()));
351 llvm::SmallString<256> dest;
352 llvm::sys::path::append(dest, dest_dir, pdb_name);
353 std::error_code ec = llvm::sys::fs::rename(tmp_file.
GetPath(), dest);
356 if (ec == std::errc::cross_device_link) {
357 ec = llvm::sys::fs::copy_file(tmp_file.
GetPath(), dest);
359 llvm::sys::fs::remove(tmp_file.
GetPath());
363 llvm::formatv(
"failed to move '{0}' to SymStore cache '{1}': {2}",
364 tmp_file.
GetPath(), dest, ec.message()));
371std::string SelectSymStoreCache(std::optional<std::string> sympath_cache) {
372 llvm::SmallVector<std::string, 2> candidates;
376 assert(!sympath_cache->empty() &&
"Empty entries resolve to default cache");
377 candidates.push_back(*sympath_cache);
384 for (
const auto &path : candidates) {
385 if (llvm::sys::fs::is_directory(path))
387 if (std::error_code ec = llvm::sys::fs::create_directories(path)) {
388 LLDB_LOG(log,
"Ignoring invalid SymStore cache directory '{0}': {1}",
399std::optional<FileSpec>
401 llvm::StringRef key, llvm::StringRef pdb_name) {
403 llvm::StringRef url = entry.
source;
404 if (url.starts_with(
"http://") || url.starts_with(
"https://")) {
406 std::string cache_path = SelectSymStoreCache(entry.
cache);
407 if (
auto spec = FindFileInLocalSymStore(cache_path, key, pdb_name)) {
408 LLDB_LOG(log,
"Found {0} in SymStore cache {1}", pdb_name, cache_path);
413 if (
auto tmp_file = RequestFileFromSymStoreServerHTTP(url, key, pdb_name)) {
414 LLDB_LOG(log,
"Downloaded {0} from SymStore {1}", pdb_name, url);
415 auto spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
420 spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
424 LLDB_LOG(log,
"Added {0} to SymStore cache {1}", pdb_name, cache_path);
431 llvm::StringRef file = entry.
source;
432 if (file.starts_with(
"file://"))
433 file = file.drop_front(7);
434 if (
auto spec = FindFileInLocalSymStore(file, key, pdb_name)) {
435 LLDB_LOG(log,
"Found {0} in local SymStore {1}", pdb_name, file);
453 if (pdb_name.empty()) {
454 LLDB_LOG(log,
"Failed to resolve symbol PDB module: PDB name empty");
458 LLDB_LOG(log,
"LocateExecutableSymbolFile {0} with UUID {1}", pdb_name,
461 LLDB_LOG(log,
"Failed to resolve symbol PDB module: UUID invalid");
465 std::string key = FormatSymStoreKey(uuid);
466 for (
const LookupEntry &entry : GetGlobalLookupOrder()) {
467 if (
auto spec = LocateSymStoreEntry(entry, key, pdb_name))
474std::vector<SymbolLocatorSymStore::LookupEntry>
479 std::vector<LookupEntry> result;
480 std::optional<std::string> implicit_cache;
481 llvm::SmallVector<llvm::StringRef, 2> entries;
482 val.split(entries,
';');
484 for (llvm::StringRef raw : entries) {
485 llvm::StringRef entry = raw.trim();
491 if (entry.starts_with_insensitive(
"cache*")) {
492 if (
auto cache = ParseCacheEntry(entry))
493 implicit_cache = *cache;
499 if (entry.starts_with_insensitive(
"symsrv*")) {
501 llvm::formatv(
"ignoring unsupported entry in env: {0}", entry));
507 if (entry.starts_with_insensitive(
"srv*")) {
508 if (
auto lookup_entry = ParseSrvEntry(entry)) {
509 if (!lookup_entry->cache && implicit_cache)
510 lookup_entry->cache = implicit_cache;
511 result.push_back(*lookup_entry);
517 result.push_back(MakeLookupEntry(entry));
525 llvm::SmallString<128> cache_dir;
526 if (llvm::sys::path::cache_directory(cache_dir)) {
527 llvm::sys::path::append(cache_dir,
"lldb",
"symstore");
528 return cache_dir.str().str();
531 constexpr bool erase_on_reboot =
false;
532 llvm::sys::path::system_temp_directory(erase_on_reboot, cache_dir);
533 llvm::sys::path::append(cache_dir,
"lldb",
"symstore");
534 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