192 Commits

Author SHA1 Message Date
jimingham
0ddcd209dd
Don't hold the Target's ModuleListLock over running LoadScriptingResourceInTarget (#138216)
That calls an unknown amount of Python code, and can do quite a bit of
work - especially if people do things like launch scripted processes in
this script affordance. Doing that while holding a major lock like the
ModuleList lock is asking for trouble.

I tried to make a test that would actually stall without this, but I
couldn't come up with anything that reliably failed. You always have to
get pretty unlucky.
2025-05-02 11:51:21 -07:00
GeorgeHuyubo
77f8335a07
Add symbol locator time for each module in statistics (#137379)
Identical PR to: https://github.com/llvm/llvm-project/pull/134563
Previous PR was approved and landed but broke the build due to bad
merge.
Manually resolve the merge conflict and try to land again.

Co-authored-by: George Hu <georgehuyubo@gmail.com>
2025-04-25 11:48:31 -07:00
Kazu Hirata
bc716a755a Revert "Add symbol locator time for each module in statistics (#134563)"
This reverts commit 070a4ae2f9bcf6967a7147ed2972f409eaa7d3a6.

Multiple buildbot failures have been reported:
https://github.com/llvm/llvm-project/pull/134563

The build fails with:

  lldb/source/Target/Statistics.cpp:75:39: error: use of undeclared
  identifier 'num_symbols_loaded'
2025-04-25 11:01:19 -07:00
GeorgeHuyubo
070a4ae2f9
Add symbol locator time for each module in statistics (#134563)
In statistics, add locate time for each module in statistics, we time
the PluginManager::LocateExecutableSymbolFile and
PluginManager::LocateExecutableObjectFile call, save the duration for
the succeeded symbol locator plugin in the Module class as a map.
New key being added:
Module level: "_symbolLocatorTime_"
Summary level: "_totalSymbolLocatorTime_"
which would be a map of symbol_locator_plugin_name to time.

Sample statistic dump output after this change:

```
Command: statistics dump
===============Output===============
{
  "commands": {
    "command container add": 1,
    "command script add": 51,
    "command script import": 59,
    "statistics dump": 1,
    "target create": 1,
    "type summary add": 36,
    "type synthetic add": 21
  },
  "memory": {
    "strings": {
      "bytesTotal": 2801664,
      "bytesUnused": 1704256,
      "bytesUsed": 1097408
    }
  },
  "modules": [
    {
      "debugInfoByteSize": 244927,
      "debugInfoEnabled": true,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0.61934599999999995,
      "debugInfoParseTime": 0.00033100000000000002,
      "identifier": 94868115726768,
      "path": "/home/hyubo/.cache/llvm-debuginfod/client/llvmcache-720c9a0f5ba8b460a1524a25597226f0fa551f71-c4crasher",
      "symbolLocatorTime": {
        "debuginfod": 1.4547020000000002
      },
      "symbolTableIndexTime": 0.0035370000000000002,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.0055040000000000002,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "720C9A0F-5BA8-B460-A152-4A25597226F0-FA551F71"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868111142256,
      "path": "[vdso](0x00007ffd41c59000)",
      "symbolLocatorTime": {
        "debuginfod": 0.80597700000000005
      },
      "symbolTableIndexTime": 2.8e-05,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.00037300000000000001,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "4D1F38BD-BD34-DFB3-C9A5-B49A2A912219-AC713763"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868116162096,
      "path": "/usr/local/fbcode/platform010/lib/libc.so.6",
      "symbolLocatorTime": {
        "debuginfod": 0.286356
      },
      "symbolTableIndexTime": 0.0091780000000000004,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.081841999999999998,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "ACE9DF01-8872-3A35-6D14-3C92527EF739-4BE32C75"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868111990032,
      "path": "/usr/local/fbcode/platform010/lib/libm.so.6",
      "symbolLocatorTime": {
        "debuginfod": 0.63356699999999999
      },
      "symbolTableIndexTime": 0.0023960000000000001,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.021706,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "85932B54-0DE7-4FC1-23B0-FB09AD1A5A61-8E1098B7"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868116399488,
      "path": "/usr/local/fbcode/platform010/lib/libmvec.so.1",
      "symbolLocatorTime": {
        "debuginfod": 0.66705099999999995
      },
      "symbolTableIndexTime": 0.00053700000000000004,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.0034429999999999999,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "4537CA22-8E6E-495B-7A03-FC2CEDCAD71C-8A7B2067"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868111778368,
      "path": "/usr/local/fbcode/platform010/lib/libatomic.so.1",
      "symbolLocatorTime": {
        "debuginfod": 0.83268299999999995
      },
      "symbolTableIndexTime": 0.000243,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.0026640000000000001,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--",
      "uuid": "F90F9111-BBD1-C2A9-972A-34EB75ABE62E-3BDED9CF"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868116403264,
      "path": "/usr/local/fbcode/platform010/lib/libgcc_s.so.1",
      "symbolLocatorTime": {
        "debuginfod": 0.58871499999999999
      },
      "symbolTableIndexTime": 0.000292,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.0033,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--",
      "uuid": "1C715A92-40BE-BE95-E148-1B401749BAB8-15D09F9D"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868113225328,
      "path": "/usr/local/fbcode/platform010/lib/libstdc++.so.6",
      "symbolLocatorTime": {
        "debuginfod": 0.76993400000000001
      },
      "symbolTableIndexTime": 0.042455,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.081374000000000002,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--",
      "uuid": "C9DAEE53-F607-981B-6BED-F2042833BFC7-71A1E66C"
    },
    {
      "debugInfoByteSize": 0,
      "debugInfoEnabled": false,
      "debugInfoHadIncompleteTypes": false,
      "debugInfoHadVariableErrors": false,
      "debugInfoIndexLoadedFromCache": false,
      "debugInfoIndexSavedToCache": false,
      "debugInfoIndexTime": 0,
      "debugInfoParseTime": 0,
      "identifier": 94868113600960,
      "path": "/usr/local/fbcode/platform010/lib/ld.so",
      "symbolLocatorTime": {
        "debuginfod": 0.48382199999999997
      },
      "symbolTableIndexTime": 0.00054799999999999998,
      "symbolTableLoadedFromCache": false,
      "symbolTableParseTime": 0.0057219999999999997,
      "symbolTableSavedToCache": false,
      "symbolTableStripped": false,
      "triple": "x86_64--linux",
      "uuid": "CCA86CF4-E4FF-42C8-7056-2F7D8B83AEE0-530B4095"
    }
  ],
  "targets": [
    {
      "breakpoints": [],
      "dyldPluginName": "dump-modulelist-dyld",
      "expressionEvaluation": {
        "failures": 0,
        "successes": 0
      },
      "frameVariable": {
        "failures": 0,
        "successes": 0
      },
      "mismatchCoredumpModuleCount": 0,
      "moduleIdentifiers": [
        94868115726768,
        94868111142256,
        94868116162096,
        94868111990032,
        94868116399488,
        94868111778368,
        94868116403264,
        94868113225328,
        94868113600960
      ],
      "signals": [
        {
          "SIGABRT": 1
        }
      ],
      "sourceMapDeduceCount": 0,
      "sourceRealpathAttemptCount": 0,
      "sourceRealpathCompatibleCount": 0,
      "stopCount": 1,
      "summaryProviderStatistics": [],
      "targetCreateTime": 4.1999999999999998e-05,
      "totalBreakpointResolveTime": 0,
      "totalSharedLibraryEventHitCount": 0
    }
  ],
  "totalDebugInfoByteSize": 244927,
  "totalDebugInfoEnabled": 1,
  "totalDebugInfoIndexLoadedFromCache": 0,
  "totalDebugInfoIndexSavedToCache": 0,
  "totalDebugInfoIndexTime": 0.61934599999999995,
  "totalDebugInfoParseTime": 0.00033100000000000002,
  "totalModuleCount": 9,
  "totalModuleCountHasDebugInfo": 1,
  "totalModuleCountWithIncompleteTypes": 0,
  "totalModuleCountWithVariableErrors": 0,
  "totalSymbolLocatorTime": {
    "debuginfod": 6.5228070000000002
  },
  "totalSymbolTableIndexTime": 0.059214000000000003,
  "totalSymbolTableParseTime": 0.205928,
  "totalSymbolTableStripped": 0,
  "totalSymbolTablesLoadedFromCache": 0,
  "totalSymbolTablesSavedToCache": 0,
  "transcript": [
    {
      "command": "symsrv",
      "commandArguments": "",
      "commandName": "symsrv",
      "durationInSeconds": 0.00069099999999999999,
      "error": "",
      "output": "",
      "timestampInEpochSeconds": 1744934015
    },
    {
      "command": "settings set symbols.enable-external-lookup true",
      "commandArguments": "symbols.enable-external-lookup true",
      "commandName": "settings set",
      "durationInSeconds": 4.1999999999999998e-05,
      "error": "",
      "output": "",
      "timestampInEpochSeconds": 1744934015
    },
    {
      "command": "settings insert-before plugin.symbol-locator.debuginfod.server-urls 0 https://our.intern.facebook.com/intern/debuginfod",
      "commandArguments": "plugin.symbol-locator.debuginfod.server-urls 0 https://our.intern.facebook.com/intern/debuginfod",
      "commandName": "settings insert-before",
      "durationInSeconds": 5.5999999999999999e-05,
      "error": "",
      "output": "",
      "timestampInEpochSeconds": 1744934015
    },
    {
      "command": "target create --core \"/var/tmp/cores/c4crasher.crasher.1576894\"",
      "commandArguments": "--core \"/var/tmp/cores/c4crasher.crasher.1576894\"",
      "commandName": "target create",
      "durationInSeconds": 6.7297630000000002,
      "error": "",
      "output": "Core file '/var/tmp/cores/c4crasher.crasher.1576894' (x86_64) was loaded.\n",
      "timestampInEpochSeconds": 1744934017
    },
    {
      "command": "fbpaste statistics dump",
      "commandArguments": "statistics dump",
      "commandName": "fbpaste",
      "timestampInEpochSeconds": 1744934055
    },
    {
      "command": "statistics dump",
      "commandArguments": "",
      "commandName": "statistics dump",
      "timestampInEpochSeconds": 1744934055
    }
  ]
}

```

Co-authored-by: George Hu <georgehuyubo@gmail.com>
2025-04-25 10:43:17 -07:00
Adrian Prantl
b798f4bd50
[lldb] Make deep copies of Status explicit (NFC) (#107170) 2024-09-05 12:44:13 -07:00
Adrian Prantl
0642cd768b
[lldb] Turn lldb_private::Status into a value type. (#106163)
This patch removes all of the Set.* methods from Status.

This cleanup is part of a series of patches that make it harder use the
anti-pattern of keeping a long-lives Status object around and updating
it while dropping any errors it contains on the floor.

This patch is largely NFC, the more interesting next steps this enables
is to:
1. remove Status.Clear()
2. assert that Status::operator=() never overwrites an error
3. remove Status::operator=()

Note that step (2) will bring 90% of the benefits for users, and step
(3) will dramatically clean up the error handling code in various
places. In the end my goal is to convert all APIs that are of the form

`    ResultTy DoFoo(Status& error)
`
to

`    llvm::Expected<ResultTy> DoFoo()
`
How to read this patch?

The interesting changes are in Status.h and Status.cpp, all other
changes are mostly

` perl -pi -e 's/\.SetErrorString/ = Status::FromErrorString/g' $(git
grep -l SetErrorString lldb/source)
`
plus the occasional manual cleanup.
2024-08-27 10:59:31 -07:00
Jonas Devlieghere
5f4b40c90a
[lldb] Expand background symbol download (#80890)
LLDB has a setting (symbols.enable-background-lookup) that calls
dsymForUUID on a background thread for images as they appear in the
current backtrace. Originally, the laziness of only looking up symbols
for images in the backtrace only existed to bring the number of
dsymForUUID calls down to a manageable number.

Users have requesting the same functionality but blocking. This gives
them the same user experience as enabling dsymForUUID globally, but
without the massive upfront cost of having to download all the images,
the majority of which they'll likely not need.

This patch renames the setting to have a more generic name
(symbols.auto-download) and changes its values from a boolean to an
enum. Users can now specify "off", "background" and "foreground". The
default remains "off" although I'll probably change that in the near
future.
2024-02-08 12:39:04 -08:00
Jonas Devlieghere
705fcd4e0a
Revert "[lldb] Expand background symbol lookup" (#81182)
Reverts llvm/llvm-project#80890
2024-02-08 11:50:53 -08:00
Jonas Devlieghere
74fc16aaaa
[lldb] Expand background symbol download (#80890)
LLDB has a setting (symbols.enable-background-lookup) that calls
dsymForUUID on a background thread for images as they appear in the
current backtrace. Originally, the laziness of only looking up symbols
for images in the backtrace only existed to bring the number of
dsymForUUID calls down to a manageable number.

Users have requesting the same functionality but blocking. This gives
them the same user experience as enabling dsymForUUID globally, but
without the massive upfront cost of having to download all the images,
the majority of which they'll likely not need.

This patch renames the setting to have a more generic name
(symbols.auto-download) and changes its values from a boolean to an
enum. Users can now specify "off", "background" and "foreground". The
default remains "off" although I'll probably change that in the near
future.
2024-02-08 11:24:07 -08:00
Alexandre Ganea
47bd76d80f [lldb] Replace deprecated std::unique_ptr::unique() to silence a warning with MS-STL. NFC.
MS-STL warns about this with `warning STL4016: std::shared_ptr::unique() is deprecated in C++17`.
2024-01-17 07:23:57 -05:00
jimingham
a4cd99ea87
Ensure that the executable module is ModuleList[0] (#78360)
We claim in a couple places that the zeroth element of the module list
for a target is the main executable, but we don't actually enforce that
in the ModuleList class. As we saw, for instance, in

32dd5b20973bde1ef77fa3b84b9f85788a1a303a

it's not all that hard to get this to be off. This patch ensures that
the first object file of type Executable added to it is moved to the
front of the ModuleList. I also added a test for this.

In the normal course of operation, where the executable is added first,
this only adds a check for whether the first element in the module list
is an executable. If that's true, we just append as normal.

Note, the code in Target::GetExecutableModule doesn't actually agree
that the zeroth element must be the executable, it instead returns the
first Module of type Executable. But I can't tell whether that was a
change in intention or just working around the bug that we don't always
maintain this ordering. But given we've said this in scripting as well
as internally, I think we shouldn't change our minds about this.
2024-01-16 17:12:32 -08:00
Adrian Prantl
917b404e2c
Add support for inline DWARF source files. (#75880)
LLVM supports DWARF 5 linetable extension to store source files inline
in DWARF. This is particularly useful for compiler-generated source
code. This implementation tries to materialize them as temporary files
lazily, so SBAPI clients don't need to be aware of them.

rdar://110926168
2024-01-04 09:04:05 -08:00
Greg Clayton
dd95877958
[lldb] Make only one function that needs to be implemented when searching for types (#74786)
This patch revives the effort to get this Phabricator patch into
upstream:

https://reviews.llvm.org/D137900

This patch was accepted before in Phabricator but I found some
-gsimple-template-names issues that are fixed in this patch.

A fixed up version of the description from the original patch starts
now.

This patch started off trying to fix Module::FindFirstType() as it
sometimes didn't work. The issue was the SymbolFile plug-ins didn't do
any filtering of the matching types they produced, and they only looked
up types using the type basename. This means if you have two types with
the same basename, your type lookup can fail when only looking up a
single type. We would ask the Module::FindFirstType to lookup "Foo::Bar"
and it would ask the symbol file to find only 1 type matching the
basename "Bar", and then we would filter out any matches that didn't
match "Foo::Bar". So if the SymbolFile found "Foo::Bar" first, then it
would work, but if it found "Baz::Bar" first, it would return only that
type and it would be filtered out.

Discovering this issue lead me to think of the patch Alex Langford did a
few months ago that was done for finding functions, where he allowed
SymbolFile objects to make sure something fully matched before parsing
the debug information into an AST type and other LLDB types. So this
patch aimed to allow type lookups to also be much more efficient.

As LLDB has been developed over the years, we added more ways to to type
lookups. These functions have lots of arguments. This patch aims to make
one API that needs to be implemented that serves all previous lookups:

- Find a single type
- Find all types
- Find types in a namespace

This patch introduces a `TypeQuery` class that contains all of the state
needed to perform the lookup which is powerful enough to perform all of
the type searches that used to be in our API. It contain a vector of
CompilerContext objects that can fully or partially specify the lookup
that needs to take place.

If you just want to lookup all types with a matching basename,
regardless of the containing context, you can specify just a single
CompilerContext entry that has a name and a CompilerContextKind mask of
CompilerContextKind::AnyType.

Or you can fully specify the exact context to use when doing lookups
like: CompilerContextKind::Namespace "std"
CompilerContextKind::Class "foo"
CompilerContextKind::Typedef "size_type"

This change expands on the clang modules code that already used a
vector<CompilerContext> items, but it modifies it to work with
expression type lookups which have contexts, or user lookups where users
query for types. The clang modules type lookup is still an option that
can be enabled on the `TypeQuery` objects.

This mirrors the most recent addition of type lookups that took a
vector<CompilerContext> that allowed lookups to happen for the
expression parser in certain places.

Prior to this we had the following APIs in Module:

```
void
Module::FindTypes(ConstString type_name, bool exact_match, size_t max_matches,
                  llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
                  TypeList &types);

void
Module::FindTypes(llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
                  llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
                  TypeMap &types);

void Module::FindTypesInNamespace(ConstString type_name,
                                  const CompilerDeclContext &parent_decl_ctx,
                                  size_t max_matches, TypeList &type_list);
```

The new Module API is much simpler. It gets rid of all three above
functions and replaces them with:

```
void FindTypes(const TypeQuery &query, TypeResults &results);
```
The `TypeQuery` class contains all of the needed settings:

- The vector<CompilerContext> that allow efficient lookups in the symbol
file classes since they can look at basename matches only realize fully
matching types. Before this any basename that matched was fully realized
only to be removed later by code outside of the SymbolFile layer which
could cause many types to be realized when they didn't need to.
- If the lookup is exact or not. If not exact, then the compiler context
must match the bottom most items that match the compiler context,
otherwise it must match exactly
- If the compiler context match is for clang modules or not. Clang
modules matches include a Module compiler context kind that allows types
to be matched only from certain modules and these matches are not needed
when d oing user type lookups.
- An optional list of languages to use to limit the search to only
certain languages

The `TypeResults` object contains all state required to do the lookup
and store the results:
- The max number of matches
- The set of SymbolFile objects that have already been searched
- The matching type list for any matches that are found

The benefits of this approach are:
- Simpler API, and only one API to implement in SymbolFile classes
- Replaces the FindTypesInNamespace that used a CompilerDeclContext as a
way to limit the search, but this only worked if the TypeSystem matched
the current symbol file's type system, so you couldn't use it to lookup
a type in another module
- Fixes a serious bug in our FindFirstType functions where if we were
searching for "foo::bar", and we found a "baz::bar" first, the basename
would match and we would only fetch 1 type using the basename, only to
drop it from the matching list and returning no results
2023-12-12 16:51:49 -08:00
Jonas Devlieghere
745e8bfd1a
[lldb] Remove LocateSymbolFile (#71301)
This completes the conversion of LocateSymbolFile into a SymbolLocator
plugin. The only remaining function is DownloadSymbolFileAsync which
doesn't really fit into the plugin model, and therefore moves into the
SymbolLocator class, while still relying on the plugins to do the
underlying work.
2023-11-05 08:26:42 -08:00
Jonas Devlieghere
c3a302d399
[lldb] Convert LocateSymbolFile into a plugin (#71151)
This commit contains the initial scaffolding to convert the
    functionality currently implemented in LocateSymbolFile to a plugin
    architecture. The plugin approach allows us to easily add new ways to
    find symbols and fixes some issues with the current implementation.

    For instance, currently we (ab)use the host OS to include support for
    querying the DebugSymbols framework on macOS. The plugin approach
    retains all the benefits (including the ability to compile this out on
    other platforms) while maintaining a higher level of separation with the
    platform independent code.

    To limit the scope of this patch, I've only converted a single function:
    LocateExecutableObjectFile. Future commits will convert the remaining
    LocateSymbolFile functions and eventually remove LocateSymbolFile. To
    make reviewing easier, that will done as follow-ups.
2023-11-03 15:42:23 -07:00
Fangrui Song
678e3ee123 [lldb] Fix duplicate word typos; NFC
Those fixes were taken from https://reviews.llvm.org/D137338
2023-09-01 21:32:24 -07:00
Alex Langford
14d95b26ae [lldb][NFCI] Remove unneeded ConstString conversions
ConstString can be implicitly converted into a llvm::StringRef. This is
very useful in many places, but it also hides places where we are
creating a ConstString only to use it as a StringRef for the entire
lifespan of the ConstString object.

I locally removed the implicit conversion and found some of the places we
were doing this.

Differential Revision: https://reviews.llvm.org/D159237
2023-08-31 11:27:59 -07:00
Kazu Hirata
04da7490d8 [lldb] Fix warnings
This patch fixes warnings like:

  lldb/source/Core/ModuleList.cpp:1086:3: error: 'scoped_lock' may not
  intend to support class template argument deduction
  [-Werror,-Wctad-maybe-unsupported]
2023-08-15 12:46:36 -07:00
Augusto Noronha
4a390a56ae [lldb] Implement ModuleList::Swap 2023-08-15 11:33:34 -07:00
Alex Langford
1d796b48e4 [lldb][NFCI] Methods to load scripting resources should take a Stream by reference
These methods all take a `Stream *` to get feedback about what's going
on. By default, it's a nullptr, but we always feed it with a valid
pointer. It would therefore make more sense to have this take a
reference.

Differential Revision: https://reviews.llvm.org/D154883
2023-07-11 10:36:11 -07:00
Jonas Devlieghere
300dce986f
[lldb] Migrate to GetPropertyAtIndexAs for FileSpecList (NFC)
Use the templated GetPropertyAtIndexAs helper for FileSpecList.
2023-05-04 22:24:23 -07:00
Jonas Devlieghere
ab73a9c1a7
[lldb] Eliminate {Get,Set}PropertyAtIndexAsFileSpec (NFC)
This patch is a continuation of 6f8b33f6dfd0 and eliminates the
{Get,Set}PropertyAtIndexAsFileSpec functions.
2023-05-04 22:10:28 -07:00
Jonas Devlieghere
917b3a7e62
[lldb] Move Core/FileSpecList -> Utility/FileSpecList (NFC)
There's no reason for FileSpecList to live in lldb/Core while FileSpec
lives in lldb/Utility. Move FileSpecList next to FileSpec.
2023-05-04 22:00:17 -07:00
Jonas Devlieghere
6f8b33f6df
[lldb] Use templates to simplify {Get,Set}PropertyAtIndex (NFC)
Use templates to simplify {Get,Set}PropertyAtIndex. It has always
bothered me how cumbersome those calls are when adding new properties.
After this patch, SetPropertyAtIndex infers the type from its arguments
and GetPropertyAtIndex required a single template argument for the
return value. As an added benefit, this enables us to remove a bunch of
wrappers from UserSettingsController and OptionValueProperties.

Differential revision: https://reviews.llvm.org/D149774
2023-05-04 16:42:46 -07:00
Jonas Devlieghere
611bd6c6ae
[lldb] Make exe_ctx an optional argument in OptionValueProperties (NFC)
The majority of call sites are nullptr as the execution context.
Refactor OptionValueProperties to make the argument optional and
simplify all the callers.
2023-05-02 10:36:11 -07:00
Jonas Devlieghere
ddd9358bca
[lldb] Remove unused will_modify argument (NFC)
Various OptionValue related classes are passing around will_modify but
the value is never used. This patch simplifies the interfaces by
removing the redundant argument.
2023-05-02 00:20:34 -07:00
Jonas Devlieghere
9c48aa68f4
[lldb] Refactor OptionValueProperties to return a std::optional (NFC)
Similar to fdbe7c7faa54, refactor OptionValueProperties to return a
std::optional instead of taking a fail value. This allows the caller to
handle situations where there's no value, instead of being unable to
distinguish between the absence of a value and the value happening the
match the fail value. When a fail value is required,
std::optional::value_or() provides the same functionality.
2023-05-01 21:46:32 -07:00
Michael Buch
5941858efd [lldb][Module][NFC] Add ModuleList::AnyOf
Differential Revision: https://reviews.llvm.org/D139083
2022-12-02 10:52:40 +00:00
Michael Buch
83599000e1 [lldb][Module] Document ModuleList::ForEach and assert nullness
Currently all callsites already assume the pointer is non-null.
This patch just asserts this assumption.

This is practically enforced by `ModuleList::Append`
which won't add `nullptr`s to `m_modules`.

Differential Revision: https://reviews.llvm.org/D139082
2022-12-02 10:52:39 +00:00
Jonas Devlieghere
11f45f36dc
[lldb] Fetching symbols in the background with dsymForUUID
On macOS, LLDB uses the DebugSymbols.framework to locate symbol rich
dSYM bundles. [1] The framework uses a variety of methods, one of them
calling into a binary or shell script to locate (and download) dSYMs.
Internally at Apple, that tool is called dsymForUUID and for simplicity
I'm just going to refer to it that way here too, even though it can be
be an arbitrary executable.

The most common use case for dsymForUUID is to fetch symbols from the
network. This can take a long time, and because the calls to the
DebugSymbols.framework are blocking, it takes a while to launch the
process. This is expected and therefore many people don't use this
functionality, but instead use add-dsym when they want symbols for a
given frame, backtrace or module. This is a little faster because you're
only fetching symbols for the module you care about, but it's still a
slow, blocking operation.

This patch introduces a hybrid approach between the two. When
symbols.enable-background-lookup is enabled, lldb will do the equivalent
of add-dsym in the background for every module that shows up in the
backtrace but doesn't have symbols for. From the user's perspective
there is no slowdown, because the process launches immediately, with
whatever symbols are available. Meanwhile, more symbol information is
added over time as the background fetching completes.

[1] https://lldb.llvm.org/use/symbols.html

rdar://76241471

Differential revision: https://reviews.llvm.org/D131328
2022-08-15 17:57:24 -07:00
Alex Langford
1d2a62afaf Re-submit "[lldb] Filter DIEs based on qualified name where possible"
This reverts commit 967df65a3610f98a3bc0ec0f2303641d7bad176c.

This fixes test/Shell/SymbolFile/NativePDB/find-functions.cpp. When
looking up functions with the PDB plugins, if we are looking for a
full function name, we should use `GetName` to populate the `name`
field instead of `GetLookupName` since `GetName` has the more
complete information.
2022-08-04 15:52:27 -07:00
Alex Langford
967df65a36 Revert "[lldb] Filter DIEs based on qualified name where possible"
This reverts commit befa77e59a7760d8c4fdd177b234e4a59500f61c.

Looks like this broke a SymbolFileNativePDB test. I'll investigate and
resubmit with a fix soon.
2022-08-04 11:52:30 -07:00
Alex Langford
befa77e59a [lldb] Filter DIEs based on qualified name where possible
Context:
When setting a breakpoint by name, we invoke Module::FindFunctions to
find the function(s) in question. However, we use a Module::LookupInfo
to first process the user-provided name and figure out exactly what
we're looking for. When we actually perform the function lookup, we
search for the basename. After performing the search, we then filter out
the results using Module::LookupInfo::Prune. For example, given
a:🅱️:foo we would first search for all instances of foo and then filter
out the results to just names that have a:🅱️:foo in them. As one can
imagine, this involves a lot of debug info processing that we do not
necessarily need to be doing. Instead of doing one large post-processing
step after finding each instance of `foo`, we can filter them as we go
to save time.

Some numbers:
Debugging LLDB and placing a breakpoint on
llvm::itanium_demangle::StringView::begin without this change takes
approximately 70 seconds and resolves 31,920 DIEs. With this change,
placing the breakpoint takes around 30 seconds and resolves 8 DIEs.

Differential Revision: https://reviews.llvm.org/D129682
2022-08-04 11:18:08 -07:00
Jeffrey Tan
7b81192d46 Introduce new symbol on-demand for debug info
This diff introduces a new symbol on-demand which skips
loading a module's debug info unless explicitly asked on
demand. This provides significant performance improvement
for application with dynamic linking mode which has large
number of modules.
The feature can be turned on with:
"settings set symbols.load-on-demand true"

The feature works by creating a new SymbolFileOnDemand class for
each module which wraps the actual SymbolFIle subclass as member
variable. By default, most virtual methods on SymbolFileOnDemand are
skipped so that it looks like there is no debug info for that module.
But once the module's debug info is explicitly requested to
be enabled (in the conditions mentioned below) SymbolFileOnDemand
will allow all methods to pass through and forward to the actual SymbolFile
which would hydrate module's debug info on-demand.

In an internal benchmark, we are seeing more than 95% improvement
for a 3000 modules application.

Currently we are providing several ways to on demand hydrate
a module's debug info:
* Source line breakpoint: matching in supported files
* Stack trace: resolving symbol context for an address
* Symbolic breakpoint: symbol table match guided promotion
* Global variable: symbol table match guided promotion

In all above situations the module's debug info will be on-demand
parsed and indexed.

Some follow-ups for this feature:
* Add a command that allows users to load debug info explicitly while using a
  new or existing command when this feature is enabled
* Add settings for "never load any of these executables in Symbols On Demand"
  that takes a list of globs
* Add settings for "always load the the debug info for executables in Symbols
  On Demand" that takes a list of globs
* Add a new column in "image list" that shows up by default when Symbols On
  Demand is enable to show the status for each shlib like "not enabled for
  this", "debug info off" and "debug info on" (with a single character to
  short string, not the ones I just typed)

Differential Revision: https://reviews.llvm.org/D121631
2022-04-26 10:42:06 -07:00
Shafik Yaghmour
28c878aeb2 [LLDB] Applying clang-tidy modernize-use-default-member-init over LLDB
Applied modernize-use-default-member-init clang-tidy check over LLDB.
It appears in many files we had already switched to in class member init but
never updated the constructors to reflect that. This check is already present in
the lldb/.clang-tidy config.

Differential Revision: https://reviews.llvm.org/D121481
2022-03-14 13:32:03 -07:00
Pavel Labath
c34698a811 [lldb] Rename Logging.h to LLDBLog.h and clean up includes
Most of our code was including Log.h even though that is not where the
"lldb" log channel is defined (Log.h defines the generic logging
infrastructure). This worked because Log.h included Logging.h, even
though it should.

After the recent refactor, it became impossible the two files include
each other in this direction (the opposite inclusion is needed), so this
patch removes the workaround that was put in place and cleans up all
files to include the right thing. It also renames the file to LLDBLog to
better reflect its purpose.
2022-02-03 14:47:01 +01:00
Pavel Labath
a007a6d844 [lldb] Convert "LLDB" log channel to the new API 2022-02-02 14:13:08 +01:00
Greg Clayton
da816ca0cb Added the ability to cache the finalized symbol tables subsequent debug sessions to start faster.
This is an updated version of the https://reviews.llvm.org/D113789 patch with the following changes:
- We no longer modify modification times of the cache files
- Use LLVM caching and cache pruning instead of making a new cache mechanism (See DataFileCache.h/.cpp)
- Add signature to start of each file since we are not using modification times so we can tell when caches are stale and remove and re-create the cache file as files are changed
- Add settings to control the cache size, disk percentage and expiration in days to keep cache size under control

This patch enables symbol tables to be cached in the LLDB index cache directory. All cache files are in a single directory and the files use unique names to ensure that files from the same path will re-use the same file as files get modified. This means as files change, their cache files will be deleted and updated. The modification time of each of the cache files is not modified so that access based pruning of the cache can be implemented.

The symbol table cache files start with a signature that uniquely identifies a file on disk and contains one or more of the following items:
- object file UUID if available
- object file mod time if available
- object name for BSD archive .o files that are in .a files if available

If none of these signature items are available, then the file will not be cached. This keeps temporary object files from expressions from being cached.

When the cache files are loaded on subsequent debug sessions, the signature is compare and if the file has been modified (uuid changes, mod time changes, or object file mod time changes) then the cache file is deleted and re-created.

Module caching must be enabled by the user before this can be used:

symbols.enable-lldb-index-cache (boolean) = false

(lldb) settings set symbols.enable-lldb-index-cache true

There is also a setting that allows the user to specify a module cache directory that defaults to a directory that defaults to being next to the symbols.clang-modules-cache-path directory in a temp directory:

(lldb) settings show symbols.lldb-index-cache-path
/var/folders/9p/472sr0c55l9b20x2zg36b91h0000gn/C/lldb/IndexCache

If this setting is enabled, the finalized symbol tables will be serialized and saved to disc so they can be quickly loaded next time you debug.

Each module can cache one or more files in the index cache directory. The cache file names must be unique to a file on disk and its architecture and object name for .o files in BSD archives. This allows universal mach-o files to support caching multuple architectures in the same module cache directory. Making the file based on the this info allows this cache file to be deleted and replaced when the file gets updated on disk. This keeps the cache from growing over time during the compile/edit/debug cycle and prevents out of space issues.

If the cache is enabled, the symbol table will be loaded from the cache the next time you debug if the module has not changed.

The cache also has settings to control the size of the cache on disk. Each time LLDB starts up with the index cache enable, the cache will be pruned to ensure it stays within the user defined settings:

(lldb) settings set symbols.lldb-index-cache-expiration-days <days>

A value of zero will disable cache files from expiring when the cache is pruned. The default value is 7 currently.

(lldb) settings set symbols.lldb-index-cache-max-byte-size <size>

A value of zero will disable pruning based on a total byte size. The default value is zero currently.
(lldb) settings set symbols.lldb-index-cache-max-percent <percentage-of-disk-space>

A value of 100 will allow the disc to be filled to the max, a value of zero will disable percentage pruning. The default value is zero.

Reviewed By: labath, wallace

Differential Revision: https://reviews.llvm.org/D115324
2021-12-16 09:59:55 -08:00
Xu Jun
dfd499a61c [lldb][NFC] avoid unnecessary roundtrips between different string types
The amount of roundtrips between StringRefs, ConstStrings and std::strings is
getting a bit out of hand, this patch avoid the unnecessary roundtrips.

Reviewed By: wallace, aprantl

Differential Revision: https://reviews.llvm.org/D112863
2021-11-01 22:15:01 -07:00
Raphael Isemann
4cf9d1e449 [lldb][NFC] Modernize for-loops in ModuleList
Reviewed By: mib

Differential Revision: https://reviews.llvm.org/D112379
2021-10-30 13:40:58 +02:00
Jonas Devlieghere
c020be17ce [lldb] Use a struct to pass function search options to Module::FindFunction
Rather than passing two booleans around, which is especially error prone
with them being next to each other, use a struct with named fields
instead.

Differential revision: https://reviews.llvm.org/D107295
2021-08-05 10:18:14 -07:00
Jonas Devlieghere
9494c510af [lldb] Use C++11 default member initializers
This converts a default constructor's member initializers into C++11
default member initializers. This patch was automatically generated with
clang-tidy and the modernize-use-default-member-init check.

$ run-clang-tidy.py -header-filter='lldb' -checks='-*,modernize-use-default-member-init' -fix

This is a mass-refactoring patch and this commit will be added to
.git-blame-ignore-revs.

Differential revision: https://reviews.llvm.org/D103483
2021-06-09 09:43:13 -07:00
Jonas Devlieghere
f2e05855de [lldb] Access the ModuleList through iterators where possible (NFC)
Replace uses of GetModuleAtIndexUnlocked and
GetModulePointerAtIndexUnlocked with the ModuleIterable and
ModuleIterableNoLocking where applicable.

Differential revision: https://reviews.llvm.org/D94271
2021-01-07 21:06:36 -08:00
Raphael Isemann
208e3f5d9b [lldb] Fix that symbols.clang-modules-cache-path is never initialized
LLDB is supposed to ask the Clang Driver what the default module cache path is
and then use that value as the default for the
`symbols.clang-modules-cache-path` setting. However, we use the property type
`String` to change `symbols.clang-modules-cache-path` even though the type of
that setting is `FileSpec`, so the setter will simply do nothing and return
`false`. We also don't check the return value of the setter, so this whole code
ends up not doing anything at all.

This changes the setter to use the correct property type and adds an assert that
we actually successfully set the default path. Also adds a test that checks that
the default value for this setting is never unset/empty path as this would
effectively disable the import-std-module feature from working by default.

Reviewed By: JDevlieghere, shafik

Differential Revision: https://reviews.llvm.org/D92772
2020-12-10 13:37:40 +01:00
Joseph Tremoulet
d20aa7ca42 [lldb] Report old modules from ModuleList::ReplaceEquivalent
This allows the Target to update its module list when loading a shared
module replaces an equivalent one.

A testcase is added which hits this codepath -- without the fix, the
target reports libbreakpad.so twice in its module list.

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D89157
2020-10-30 15:14:32 -04:00
Joseph Tremoulet
61bfc703c3 [lldb] GetSharedModule: Collect old modules in SmallVector
The various GetSharedModule methods have an optional out parameter for
the old module when a file has changed or been replaced, which the
Target uses to keep its module list current/correct.  We've been using
a single ModuleSP to track "the" old module, and this change switches
to using a SmallVector of ModuleSP, which has a couple benefits:
 - There are multiple codepaths which may discover an old module, and
   this centralizes the code for how to handle multiples in one place,
   in the Target code.  With the single ModuleSP, each place that may
   discover an old module is responsible for how it handles multiples,
   and the current code is inconsistent (some code paths drop the first
   old module, others drop the second).
 - The API will be more natural for identifying old modules in routines
   that work on sets, like ModuleList::ReplaceEquivalent (which I plan
   on updating to report old module(s) in a subsequent change to fix a
   bug).

I'm not convinced we can ever actually run into the case that multiple
old modules are found in the same GetOrCreateModule call, but I think
this change makes sense regardless, in light of the above.

When an old module is reported, Target::GetOrCreateModule calls
m_images.ReplaceModule, which doesn't allow multiple "old" modules; the
new code calls ReplaceModule for the first "old" module, and for any
subsequent old modules it logs the event and calls m_images.Remove.

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D89156
2020-10-30 15:14:31 -04:00
Jonas Devlieghere
8953376478 [lldb] Remove redundant WithFormat suffixes (NFC)
Replace calls to FooWithFormat() with calls to Foo() when only one
argument is provided and the given string doesn't need to be formatted.
2020-07-20 23:00:32 -07:00
Raphael Isemann
139e2a3f7b [lldb] Remove orphaned modules in a loop
Summary:

When modules reference each other (which happens for example with the different
modules LLDB loads when debugging -gmodules-compiled binaries), just iterating
over the module list once isn't good enough to find all orphans. Any removed
modules in the module list will also clear up the shared pointers they hold to
other modules, so after any module was removed from the list, LLDB should
iterate again and check if any additional modules can no be safely deleted.

This is currently causing that many gmodules tests are not cleaning up all
allocated modules which causes cleanup asserts to fail (right now these asserts
just mark the test as unsupported, but after D83865 the tests will start
failing).

Reviewers: aprantl, clayborg, JDevlieghere

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D84015
2020-07-20 10:47:56 +02:00
Raphael Isemann
f9568a9549 [lldb][NFC] Make all CompilerDeclContext parameters references instead of pointers
Summary:
All of our lookup APIs either use `CompilerDeclContext &` or `CompilerDeclContext *` semi-randomly it seems.
This leads to us constantly converting between those two types (and doing nullptr checks when going from
pointer to reference). It also leads to the confusing situation where we have two possible ways to express
that we don't have a CompilerDeclContex: either a nullptr or an invalid CompilerDeclContext (aka a default
constructed CompilerDeclContext).

This moves all APIs to use references and gets rid of all the nullptr checks and conversions.

Reviewers: labath, mib, shafik

Reviewed By: labath, shafik

Subscribers: shafik, arphaman, abidh, JDevlieghere, lldb-commits

Tags: #lldb

Differential Revision: https://reviews.llvm.org/D74607
2020-02-18 08:58:36 +01:00
Raphael Isemann
642bc15dd7 [lldb][NFC] Remove several inefficient ConstString -> const char * -> StringRef conversions
StringRef will call strlen on the C string which is inefficient (as ConstString already
knows the string lenght and so does StringRef). This patch replaces all those calls
with GetStringRef() which doesn't recompute the length.
2020-02-11 09:14:41 +01:00