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/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"
29
30using namespace lldb;
31using namespace lldb_private;
32
34
35namespace {
36
37#define LLDB_PROPERTIES_symbollocatorsymstore
38#include "SymbolLocatorSymStoreProperties.inc"
39
40enum {
41#define LLDB_PROPERTIES_symbollocatorsymstore
42#include "SymbolLocatorSymStorePropertiesEnum.inc"
43};
44
45class PluginProperties : public Properties {
46public:
47 static llvm::StringRef GetSettingName() {
49 }
50
51 PluginProperties() {
52 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
53 m_collection_sp->Initialize(g_symbollocatorsymstore_properties_def);
54 }
55
56 Args GetURLs() const {
57 Args urls;
58 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertySymStoreURLs, urls);
59 return urls;
60 }
61
62 std::string GetCachePath() const {
63 OptionValueString *s =
64 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
65 ePropertyCachePath);
66 if (s && !s->GetCurrentValueAsRef().empty())
67 return s->GetCurrentValue();
69 }
70
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);
75 }
76
77 std::optional<std::string> GetTLSCertFingerprint() const {
78 OptionValueString *s =
79 m_collection_sp->GetPropertyAtIndexAsOptionValueString(
80 ePropertyTLSCertFingerprint);
81 if (!s)
82 return {};
83 llvm::StringRef val = s->GetCurrentValueAsRef();
84 if (val.empty())
85 return {};
86 if (val.size() != 64 || !llvm::all_of(val, llvm::isHexDigit)) {
87 Debugger::ReportWarning(llvm::formatv(
88 "plugin.symbol-locator.symstore.tls-cert-fingerprint: expected a "
89 "64-character hex string (SHA-256), but got '{0}', ignoring",
90 val));
91 return {};
92 }
93 return val.lower();
94 }
95};
96
97} // namespace
98
99static PluginProperties &GetGlobalPluginProperties() {
100 static PluginProperties g_settings;
101 return g_settings;
102}
103
105
109 nullptr, LocateExecutableSymbolFile, nullptr, nullptr,
111 llvm::HTTPClient::initialize();
112
113 std::string default_cache = GetSystemDefaultCachePath();
114 if (std::error_code ec = llvm::sys::fs::create_directories(default_cache)) {
115 Debugger::ReportWarning(llvm::formatv(
116 "default SymStore cache directory '{0}' is not accessible: {1}",
117 default_cache, ec.message()));
118 }
119}
120
123 debugger, PluginProperties::GetSettingName())) {
124 constexpr bool is_global_setting = true;
126 debugger, GetGlobalPluginProperties().GetValueProperties(),
127 "Properties for the SymStore Symbol Locator plug-in.",
128 is_global_setting);
129 }
130}
131
134 llvm::HTTPClient::cleanup();
135}
136
138 return "Symbol locator for PDB in SymStore";
139}
140
144
145namespace {
146
147SymbolLocatorSymStore::LookupEntry MakeLookupEntry(llvm::StringRef source) {
149 entry.source = source.str();
150 entry.cache = std::nullopt;
151 return entry;
152}
153
154SymbolLocatorSymStore::LookupEntry MakeLookupEntry(llvm::StringRef source,
155 llvm::StringRef cache) {
157 entry.source = source.str();
158 entry.cache = cache.str();
159 return entry;
160}
161
162std::vector<SymbolLocatorSymStore::LookupEntry> GetGlobalLookupOrder() {
163 std::vector<SymbolLocatorSymStore::LookupEntry> result;
164
165 const char *sym_path = std::getenv("_NT_SYMBOL_PATH");
166 for (auto entry : SymbolLocatorSymStore::ParseEnvSymbolPaths(sym_path))
167 result.push_back(std::move(entry));
168
169 const char *alt_path = std::getenv("_NT_ALT_SYMBOL_PATH");
170 for (auto entry : SymbolLocatorSymStore::ParseEnvSymbolPaths(alt_path))
171 result.push_back(std::move(entry));
172
173 for (const auto &url : GetGlobalPluginProperties().GetURLs())
174 result.push_back(MakeLookupEntry(url.ref()));
175
176 return result;
177}
178
179std::optional<SymbolLocatorSymStore::LookupEntry>
180ParseSrvEntry(llvm::StringRef entry) {
181 llvm::SmallVector<llvm::StringRef, 4> parts;
182 entry.trim().split(parts, '*');
183
184 // Format is: srv*[LocalCache*]SymbolStore
185 switch (parts.size()) {
186 case 2:
187 return MakeLookupEntry(parts[1]);
188 case 3: {
189 // Fall back to the configured default cache for empty values.
190 if (parts[1].empty())
191 return MakeLookupEntry(parts[2],
192 GetGlobalPluginProperties().GetCachePath());
193 return MakeLookupEntry(parts[2], parts[1]);
194 }
195 default:
196 return {}; // Ignore entries with invalid number of parts.
197 }
198}
199
200std::optional<std::string> ParseCacheEntry(llvm::StringRef entry) {
201 llvm::SmallVector<llvm::StringRef, 2> parts;
202 entry.trim().split(parts, '*');
203
204 // Ignore entries with invalid number of parts.
205 if (parts.size() > 2)
206 return {};
207
208 // Empty cache* deliberatly specifies the default cache path.
209 llvm::StringRef value;
210 if (parts.size() == 2)
211 value = parts.back();
212
213 // Fall back to LLDB's default cache for empty values.
214 if (value.empty())
215 return GetGlobalPluginProperties().GetCachePath();
216
217 return value.str();
218}
219
220// RSDS entries store identity as a 20-byte UUID composed of 16-byte GUID and
221// 4-byte age:
222// 12345678-1234-5678-9ABC-DEF012345678-00000001
223//
224// SymStore key is a string with no separators and age as decimal:
225// 12345678123456789ABCDEF0123456781
226//
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);
232}
233
234bool HasUnsafeCharacters(llvm::StringRef s) {
235 for (unsigned char c : s) {
236 // RFC 3986 unreserved characters are safe for file names and URLs.
237 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
238 (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
239 c == '~') {
240 continue;
241 }
242
243 return true;
244 }
245
246 // Avoid path semantics issues.
247 return s == "." || s == "..";
248}
249
250std::optional<FileSpec>
251RequestFileFromSymStoreServerHTTP(llvm::StringRef base_url, llvm::StringRef key,
252 llvm::StringRef pdb_name) {
253 using namespace llvm::sys;
254
255 // Make sure URL will be valid, portable, and compatible with symbol servers.
256 if (HasUnsafeCharacters(pdb_name)) {
257 Debugger::ReportWarning(llvm::formatv(
258 "rejecting HTTP lookup for PDB file due to unsafe characters in "
259 "name: {0}",
260 pdb_name));
261 return {};
262 }
263
264 // Download into a temporary file.
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));
269
270 // Server has SymStore directory structure with forward slashes as separators.
271 std::string source_url =
272 llvm::formatv("{0}/{1}/{2}/{1}", base_url, pdb_name, key);
273
274 if (!llvm::HTTPClient::isAvailable()) {
276 "HTTP client is not available for SymStore download");
277 return {};
278 }
279
280 llvm::HTTPClient client;
281 client.setTimeout(
282 std::chrono::seconds(GetGlobalPluginProperties().GetTimeout()));
283
284 llvm::StreamedHTTPResponseHandler Handler(
285 [dest = tmp_file.str().str()]()
286 -> llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> {
287 std::error_code ec;
288 auto os = std::make_unique<llvm::raw_fd_ostream>(dest, ec);
289 if (ec)
290 return llvm::createStringError(ec, "Failed to open file for writing");
291 return std::make_unique<llvm::CachedFileStream>(std::move(os), dest);
292 },
293 client);
294
295 llvm::HTTPRequest request(source_url);
296 request.PinnedCertFingerprint =
297 GetGlobalPluginProperties().GetTLSCertFingerprint();
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))));
302 return {};
303 }
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))));
308 return {};
309 }
310
311 unsigned responseCode = client.responseCode();
312 switch (responseCode) {
313 case 404:
314 return {}; // file not found
315 case 200:
316 return FileSpec(tmp_file.str()); // success
317 default:
318 Debugger::ReportWarning(llvm::formatv(
319 "failed to download from SymStore '{0}': response code {1}", source_url,
320 responseCode));
321 return {};
322 }
323}
324
325std::optional<FileSpec> FindFileInLocalSymStore(llvm::StringRef root_dir,
326 llvm::StringRef key,
327 llvm::StringRef pdb_name) {
328 llvm::SmallString<256> path;
329 llvm::sys::path::append(path, root_dir, pdb_name, key, pdb_name);
330 FileSpec spec(path);
331 if (!FileSystem::Instance().Exists(spec))
332 return {};
333
334 return spec;
335}
336
337std::optional<FileSpec> MoveToLocalSymStore(llvm::StringRef cache,
338 llvm::StringRef key,
339 llvm::StringRef pdb_name,
340 FileSpec tmp_file) {
341 // Caches have SymStore directory structure: cache/pdb_name/key/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()));
348 return {};
349 }
350
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);
354
355 // Fall back to copy+delete if we move to a different volume.
356 if (ec == std::errc::cross_device_link) {
357 ec = llvm::sys::fs::copy_file(tmp_file.GetPath(), dest);
358 if (!ec)
359 llvm::sys::fs::remove(tmp_file.GetPath());
360 }
361 if (ec) {
363 llvm::formatv("failed to move '{0}' to SymStore cache '{1}': {2}",
364 tmp_file.GetPath(), dest, ec.message()));
365 return {};
366 }
367
368 return FileSpec(dest.str());
369}
370
371std::string SelectSymStoreCache(std::optional<std::string> sympath_cache) {
372 llvm::SmallVector<std::string, 2> candidates;
373
374 // Prefer user cache from symbol path.
375 if (sympath_cache) {
376 assert(!sympath_cache->empty() && "Empty entries resolve to default cache");
377 candidates.push_back(*sympath_cache);
378 }
379
380 // Fallback to configured cache from settings.
381 candidates.push_back(GetGlobalPluginProperties().GetCachePath());
382
384 for (const auto &path : candidates) {
385 if (llvm::sys::fs::is_directory(path))
386 return path;
387 if (std::error_code ec = llvm::sys::fs::create_directories(path)) {
388 LLDB_LOG(log, "Ignoring invalid SymStore cache directory '{0}': {1}",
389 path, ec.message());
390 continue;
391 }
392 return path;
393 }
394
395 // Last resort is the system default location.
397}
398
399std::optional<FileSpec>
400LocateSymStoreEntry(const SymbolLocatorSymStore::LookupEntry &entry,
401 llvm::StringRef key, llvm::StringRef pdb_name) {
403 llvm::StringRef url = entry.source;
404 if (url.starts_with("http://") || url.starts_with("https://")) {
405 // Check cache first.
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);
409 return *spec;
410 }
411
412 // Download and move to cache.
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);
416 if (!spec) {
417 // Try the fallback and eventually rather cancel than loading the tmp
418 // file, since it might disappear or get overwritten.
420 spec = MoveToLocalSymStore(cache_path, key, pdb_name, *tmp_file);
421 if (!spec)
422 return {};
423 }
424 LLDB_LOG(log, "Added {0} to SymStore cache {1}", pdb_name, cache_path);
425 return *spec;
426 }
427
428 return {};
429 }
430
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);
436 return *spec;
437 }
438
439 return {};
440}
441
442} // namespace
443
445 const ModuleSpec &module_spec, const FileSpecList &default_search_paths) {
446 const UUID &uuid = module_spec.GetUUID();
447 if (!uuid.IsValid() ||
448 !ModuleList::GetGlobalModuleListProperties().GetEnableExternalLookup())
449 return {};
450
452 std::string pdb_name = module_spec.GetSymbolFileSpec().GetFilename().str();
453 if (pdb_name.empty()) {
454 LLDB_LOG(log, "Failed to resolve symbol PDB module: PDB name empty");
455 return {};
456 }
457
458 LLDB_LOG(log, "LocateExecutableSymbolFile {0} with UUID {1}", pdb_name,
459 uuid.GetAsString());
460 if (uuid.GetBytes().size() != 20) {
461 LLDB_LOG(log, "Failed to resolve symbol PDB module: UUID invalid");
462 return {};
463 }
464
465 std::string key = FormatSymStoreKey(uuid);
466 for (const LookupEntry &entry : GetGlobalLookupOrder()) {
467 if (auto spec = LocateSymStoreEntry(entry, key, pdb_name))
468 return *spec;
469 }
470
471 return {};
472}
473
474std::vector<SymbolLocatorSymStore::LookupEntry>
476 if (val.empty())
477 return {};
478
479 std::vector<LookupEntry> result;
480 std::optional<std::string> implicit_cache;
481 llvm::SmallVector<llvm::StringRef, 2> entries;
482 val.split(entries, ';');
483
484 for (llvm::StringRef raw : entries) {
485 llvm::StringRef entry = raw.trim();
486 if (entry.empty())
487 continue;
488
489 // Explicit cache directives apply to all subsequent srv* entries that don't
490 // set their own explicit cache.
491 if (entry.starts_with_insensitive("cache*")) {
492 if (auto cache = ParseCacheEntry(entry))
493 implicit_cache = *cache;
494 continue;
495 }
496
497 // SymStore directives with explicit interpreters are unsupported
498 // explicitly.
499 if (entry.starts_with_insensitive("symsrv*")) {
501 llvm::formatv("ignoring unsupported entry in env: {0}", entry));
502 continue;
503 }
504
505 // SymStore server directives may include an explicit cache.
506 // Format is: srv*[LocalCache*]SymbolStore
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);
512 }
513 continue;
514 }
515
516 // Plain local paths aren't cached.
517 result.push_back(MakeLookupEntry(entry));
518 }
519
520 return result;
521}
522
524 // Fall back to the platform cache directory.
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();
529 }
530 // Last resort: use a subdirectory of the system temp directory.
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();
535}
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 *once=nullptr)
Report warning events.
A file collection class.
A file utility class.
Definition FileSpec.h:57
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:249
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
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