[Go to site: main page, start]

LLDB mainline
SymbolLocatorSymStore.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10
15#include "lldb/Utility/Args.h"
17#include "lldb/Utility/Log.h"
18#include "lldb/Utility/UUID.h"
19
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"
31
32#include <memory>
33#include <mutex>
34
35using namespace lldb;
36using namespace lldb_private;
37
39
40namespace {
41
42#define LLDB_PROPERTIES_symbollocatorsymstore
43#include "SymbolLocatorSymStoreProperties.inc"
44
45enum {
46#define LLDB_PROPERTIES_symbollocatorsymstore
47#include "SymbolLocatorSymStorePropertiesEnum.inc"
48};
49
50class PluginProperties : public Properties {
51public:
52 static llvm::StringRef GetSettingName() {
54 }
55
56 PluginProperties() {
57 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
58 m_collection_sp->Initialize(g_symbollocatorsymstore_properties_def);
59 }
60
61 Args GetURLs() const {
62 Args urls;
63 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertySymStoreURLs, urls);
64 return urls;
65 }
66
67 std::string GetCachePath() const {
68 OptionValueString *s =
69 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
70 ePropertyCachePath);
71 if (s && !s->GetCurrentValueAsRef().empty())
72 return s->GetCurrentValue();
74 }
75
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);
80 }
81
82 std::optional<std::string> GetTLSCertFingerprint() const {
83 OptionValueString *s =
84 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
85 ePropertyTLSCertFingerprint);
86 if (!s)
87 return {};
88 llvm::StringRef val = s->GetCurrentValueAsRef();
89 if (val.empty())
90 return {};
91 if (val.size() != 64 || !llvm::all_of(val, llvm::isHexDigit)) {
92 Debugger::ReportWarning(llvm::formatv(
93 "plugin.symbol-locator.symstore.tls-cert-fingerprint: expected a "
94 "64-character hex string (SHA-256), but got '{0}', ignoring",
95 val));
96 return {};
97 }
98 return val.lower();
99 }
100};
101
102} // namespace
103
104static PluginProperties &GetGlobalPluginProperties() {
105 static PluginProperties g_settings;
106 return g_settings;
107}
108
110
114 nullptr, LocateExecutableSymbolFile, nullptr, nullptr,
116 llvm::HTTPClient::initialize();
117
118 std::string default_cache = GetSystemDefaultCachePath();
119 if (std::error_code ec = llvm::sys::fs::create_directories(default_cache)) {
120 Debugger::ReportWarning(llvm::formatv(
121 "default SymStore cache directory '{0}' is not accessible: {1}",
122 default_cache, ec.message()));
123 }
124}
125
128 debugger, PluginProperties::GetSettingName())) {
129 constexpr bool is_global_setting = true;
131 debugger, GetGlobalPluginProperties().GetValueProperties(),
132 "Properties for the SymStore Symbol Locator plug-in.",
133 is_global_setting);
134 }
135}
136
139 llvm::HTTPClient::cleanup();
140}
141
143 return "Symbol locator for PDB in SymStore";
144}
145
149
150namespace {
151
152SymbolLocatorSymStore::LookupEntry MakeLookupEntry(llvm::StringRef source) {
154 entry.source = source.str();
155 entry.cache = std::nullopt;
156 return entry;
157}
158
159SymbolLocatorSymStore::LookupEntry MakeLookupEntry(llvm::StringRef source,
160 llvm::StringRef cache) {
162 entry.source = source.str();
163 entry.cache = cache.str();
164 return entry;
165}
166
167std::vector<SymbolLocatorSymStore::LookupEntry> GetGlobalLookupOrder() {
168 std::vector<SymbolLocatorSymStore::LookupEntry> result;
169
170 const char *sym_path = std::getenv("_NT_SYMBOL_PATH");
171 for (auto entry : SymbolLocatorSymStore::ParseEnvSymbolPaths(sym_path))
172 result.push_back(std::move(entry));
173
174 const char *alt_path = std::getenv("_NT_ALT_SYMBOL_PATH");
175 for (auto entry : SymbolLocatorSymStore::ParseEnvSymbolPaths(alt_path))
176 result.push_back(std::move(entry));
177
178 for (const auto &url : GetGlobalPluginProperties().GetURLs())
179 result.push_back(MakeLookupEntry(url.ref()));
180
181 return result;
182}
183
184std::optional<SymbolLocatorSymStore::LookupEntry>
185ParseSrvEntry(llvm::StringRef entry) {
186 llvm::SmallVector<llvm::StringRef, 4> parts;
187 entry.trim().split(parts, '*');
188
189 // Format is: srv*[LocalCache*]SymbolStore
190 switch (parts.size()) {
191 case 2:
192 return MakeLookupEntry(parts[1]);
193 case 3: {
194 // Fall back to the configured default cache for empty values.
195 if (parts[1].empty())
196 return MakeLookupEntry(parts[2],
197 GetGlobalPluginProperties().GetCachePath());
198 return MakeLookupEntry(parts[2], parts[1]);
199 }
200 default:
201 return {}; // Ignore entries with invalid number of parts.
202 }
203}
204
205std::optional<std::string> ParseCacheEntry(llvm::StringRef entry) {
206 llvm::SmallVector<llvm::StringRef, 2> parts;
207 entry.trim().split(parts, '*');
208
209 // Ignore entries with invalid number of parts.
210 if (parts.size() > 2)
211 return {};
212
213 // Empty cache* deliberatly specifies the default cache path.
214 llvm::StringRef value;
215 if (parts.size() == 2)
216 value = parts.back();
217
218 // Fall back to LLDB's default cache for empty values.
219 if (value.empty())
220 return GetGlobalPluginProperties().GetCachePath();
221
222 return value.str();
223}
224
225// RSDS entries store identity as a 20-byte UUID composed of 16-byte GUID and
226// 4-byte age:
227// 12345678-1234-5678-9ABC-DEF012345678-00000001
228//
229// SymStore key is a string with no separators and age as decimal:
230// 12345678123456789ABCDEF0123456781
231//
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);
237}
238
239bool HasUnsafeCharacters(llvm::StringRef s) {
240 for (unsigned char c : s) {
241 // RFC 3986 unreserved characters are safe for file names and URLs.
242 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
243 (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
244 c == '~') {
245 continue;
246 }
247
248 return true;
249 }
250
251 // Avoid path semantics issues.
252 return s == "." || s == "..";
253}
254
255std::optional<FileSpec>
256RequestFileFromSymStoreServerHTTP(llvm::StringRef base_url, llvm::StringRef key,
257 llvm::StringRef pdb_name) {
258 using namespace llvm::sys;
259
260 // Make sure URL will be valid, portable, and compatible with symbol servers.
261 if (HasUnsafeCharacters(pdb_name)) {
262 Debugger::ReportWarning(llvm::formatv(
263 "rejecting HTTP lookup for PDB file due to unsafe characters in "
264 "name: {0}",
265 pdb_name));
266 return {};
267 }
268
269 if (!llvm::HTTPClient::isAvailable()) {
271 "HTTP client is not available for SymStore download");
272 return {};
273 }
274
275 // Download into a temporary file. The name must be unique: lookups for the
276 // same file can be in flight concurrently.
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));
282
283 llvm::SmallString<128> tmp_file;
284 if (std::error_code ec = fs::createUniqueFile(tmp_model, tmp_file)) {
285 Debugger::ReportWarning(llvm::formatv(
286 "failed to create a temporary file to download '{0}' into: {1}",
287 pdb_name, ec.message()));
288 return {};
289 }
290
291 // Clean up the temporary file unless we hand it off to the caller.
292 llvm::scope_exit remove_tmp_file([&] { fs::remove(tmp_file.str()); });
293
294 // Server has SymStore directory structure with forward slashes as separators.
295 std::string source_url =
296 llvm::formatv("{0}/{1}/{2}/{1}", base_url, pdb_name, key);
297
298 llvm::HTTPClient client;
299 client.setTimeout(
300 std::chrono::seconds(GetGlobalPluginProperties().GetTimeout()));
301
302 llvm::StreamedHTTPResponseHandler Handler(
303 [dest = tmp_file.str().str()]()
304 -> llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> {
305 std::error_code ec;
306 auto os = std::make_unique<llvm::raw_fd_ostream>(dest, ec);
307 if (ec)
308 return llvm::createStringError(ec, "Failed to open file for writing");
309 return std::make_unique<llvm::CachedFileStream>(std::move(os), dest);
310 },
311 client);
312
313 llvm::HTTPRequest request(source_url);
314 request.PinnedCertFingerprint =
315 GetGlobalPluginProperties().GetTLSCertFingerprint();
316 if (llvm::Error Err = client.perform(request, Handler)) {
318 llvm::formatv("failed to download from SymStore '{0}': {1}", source_url,
319 llvm::toString(std::move(Err))));
320 return {};
321 }
322 if (llvm::Error Err = Handler.commit()) {
324 llvm::formatv("failed to download from SymStore '{0}': {1}", source_url,
325 llvm::toString(std::move(Err))));
326 return {};
327 }
328
329 unsigned responseCode = client.responseCode();
330 switch (responseCode) {
331 case 200:
332 remove_tmp_file.release();
333 return FileSpec(tmp_file.str()); // success
334 case 404:
335 return {}; // file not found
336 default:
337 Debugger::ReportWarning(llvm::formatv(
338 "failed to download from SymStore '{0}': response code {1}", source_url,
339 responseCode));
340 return {};
341 }
342}
343
344std::optional<FileSpec> FindFileInLocalSymStore(llvm::StringRef root_dir,
345 llvm::StringRef key,
346 llvm::StringRef pdb_name) {
347 llvm::SmallString<256> path;
348 llvm::sys::path::append(path, root_dir, pdb_name, key, pdb_name);
349 FileSpec spec(path);
350 if (!FileSystem::Instance().Exists(spec))
351 return {};
352
353 return spec;
354}
355
356/// Synchronizes lookups that resolve to the same cache entry. Lookups for
357/// different entries never contend. The map is proportional to the number of
358/// lookups in flight, not the number of symbols resolved.
359class DownloadLock {
360public:
361 DownloadLock(llvm::StringRef cache, llvm::StringRef key,
362 llvm::StringRef pdb_name)
363 : m_key(llvm::formatv("{0}/{1}/{2}", cache, key, pdb_name)) {
364 {
365 std::lock_guard<std::mutex> guard(GetMapMutex());
366 std::shared_ptr<Entry> &entry = GetMap()[m_key];
367 if (!entry)
368 entry = std::make_shared<Entry>();
369 m_entry = entry;
370 }
371 m_entry->mutex.lock();
372 }
373
374 ~DownloadLock() {
375 m_entry->mutex.unlock();
376 std::lock_guard<std::mutex> guard(GetMapMutex());
377 m_entry.reset();
378 auto it = GetMap().find(m_key);
379 if (it != GetMap().end() && it->second.use_count() == 1)
380 GetMap().erase(it);
381 }
382
383 DownloadLock(const DownloadLock &) = delete;
384 DownloadLock &operator=(const DownloadLock &) = delete;
385
386private:
387 struct Entry {
388 std::mutex mutex;
389 };
390
391 static std::mutex &GetMapMutex() {
392 static std::mutex g_mutex;
393 return g_mutex;
394 }
395
396 static llvm::StringMap<std::shared_ptr<Entry>> &GetMap() {
397 static llvm::StringMap<std::shared_ptr<Entry>> g_map;
398 return g_map;
399 }
400
401 std::string m_key;
402 std::shared_ptr<Entry> m_entry;
403};
404
405std::optional<FileSpec> MoveToLocalSymStore(llvm::StringRef cache,
406 llvm::StringRef key,
407 llvm::StringRef pdb_name,
408 FileSpec tmp_file) {
409 // Caches have SymStore directory structure: cache/pdb_name/key/pdb_name
410 llvm::SmallString<256> dest_dir;
411 llvm::sys::path::append(dest_dir, cache, pdb_name, key);
412 if (std::error_code ec = llvm::sys::fs::create_directories(dest_dir)) {
414 llvm::formatv("failed to create SymStore cache directory '{0}': {1}",
415 dest_dir, ec.message()));
416 return {};
417 }
418
419 llvm::SmallString<256> dest;
420 llvm::sys::path::append(dest, dest_dir, pdb_name);
421 std::error_code ec = llvm::sys::fs::rename(tmp_file.GetPath(), dest);
422
423 // Fall back to copy+delete if we move to a different volume. Copy next to
424 // the destination and rename, so a concurrent lookup never observes a
425 // partially written file at the cache location.
426 if (ec == std::errc::cross_device_link) {
427 llvm::SmallString<256> staged;
428 if ((ec = llvm::sys::fs::createUniqueFile(dest + ".%%%%%%", staged))) {
429 Debugger::ReportWarning(llvm::formatv(
430 "failed to create a temporary file in SymStore cache '{0}': {1}",
431 dest_dir, ec.message()));
432 return {};
433 }
434 llvm::scope_exit remove_staged([&] { llvm::sys::fs::remove(staged); });
435 if (!(ec = llvm::sys::fs::copy_file(tmp_file.GetPath(), staged)) &&
436 !(ec = llvm::sys::fs::rename(staged, dest))) {
437 remove_staged.release();
438 llvm::sys::fs::remove(tmp_file.GetPath());
439 }
440 }
441 if (ec) {
443 llvm::formatv("failed to move '{0}' to SymStore cache '{1}': {2}",
444 tmp_file.GetPath(), dest, ec.message()));
445 return {};
446 }
447
448 return FileSpec(dest.str());
449}
450
451std::string SelectSymStoreCache(std::optional<std::string> sympath_cache) {
452 llvm::SmallVector<std::string, 2> candidates;
453
454 // Prefer user cache from symbol path.
455 if (sympath_cache) {
456 assert(!sympath_cache->empty() && "Empty entries resolve to default cache");
457 candidates.push_back(*sympath_cache);
458 }
459
460 // Fallback to configured cache from settings.
461 candidates.push_back(GetGlobalPluginProperties().GetCachePath());
462
464 for (const auto &path : candidates) {
465 if (llvm::sys::fs::is_directory(path))
466 return path;
467 if (std::error_code ec = llvm::sys::fs::create_directories(path)) {
468 LLDB_LOG(log, "Ignoring invalid SymStore cache directory '{0}': {1}",
469 path, ec.message());
470 continue;
471 }
472 return path;
473 }
474
475 // Last resort is the system default location.
477}
478
479std::optional<FileSpec>
480LocateSymStoreEntry(const SymbolLocatorSymStore::LookupEntry &entry,
481 llvm::StringRef key, llvm::StringRef pdb_name) {
483 llvm::StringRef url = entry.source;
484 if (url.starts_with("http://") || url.starts_with("https://")) {
485 std::string cache_path = SelectSymStoreCache(entry.cache);
486
487 // Held across the cache check as well as the download, so that a thread
488 // that loses the race observes the winner's result instead of fetching
489 // the same symbol a second time.
490 DownloadLock lock(cache_path, key, pdb_name);
491
492 // Check cache first.
493 if (auto spec = FindFileInLocalSymStore(cache_path, key, pdb_name)) {
494 LLDB_LOG(log, "Found {0} in SymStore cache {1}", pdb_name, cache_path);
495 return *spec;
496 }
497
498 // Download and move to cache.
499 if (auto tmp_file = RequestFileFromSymStoreServerHTTP(url, key, pdb_name)) {
500 LLDB_LOG(log, "Downloaded {0} from SymStore {1}", pdb_name, url);
501 auto spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
502 if (!spec) {
503 // Try the fallback and eventually rather cancel than loading the tmp
504 // file, since it might disappear or get overwritten.
506 spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
507 if (!spec)
508 return {};
509 }
510 LLDB_LOG(log, "Added {0} to SymStore cache {1}", pdb_name, cache_path);
511 return *spec;
512 }
513
514 return {};
515 }
516
517 llvm::StringRef file = entry.source;
518 if (file.starts_with("file://"))
519 file = file.drop_front(7);
520 if (auto spec = FindFileInLocalSymStore(file, key, pdb_name)) {
521 LLDB_LOG(log, "Found {0} in local SymStore {1}", pdb_name, file);
522 return *spec;
523 }
524
525 return {};
526}
527
528} // namespace
529
531 const ModuleSpec &module_spec, const FileSpecList &default_search_paths) {
532 const UUID &uuid = module_spec.GetUUID();
533 if (!uuid.IsValid() ||
534 !ModuleList::GetGlobalModuleListProperties().GetEnableExternalLookup())
535 return {};
536
538 std::string pdb_name = module_spec.GetSymbolFileSpec().GetFilename().str();
539 if (pdb_name.empty()) {
540 LLDB_LOG(log, "Failed to resolve symbol PDB module: PDB name empty");
541 return {};
542 }
543
544 LLDB_LOG(log, "LocateExecutableSymbolFile {0} with UUID {1}", pdb_name,
545 uuid.GetAsString());
546 if (uuid.GetBytes().size() != 20) {
547 LLDB_LOG(log, "Failed to resolve symbol PDB module: UUID invalid");
548 return {};
549 }
550
551 std::string key = FormatSymStoreKey(uuid);
552 for (const LookupEntry &entry : GetGlobalLookupOrder()) {
553 if (auto spec = LocateSymStoreEntry(entry, key, pdb_name))
554 return *spec;
555 }
556
557 return {};
558}
559
560std::vector<SymbolLocatorSymStore::LookupEntry>
562 if (val.empty())
563 return {};
564
565 std::vector<LookupEntry> result;
566 std::optional<std::string> implicit_cache;
567 llvm::SmallVector<llvm::StringRef, 2> entries;
568 val.split(entries, ';');
569
570 for (llvm::StringRef raw : entries) {
571 llvm::StringRef entry = raw.trim();
572 if (entry.empty())
573 continue;
574
575 // Explicit cache directives apply to all subsequent srv* entries that don't
576 // set their own explicit cache.
577 if (entry.starts_with_insensitive("cache*")) {
578 if (auto cache = ParseCacheEntry(entry))
579 implicit_cache = *cache;
580 continue;
581 }
582
583 // SymStore directives with explicit interpreters are unsupported
584 // explicitly.
585 if (entry.starts_with_insensitive("symsrv*")) {
587 llvm::formatv("ignoring unsupported entry in env: {0}", entry));
588 continue;
589 }
590
591 // SymStore server directives may include an explicit cache.
592 // Format is: srv*[LocalCache*]SymbolStore
593 if (entry.starts_with_insensitive("srv*")) {
594 if (auto lookup_entry = ParseSrvEntry(entry)) {
595 if (!lookup_entry->cache && implicit_cache)
596 lookup_entry->cache = implicit_cache;
597 result.push_back(*lookup_entry);
598 }
599 continue;
600 }
601
602 // Plain local paths aren't cached.
603 result.push_back(MakeLookupEntry(entry));
604 }
605
606 return result;
607}
608
610 // Fall back to the platform cache directory.
611 llvm::SmallString<128> cache_dir;
612 if (llvm::sys::path::cache_directory(cache_dir)) {
613 llvm::sys::path::append(cache_dir, "lldb", "symstore");
614 return cache_dir.str().str();
615 }
616 // Last resort: use a subdirectory of the system temp directory.
617 constexpr bool erase_on_reboot = false;
618 llvm::sys::path::system_temp_directory(erase_on_reboot, cache_dir);
619 llvm::sys::path::append(cache_dir, "lldb", "symstore");
620 return cache_dir.str().str();
621}
FormatEntity::Entry Entry
static PluginProperties & GetGlobalPluginProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_PLUGIN_DEFINE(PluginName)
static PluginProperties & GetGlobalPluginProperties()
A class to manage flag bits.
Definition Debugger.h:100
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *>
Report warning events.
A file collection class.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
static ModuleListProperties & GetGlobalModuleListProperties()
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:81
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::vector< LookupEntry > ParseEnvSymbolPaths(llvm::StringRef val)
Represents UUID's of various sizes.
Definition UUID.h:27
llvm::ArrayRef< uint8_t > GetBytes() const
Definition UUID.h:66
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
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.
Definition Log.h:338