Commit Graph

14518 Commits

Author SHA1 Message Date
Jim Ingham be0ced03ba Revert "Revert "Add support for fetching signed values from tagged pointers.""
This reverts commit 602ab188a7.

The patch replicated an lldbassert for a certain type of NSNumber for tagged
pointers.  This really shouldn't be an assert since we don't do anything wrong
with these numbers, we just don't print a summary.  So this patch changed the
lldbassert to a log message in reverting the revert.
2021-04-05 18:18:26 -07:00
Jason Molenda 602ab188a7 Revert "Add support for fetching signed values from tagged pointers."
This reverts commit 4d9039c8dc.

This is causing the greendragon bots to fail most of the time when
running TestNSDictionarySynthetic.py.  Reverting until Jim has a chance
to look at this on Monday.  Running the commands from that test from
the command line, it fails 10-13% of the time on my desktop.

This is a revert of Jim's changes in https://reviews.llvm.org/D99694
2021-04-04 01:47:35 -07:00
Jonas Devlieghere cf51bf77b0 [lldb] Account for objc_debug_class_getNameRaw returning NULL
On macOS Catalina, calling objc_debug_class_getNameRaw on some of the
ISA pointers returns NULL, causing us to crash and unwind before reading
all the Objective-C classes. This does not happen on macOS Big Sur.
Account for that possibility and skip the class when that happens.
2021-04-01 19:58:28 -07:00
Jason Molenda 78a1412845 Handle all standalone combinations of LC_NOTEs w/ & w/o addr & uuid
Fill out ProcessMachCore::DoLoadCore to handle LC_NOTE hints with
a UUID or with a UUID+address, and load the binary at the specified
offset correctly.  Add tests for all four combinations.  Change
DynamicLoaderStatic to not re-set a Section's load address in the
Target if it's already been specified.

Differential Revision: https://reviews.llvm.org/D99571
rdar://51490545
2021-04-01 18:59:36 -07:00
Greg Clayton 2d733923b8 Fix "image lookup --address" Summary results for inline functions.
Inline callstacks were being incorrectly displayed in the results of "image lookup --address". The deepest frame wasn't displaying the line table line entry, it was always showing the inline information's call file and line on the previous frame. This is now fixed and has tests to make sure it doesn't regress.

Differential Revision: https://reviews.llvm.org/D98761
2021-04-01 11:36:26 -07:00
Raphael Isemann 18dbe0f954 [lldb] Prevent that LLDB randomly crashes in CommandLineParser::addOption by initializing LLVM's command line parser
Since quite a while Apple's LLDB fork (that contains the Swift debugging
support) is randomly crashing in `CommandLineParser::addOption` with an error
such as `CommandLine Error: Option 'h' registered more than once!`

The backtrace of the crashing thread is shown below. There are also usually many
other threads also performing similar clang::FrontendActions which are all
trying to generate (usually outdated) Clang modules which are used by Swift for
various reasons.

```
[  6] LLDB`CommandLineParser::addOption(llvm:🆑:Option*, llvm:🆑:SubCommand*) + 856
[  7] LLDB`CommandLineParser::addOption(llvm:🆑:Option*, llvm:🆑:SubCommand*) + 733
[  8] LLDB`CommandLineParser::addOption(llvm:🆑:Option*, bool) + 184
[  9] LLDB`llvm:🆑:ParseCommandLineOptions(...) [inlined] ::CommandLineParser::ParseCommandLineOptions(... + 1279
[  9] LLDB`llvm:🆑:ParseCommandLineOptions(...) + 497
[ 10] LLDB`setCommandLineOpts(clang::CodeGenOptions const&) + 416
[ 11] LLDB`EmitAssemblyHelper::EmitAssemblyWithNewPassManager(...) + 98
[ 12] LLDB`clang::EmitBackendOutput(...) + 4580
[ 13] LLDB`PCHContainerGenerator::HandleTranslationUnit(clang::ASTContext&) + 871
[ 14] LLDB`clang::MultiplexConsumer::HandleTranslationUnit(clang::ASTContext&) + 43
[ 15] LLDB`clang::ParseAST(clang::Sema&, bool, bool) + 579
[ 16] LLDB`clang::FrontendAction::Execute() + 74
[ 17] LLDB`clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 1808
```

The underlying reason for the crash is that the CommandLine code in LLVM isn't
thread-safe and will never be thread-safe with its current architecture. The way
LLVM's CommandLine logic works is that all parts of the LLVM can provide command
line arguments by defining `cl::opt` global variables and their constructors
(which are invoked during static initialisation) register the variable in LLVM's
CommandLineParser (which is also just a global variable). At some later point
after static initialization we actually try to parse command line arguments and
we ask the CommandLineParser to parse our `argv`.  The CommandLineParser then
lazily constructs it's internal parsing state in a non-thread-safe way (this is
where the crash happens), parses the provided command line and then goes back to
the respective `cl::opt` global variables and sets their values according to the
parse result.

As all of this is based on global state, this whole mechanism isn't thread-safe
so the only time to ever use it is when we know we only have one active thread
dealing with LLVM logic. That's why nearly all callers of
`llvm:🆑:ParseCommandLineOptions` are at the top of the `main` function of the
some LLVM-based tool. One of the few exceptions to this rule is in the
`setCommandLineOpts` function in `BackendUtil.cpp` which is in our backtrace:

```
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
  SmallVector<const char *, 16> BackendArgs;
  BackendArgs.push_back("clang"); // Fake program name.
  if (!CodeGenOpts.DebugPass.empty()) {
    BackendArgs.push_back("-debug-pass");
    BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  }
  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
    BackendArgs.push_back("-limit-float-precision");
    BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  }
  BackendArgs.push_back(nullptr);
  llvm:🆑:ParseCommandLineOptions(BackendArgs.size() - 1,
                                    BackendArgs.data());
}
```

This is trying to set `cl::opt` variables in the LLVM backend to their right
value as the passed via CodeGenOptions by invoking the CommandLine parser. As
this is just in some generic Clang CodeGen code (where we allow having multiple
threads) this is code is clearly wrong. If we're unlucky it either overwrites
the value of the global variables or it causes the CommandLine parser to crash.

So the next question is why is this only crashing in LLDB? The main reason seems
to be that easiest way to crash this code is to concurrently enter the initial
CommandLineParser construction where it tries to collect all the registered
`cl::opt` options and checks for sanity:

```
      // If it's a DefaultOption, check to make sure it isn't already there.
      if (O->isDefaultOption() &&
          SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
        return;

      // Add argument to the argument map!
      if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
        errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
               << "' registered more than once!\n";
        HadErrors = true;
      }
```

The `OptionsMap` here is global variable and if we end up in this code with two
threads at once then two threads at the same time can register an option (such
as 'h') when they pass the first `if` and then we fail with the sanity check in
the second `if`.

After this sanity check and initial setup code the only remaining work is just
parsing the provided CommandLine which isn't thread-safe but at least doesn't
crash in all my attempts at breaking it (as it's usually just reading from the
already generated parser state but not further modifying it). The exception to
this is probably that once people actually specify the options in the code
snippet above we might run into some new interesting ways to crash everything.

To go back to why it's only affecting LLDB: Nearly all LLVM tools I could find
(even if they are using threads) seem to call the CommandLine parser at the
start so they all execute the initial parser setup at a point where there is
only one thread. So once the code above is executed they are mostly safe from
the sanity check crashes. We even have some shady code for the gtest `main` in
`TestMain.cpp` which is why this also doesn't affect unit tests.

The only exception to this rule is ... *drum roll* ... LLDB! it's not using that
CommandLine library for parsing options so it also never ends up calling it in
`main`. So when we end up in the `FrontendAction` code from the backtrace we are
already very deep in some LLDB logic and usually already have several threads.
In a situation where Swift decides to compile a large amount of Clang modules in
parallel we then end up entering this code via several threads. If several
threads reach this code at the same time we end up in the situation where the
sanity-checking code of CommandLine crashes. I have a very reliable way of
demonstrating the whole thing in D99650 (just run the unit test several times,
it usually crashes after 3-4 attempts).

We have several ways to fix this:

1. Make the whole CommandLine mechanism in LLVM thread-safe.

2. Get rid of `setCommandLineOpts` in `BackendUtil.cpp` and other callers of the
command line parsing in generic Clang code.

3. Initialise the CommandLine library in a safe point in LLDB.

Option 1 is just a lot of work and I'm not even sure where to start. The whole
mechanism is based on global variables and global state and this seems like a
humongous task.

Option 2 is probably the best thing we can do in the near future. There are only
two callers of the command line parser in generic Clang code. The one in
`BackendUtils.cpp` looks like it can be replaced with some reasonable
refactoring (as it only deals with two specific options). There is another one
in `ExecuteCompilerInvocation` which deals with forwarding the generic `-mllvm`
options to the backend which seems like it will just end up requiring us to do
Option 1.

Option 3 is what this patch is doing. We just parse some dummy command line
invocation in a point of the LLDB execution where we only have one thread that
is dealing with LLVM/Clang stuff. This way we are at least prevent the frequent
crashes for users as parsing the dummy command line invocation will set up the
initial parser state safely.

Fixes rdar://70989856

Reviewed By: mib, JDevlieghere

Differential Revision: https://reviews.llvm.org/D99652
2021-04-01 20:17:54 +02:00
Jim Ingham 4d9039c8dc Add support for fetching signed values from tagged pointers.
The ObjC runtime offers both signed & unsigned tagged pointer value
accessors to tagged pointer providers, but lldb's tagged pointer
code only implemented the unsigned one.  This patch adds an
emulation of the signed one.

The motivation for doing this is that NSNumbers use the signed
accessor (they are always signed) and we need to follow that in our
summary provider or we will get incorrect values for negative
NSNumbers.

The data-formatter-objc test file had NSNumber examples (along with lots of other
goodies) but the NSNumber values weren't tested.  So I also added
checks for those values to the test.

I also did a quick audit of the other types in that main.m file, and
it looks like pretty much all the other values are either intermediates
or are tested.

Differential Revision: https://reviews.llvm.org/D99694
2021-04-01 10:59:25 -07:00
Muhammad Omair Javaid 88a5b35d63 Revert "Revert "[LLDB] Arm64/Linux Add MTE and Pointer Authentication registers""
This reverts commit 71b648f715.

There was a typo in the last commit which was causing LLDB AArch64 Linux
buildbot testsuite failures. Now fixed in current version.
2021-04-01 14:07:50 +05:00
Pavel Labath e1d4fb1ebf [lldb] Fix build errors from 3bea7306e8
The addition of the dummy constructors requires matching changes in os-
and arch-specific files, which I forgot about.
2021-04-01 09:01:35 +02:00
Pavel Labath 3bea7306e8 [lldb] Fix compilation with gcc-6.5
This fixes (works around) two errors with gcc-6.5.
- in the RegisterContext_x86 files, gcc is unable to synthesize a
  default constructor -- it thinks it needs to initialize the virtual
  base class, even though said classes are abstract. I fix that by
  providing a dummy constructor.
- In ReproducerInstrumentationTest, it is not able to deduce that the
  TestingRegistry class is movable (it contains a map of unique
  pointers). I change the type from Optional<TestingRegistry> to
  unique_ptr<TestingRegistry), so that moving is not required
  (copying/moving a polymorphic type is not a very good idea in any
  case).
2021-04-01 08:44:50 +02:00
Jonas Devlieghere dfc8da19c5 [lldb] Remove LLDB_CAPTURE_REPRODUCER override
Remove the LLDB_CAPTURE_REPRODUCER as it is inherently dangerous. The
reproducers require careful initialization which cannot be guaranteed by
overwriting the reproducer mode at this level.

If we want to provide this functionality, we should do it in the driver
instead. It was originally added to enable capture in CI, but we now
have a dedicated CI job that captures and replays the test suite.
2021-03-31 21:10:56 -07:00
Muhammad Omair Javaid 71b648f715 Revert "[LLDB] Arm64/Linux Add MTE and Pointer Authentication registers"
This reverts commit 1164b4e295.

Reason: LLDB AArch64 Linux buildbot failure
2021-03-31 17:12:14 +05:00
Walter Erquinigo a4ee79c8ae Fix errors in 0b69756110
Errors found in
https://lab.llvm.org/buildbot/#/builders/68/builds/9681/steps/6/logs/stdio
2021-03-30 18:03:02 -07:00
Walter Erquinigo 0b69756110 [trace][intel-pt] Implement trace start and trace stop
This implements the interactive trace start and stop methods.

This diff ended up being much larger than I anticipated because, by doing it, I found that I had implemented in the beginning many things in a non optimal way. In any case, the code is much better now.

There's a lot of boilerplate code due to the gdb-remote protocol, but the main changes are:

- New tracing packets: jLLDBTraceStop, jLLDBTraceStart, jLLDBTraceGetBinaryData. The gdb-remote packet definitions are quite comprehensive.
- Implementation of the "process trace start|stop" and "thread trace start|stop" commands.
- Implementaiton of an API in Trace.h to interact with live traces.
- Created an IntelPTDecoder for live threads, that use the debugger's stop id as checkpoint for its internal cache.
- Added a functionality to stop the process in case "process tracing" is enabled and a new thread can't traced.
- Added tests

I have some ideas to unify the code paths for post mortem and live threads, but I'll do that in another diff.

Differential Revision: https://reviews.llvm.org/D91679
2021-03-30 17:31:37 -07:00
Muhammad Omair Javaid 1164b4e295 [LLDB] Arm64/Linux Add MTE and Pointer Authentication registers
This patch adds two new dynamic register sets for AArch64 MTE and
Pointer Authentication features. These register sets are dynamic and
will only be available if underlying hardware support either of these
features. LLDB will pull in Aux vector information and create register
infos based on that information.

A follow up patch will add a test case to test these feature registers.

Reviewed By: labath, DavidSpickett

Differential Revision: https://reviews.llvm.org/D96460
2021-03-31 04:39:00 +05:00
Muhammad Omair Javaid d6d3d21cd1 [LLDB] Add support for Arm64/Linux dynamic register sets
This is patch adds support for adding dynamic register sets for
AArch64 dynamic features in LLDB. AArch64 has optional features like
SVE, Pointer Authentication and MTE which means LLDB needs to decide
at run time which registers it needs to pull in for the current
executable based on underlying support for a certain feature.

This patch makes necessary adjustments to make way for dynamic
register infos and dynamic register sets.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D96458
2021-03-31 04:38:36 +05:00
Pavel Labath ce03a86237 [lldb] Remove linux/mips debugging support
As discussed on lldb-dev
<https://lists.llvm.org/pipermail/lldb-dev/2021-March/016777.html> the
mips code is unmaintained and untested. It also carries a lot of
technical debt which is not limited to mips-specific code.

Generic mips support remains (and is going to be used by the upcoming
freebsd code). Resurrecting mips support should be a matter of re-adding
the relevant register context files (while avoiding reintroducing the
debt).
2021-03-30 15:24:43 +02:00
Michał Górny 6c1a8039de [lldb] [server] Support for multiprocess extension
Add a minimal support for the multiprocess extension in lldb-server.
The server indicates support for it via qSupported, and accepts
thread-ids containing a PID.  However, it still does not support
debugging more than one inferior, so any other PID value results
in an error.

Differential Revision: https://reviews.llvm.org/D98482
2021-03-30 15:09:27 +02:00
Michał Górny 64bb9cf7bf [lldb] [Process/gdb-remote] Fix TID reading to use U64
Fix multiple instances of reading thread-id to use U64 type instead
of U32.  This is consistent with lldb::tid_t being a 64-bit type.
2021-03-30 13:59:32 +02:00
Pavel Labath d1486e65a1 [lldb] Change CreateHostNativeRegisterContextLinux argument type
to NativeThreadLinux. This avoid casts down the line.
2021-03-30 11:45:17 +02:00
Pavel Labath 1a2d25fcdd Revert "[lldb/DWARF] Simplify DIE extraction code slightly"
This reverts commit 1b96e133cf due to
failures on windows.
2021-03-30 09:59:34 +02:00
Pavel Labath 1b96e133cf [lldb/DWARF] Simplify DIE extraction code slightly
Remove the "depth" variable, as the same information can be obtained
through die_index_stack.size().

Also add a test case for a one tricky case I noticed -- a unit
containing only a null unit die.
2021-03-30 08:44:17 +02:00
Greg Clayton eee309068e Fix .debug_aranges parsing issues.
When LLVM error handling was introduced to the parsing of the .debug_aranges it would cause major issues if any DWARFDebugArangeSet::extract() calls returned any errors. The code in DWARFDebugInfo::GetCompileUnitAranges() would end up calling DWARFDebugAranges::extract() which would return an error if _any_ DWARFDebugArangeSet had any errors, but it default constructed a DWARFDebugAranges object into DWARFDebugInfo::m_cu_aranges_up and populated it partially, and returned an error prior to finishing much needed functionality in the DWARFDebugInfo::GetCompileUnitAranges() function. Subsequent callers to this function would see that the DWARFDebugInfo::m_cu_aranges_up was actually valid and return this partially populated DWARFDebugAranges reference _and_ it would not be sorted or minimized.

This above bugs would cause an incomplete .debug_aranges parsing, it would skip manually parsing any compile units for ranges, and would not sort the DWARFDebugAranges in m_cu_aranges_up.

This bug would also cause breakpoints set by file and line to fail to set correctly if a symbol context for an address could not be resolved properly, which the incomplete and unsorted DWARFDebugAranges object that DWARFDebugInfo::GetCompileUnitAranges() returned would cause symbol context lookups resolved by address (breakpoint address) to fail to find any DWARF debug info for a given address.

This patch fixes all of the issues that I found:
- DWARFDebugInfo::GetCompileUnitAranges() no longer returns a "llvm::Expected<DWARFDebugAranges &>", but just returns a "const DWARFDebugAranges &". Why? Because this code contained a fallback that would parse all of the valid DWARFDebugArangeSet objects, and would check which compile units had valid .debug_aranges set entries, and manually build an address ranges table using DWARFUnit::BuildAddressRangeTable(). If we return an error because any DWARFDebugArangeSet has any errors, then we don't do any of this code. Now we parse all DWARFDebugArangeSet objects that have no errors, if any calls to DWARFDebugArangeSet::extract() return errors, we skip that DWARFDebugArangeSet so that we can use the fallback call to DWARFUnit::BuildAddressRangeTable(). Since DWARFDebugInfo::GetCompileUnitAranges() needs to parse what it can from the .debug_aranges and build address ranges tables for any compile units that don't have any .debug_aranges sets, everything now works as expected.
- Fix an issue where a DWARFDebugArangeSet contains multiple terminator entries. The LLVM parser and llvm-dwarfdump properly warn about this because it happens with linux compilers and linkers and was the original cause of the bug I am fixing here. We now correctly warn about this issue if "log enable dwarf info" is enabled, but we continue to parse the DWARFDebugArangeSet correctly so we don't lose data that is contained in the .debug_aranges section.
- DWARFDebugAranges::extract() no longer returns a llvm::Error because we need to be able to parse all of the valid DWARFDebugArangeSet objects. It also will correctly skip a DWARFDebugArangeSet object that has errors in the middle of the stream by setting the start offsets of each DWARFDebugArangeSet to be calculated by the previous DWARFDebugArangeSet::extract() calculated offset that uses the header which contains the length of the DWARFDebugArangeSet. This means if do we run into real errors while parsing individual DWARFDebugArangeSet objects, we can continue to parse the rest of the validly encoded DWARFDebugArangeSet objects in the .debug_aranges section. This will allow LLDB to parse DWARF that contains a possibly newer .debug_aranges set format than LLDB currently supports because we will error out for the parsing of the DWARFDebugArangeSet, but be able to skip to the next DWARFDebugArangeSet object using the "DWARFDebugArangeSet.m_header.length" field to calculate the next starting offset.

Tests were added to cover all new functionality.

Differential Revision: https://reviews.llvm.org/D99401
2021-03-29 15:34:36 -07:00
Raphael Isemann 32f252a765 [lldb][NFC] Fix -Wdocumentation issue in ProcessMinidump 2021-03-29 19:40:41 +02:00
Jonas Devlieghere bf8cbfa65f [lldb] Move UpdateISAToDescriptorMap into ClassInfoExtractor (NFC)
Move UpdateISAToDescriptorMap into ClassInfoExtractor so that all the
formerly public functions can be private and remain an implementation
detail of the extractor.

Differential revision: https://reviews.llvm.org/D99448
2021-03-29 09:23:44 -07:00
Jonas Devlieghere 4d593efd7f [lldb] Include llvm-config.h instead of config.h
This distinction doesn't matter for an in-tree build, but when building
against an installed llvm, only the former is present.

This should fix the LLDB Standalone bot:
http://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake-standalone/
2021-03-29 08:58:51 -07:00
Jonas Devlieghere 24baaad945 [lldb] Remove UpdateISAToDescriptorMapFromMemory
Remove UpdateISAToDescriptorMapFromMemory because it's dead code.
2021-03-26 15:40:36 -07:00
Jonas Devlieghere 645764f3aa [lldb] Add consistency between reading the dynamic and shared cache class info
This adds the consistency I promised in D99315 between how we read the
class info from the Objective-C runtime and the shared cache. (NFC)

Differential revision: https://reviews.llvm.org/D99446
2021-03-26 15:19:21 -07:00
Jonas Devlieghere 077aa10253 [lldb] Support lazily named classes in the Objective-C classes
Generic classes in Swift have their name instantiated on request, since
the vast majority never need it, and it just wastes time and memory.
This results in LLDB being unable to determine the dynamic type of these
Swift objects.

The main issues is that lazily named classes are not added to the
gdb_objc_realized_classes hashtable. This means the class count in the
table doesn't change when a class is realized and LLDB doesn't know it
needs to re-parse the class info. But even if it did, the classes are
not in the hash table.

The first change in this patch is that we read
objc_debug_realized_class_generation_count and re-parse the class info
when the count changes.

The second change in this patch is that we use
objc_copyRealizedClassList (if available) to get all realized classes
from the runtime.

Unfortunately, objc_copyRealizedClassList calls _dyld_objc_class_count
in its implementation. As we know, the Objective-C parsing code might
get called before dyld is fully initialized, resulting in crashes or
even a stranded lock. Therefore we only use objc_copyRealizedClassList
when we know it's safe to do so by checking libSystemInitialized in
dyld_all_image_infos.

As a result, it's possible that the first time we read the Objective-C
runtime we are forced to use gdb_objc_realized_classes. This should be
fine, as there should be no lazily named classes at this point.
Subsequent queries will detect the change in realized class generation
count and use objc_copyRealizedClassList.

This patch keeps the old behavior when objc_copyRealizedClassList or
objc_debug_realized_class_generation_count are not available.

Differential revision: https://reviews.llvm.org/D99315
2021-03-26 13:34:08 -07:00
Jonas Devlieghere bbb419151c [lldb] Add IsFullyInitialized to DynamicLoader
On Darwin based systems, lldb will get notified by dyld before it itself
finished initializing, at which point it's not safe to call certain APIs
or SPIs. Add a method to the DynamicLoader to query that.

Differential revision: https://reviews.llvm.org/D99314
2021-03-25 15:44:37 -07:00
Vedant Kumar 414412d3dc [lldb/Commands] Fix spelling of target.move-to-nearest-code in helptext 2021-03-25 14:25:10 -07:00
Abhina Sreeskantharajan c83cd8feef [NFC] Reordering parameters in getFile and getFileOrSTDIN
In future patches I will be setting the IsText parameter frequently so I will refactor the args to be in the following order. I have removed the FileSize parameter because it is never used.

```
  static ErrorOr<std::unique_ptr<MemoryBuffer>>
  getFile(const Twine &Filename, bool IsText = false,
          bool RequiresNullTerminator = true, bool IsVolatile = false);

  static ErrorOr<std::unique_ptr<MemoryBuffer>>
  getFileOrSTDIN(const Twine &Filename, bool IsText = false,
                 bool RequiresNullTerminator = true);

 static ErrorOr<std::unique_ptr<MB>>
 getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
            bool IsText, bool RequiresNullTerminator, bool IsVolatile);

  static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
  getFile(const Twine &Filename, bool IsVolatile = false);
```

Reviewed By: jhenderson

Differential Revision: https://reviews.llvm.org/D99182
2021-03-25 09:47:49 -04:00
Fred Riss c4fee95746 [lldb/ObjC] Make the NonPointerIsaCache initialization lazy
The objc_debug_isa_class_mask magic value that the objc runtime vends
is now initialized using a static initializer instead of a constant
value. The runtime plugin itself will be initialized before the value
is computed and as a result, the cache will get the wrong value.

Making the creation of the NonPointerIsaCache fully lazy fixes this.
2021-03-24 20:08:06 -07:00
Jonas Devlieghere ff29fdfe4e [lldb] Format AppleObjCRuntimeV2 (NFC) 2021-03-24 20:08:06 -07:00
Med Ismail Bennani fad34da7fd Revert "[lldb/Plugins] Add ScriptedProcess Process Plugin"
Reverting commit b09d44b6ae, since it breaks
the windows bots: https://lab.llvm.org/buildbot/#/builders/83/builds/4993

It seems to crash the `TestIRMemoryMapWindows.test` test.
2021-03-24 21:31:16 +01:00
Greg Clayton e122877f10 Add a progress class that can track long running operations in LLDB.
LLDB can often appear deadlocked to users that use IDEs when it is indexing DWARF, or parsing symbol tables. These long running operations can make a debug session appear to be doing nothing even though a lot of work is going on inside LLDB. This patch adds a public API to allow clients to listen to debugger events that report progress and will allow UI to create an activity window or display that can show users what is going on and keep them informed of expensive operations that are going on inside LLDB.

Differential Revision: https://reviews.llvm.org/D97739
2021-03-24 12:58:13 -07:00
Jim Ingham c8faa8c266 Make the stop-on-sharedlibrary-events setting work.
The StopInfoBreakpoint::PerformAction was overriding the synchronous
breakpoint's ShouldStop report.  Fix that and add a test.

This fixes two bugs in the original submission:
1) Actually generate both dylibs by including the second one in the Makefile
2) Don't ask synchronous callbacks for their opinion on whether to stop
   in the async context, that info is taken care of by recording the m_should_stop
   on entry to PerformAction.

Differential Revision: https://reviews.llvm.org/D98914
2021-03-24 11:15:11 -07:00
Shafik Yaghmour 13bb39aad3 [NFC][LLDB] Removing extra semicolons to silence -Wc++98-compat-extra-semi diagnostics 2021-03-24 19:10:58 +01:00
Med Ismail Bennani b09d44b6ae [lldb/Plugins] Add ScriptedProcess Process Plugin
This patch introduces Scripted Processes to lldb.

The goal, here, is to be able to attach in the debugger to fake processes
that are backed by script files (in Python, Lua, Swift, etc ...) and
inspect them statically.

Scripted Processes can be used in cooperative multithreading environments
like the XNU Kernel or other real-time operating systems, but it can
also help us improve the debugger testing infrastructure by writting
synthetic tests that simulates hard-to-reproduce process/thread states.

Although ScriptedProcess is not feature-complete at the moment, it has
basic execution capabilities and will improve in the following patches.

rdar://65508855

Differential Revision: https://reviews.llvm.org/D95713

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-24 19:10:58 +01:00
Dmitri Gribenko 41454c30f6 Updated LLDB for the new Clang Language enumerator 'OpenCLCXX' 2021-03-24 16:46:02 +01:00
David Zarzycki 952bc6c92e Revert "[lldb/Plugins] Add ScriptedProcess Process Plugin"
This reverts commit dd391e1ef7.

This patch causes 17 LLDB test regressions on Fedora 33 (x86-64).
2021-03-24 07:07:22 -04:00
Jason Molenda 3bc65a946e Handle a LC_NOTE main bin spec for user process corefiles
I was playing around with main bin spec LC_NOTEs and noticed
a small oversight in the parsing of user process corefile notes.
2021-03-24 02:18:17 -07:00
Shafik Yaghmour ec00502b9f [NFC][LLDB] Removing extra semicolons to silence -Wc++98-compat-extra-semi diagnostics 2021-03-23 14:32:36 -07:00
Adrian Prantl 2c6710a5e1 Teach DWARFExpression about DWARF 4+ Location Descriptions
DWARFExpression implements the DWARF2 expression model that left
ambiguity on whether the result of an expression was a value or an
address. This patch implements the DWARF location description model
introduces in DWARF 4 and sets the result Value's kind accordingly, if
the expression comes from a DWARF v4+ compile unit. The nomenclature
is taken from DWARF 5, chapter 2.6 "Location Descriptions".

Differential Revision: https://reviews.llvm.org/D98996
2021-03-23 10:29:51 -07:00
Med Ismail Bennani dd391e1ef7 [lldb/Plugins] Add ScriptedProcess Process Plugin
This patch introduces Scripted Processes to lldb.

The goal, here, is to be able to attach in the debugger to fake processes
that are backed by script files (in Python, Lua, Swift, etc ...) and
inspect them statically.

Scripted Processes can be used in cooperative multithreading environments
like the XNU Kernel or other real-time operating systems, but it can
also help us improve the debugger testing infrastructure by writting
synthetic tests that simulates hard-to-reproduce process/thread states.

Although ScriptedProcess is not feature-complete at the moment, it has
basic execution capabilities and will improve in the following patches.

rdar://65508855

Differential Revision: https://reviews.llvm.org/D95713

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-23 18:24:47 +01:00
Med Ismail Bennani 1f6a57c1a0 [lldb/Interpreter] Add ScriptInterpreter Wrapper for ScriptedProcess
This patch adds a ScriptedProcess interface to the ScriptInterpreter and
more specifically, to the ScriptInterpreterPython.

This interface will be used in the C++ `ScriptProcess` Process Plugin to
call the script methods.

At the moment, not all methods are implemented, they will upstreamed in
upcoming patches.

This patch also adds helper methods to the ScriptInterpreter to
convert `SBAPI` Types (SBData & SBError) to `lldb_private` types
(DataExtractor & Status).

rdar://65508855

Differential Revision: https://reviews.llvm.org/D95711

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-23 18:24:47 +01:00
Med Ismail Bennani 3e0ad11543 [lldb/Commands] Add command options for ScriptedProcess to ProcessLaunch
This patch adds a new command options to the CommandObjectProcessLaunch
for scripted processes.

Among the options, the user need to specify the class name managing the
scripted process. The user can also use a key-value dictionary holding
arbitrary data that will be passed to the managing class.

This patch also adds getters and setters to `SBLaunchInfo` for the
class name managing the scripted process and the dictionary.

rdar://65508855

Differential Review: https://reviews.llvm.org/D95710

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-23 18:24:47 +01:00
Kim-Anh Tran 68dafe40a6 [lldb] Use CompileUnit::ResolveSymbolContext in SymbolFileDWARF
SymbolFileDWARF::ResolveSymbolContext is currently unaware that in DWARF5 the primary file is specified at file index 0. As a result it misses to correctly resolve the symbol context for the primary file when DWARF5 debug data is used and the primary file is only specified at index 0.

This change makes use of CompileUnit::ResolveSymbolContext to resolve the symbol context. The ResolveSymbolContext in CompileUnit has been previously already updated to reflect changes in DWARF5
and contains a more readable version. It can resolve more, but will also do a bit more work than
SymbolFileDWARF::ResolveSymbolContext (getting the Module, and going through SymbolFileDWARF::ResolveSymbolContextForAddress), however, it's mostly directed by $resolve_scope
what will be resolved, and ensures that code is easier to maintain if there's only one path.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D98619
2021-03-22 08:44:16 +01:00
Vedant Kumar 4bd2bfb6ec [lldb/PlatformPOSIX] Change LoadImage default to RTLD_LAZY (reapply)
In general, it seems like the debugger should allow programs to load & run with
libraries as far as possible, instead of defaulting to being super-picky about
unavailable symbols.

This is critical on macOS/Darwin, as libswiftCore.dylib may 1) export a version
symbol using @available markup and then 2) expect that other exported APIs are
only dynamically used once the version symbol is checked. We can't open a
version of the library built with a bleeding-edge SDK on an older OS without
RTLD_LAXY (or pervasive/expensive @available markup added to dyld APIs).

This was previously committed as cb8c1ee269 and reverted due to
unknown failures on the Linux bots. This version adds additional asserts
to check that the shared objects are where we expect them & that calling
f1() from libt1 produces the expected value. The Linux failure is
tracked by https://bugs.llvm.org/show_bug.cgi?id=49656.

See: https://lists.llvm.org/pipermail/lldb-dev/2021-March/016796.html

Differential Revision: https://reviews.llvm.org/D98879
2021-03-19 16:06:00 -07:00
Vedant Kumar d8d5ef2e9d Revert "[lldb/PlatformPOSIX] Change LoadImage default to RTLD_LAZY"
This reverts commit cb8c1ee269. The test
is failing on Debian for unknown reasons.

https://lab.llvm.org/buildbot/#/builders/68/builds/8990
2021-03-19 15:26:16 -07:00
Vedant Kumar cb8c1ee269 [lldb/PlatformPOSIX] Change LoadImage default to RTLD_LAZY
In general, it seems like the debugger should allow programs to load & run with
libraries as far as possible, instead of defaulting to being super-picky about
unavailable symbols.

This is critical on macOS/Darwin, as libswiftCore.dylib may 1) export a version
symbol using @available markup and then 2) expect that other exported APIs are
only dynamically used once the version symbol is checked. We can't open a
version of the library built with a bleeding-edge SDK on an older OS without
RTLD_LAXY (or pervasive/expensive @available markup added to dyld APIs).

See: https://lists.llvm.org/pipermail/lldb-dev/2021-March/016796.html

Differential Revision: https://reviews.llvm.org/D98879
2021-03-19 15:13:43 -07:00
Jonas Devlieghere e089b5e9e1 [lldb] Call os_log_fault on lldb_assert
Call `os_log_fault` when an lldb assert fails. We piggyback off
`LLVM_SUPPORT_XCODE_SIGNPOSTS`, which also depends on `os_log`, to avoid
having to introduce another CMake check and corresponding define.

This patch also adds a small test using lldb-test that verifies we abort
with a "regular" assertion when asserts are enabled.

Differential revision: https://reviews.llvm.org/D98987
2021-03-19 14:23:50 -07:00
Jim Ingham 9d081a7ffe Revert "Make the stop-on-sharedlibrary-events setting work."
This reverts commit 9406d43138.

I messed up a test, and when I got it right it was failing.  The changed logic
doesn't work quite right (now the async callback called at sync time is
forcing us to stop.  I need to be a little more careful about that.
2021-03-19 12:38:41 -07:00
Jim Ingham 9406d43138 Make the stop-on-sharedlibrary-events setting work.
We weren't taking into account the "m_should_stop" setting that the
synchronous breakpoint callback had already set when we did PerformAction
in the StopInfoBreakpoint.  So we didn't obey its instructions when it
told us to stop.  Fixed that and added some tests both for when we
just have the setting, and when we have the setting AND other breakpoints
at the shared library load notification breakpoint address.

Differential Revision: https://reviews.llvm.org/D98914
2021-03-19 12:02:16 -07:00
David Spickett 96927bafa4 [lldb] Correct unsigned decimal argument check in memory write
getAsInteger returns false when it succeeds.

Before:
(lldb) memory write 0x00007ffff7dd3000 99 -f "unsigned decimal"
error: '99' is not a valid unsigned decimal string value.

After:
(lldb) memory write 0x00007ffff7dd3000 99 -f "unsigned decimal"
(lldb) memory read 0x00007ffff7dd3000 0x00007ffff7dd3001
0x7ffff7dd3000: 63                                               c
2021-03-17 16:08:54 +00:00
David Spickett 4b513b2458 [lldb] Correct typo in memory read error
Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D98770
2021-03-17 10:38:31 +00:00
Vassil Vassilev 0cb7e7ca0c Make iteration over the DeclContext::lookup_result safe.
The idiom:
```
DeclContext::lookup_result R = DeclContext::lookup(Name);
for (auto *D : R) {...}
```

is not safe when in the loop body we trigger deserialization from an AST file.
The deserialization can insert new declarations in the StoredDeclsList whose
underlying type is a vector. When the vector decides to reallocate its storage
the pointer we hold becomes invalid.

This patch replaces a SmallVector with an singly-linked list. The current
approach stores a SmallVector<NamedDecl*, 4> which is around 8 pointers.
The linked list is 3, 5, or 7. We do better in terms of memory usage for small
cases (and worse in terms of locality -- the linked list entries won't be near
each other, but will be near their corresponding declarations, and we were going
to fetch those memory pages anyway). For larger cases: the vector uses a
doubling strategy for reallocation, so will generally be between half-full and
full. Let's say it's 75% full on average, so there's N * 4/3 + 4 pointers' worth
of space allocated currently and will be 2N pointers with the linked list. So we
break even when there are N=6 entries and slightly lose in terms of memory usage
after that. We suspect that's still a win on average.

Thanks to @rsmith!

Differential revision: https://reviews.llvm.org/D91524
2021-03-17 08:59:04 +00:00
Pavel Labath 463863fffe [lldb] Move PlatformPOSIX::ConnectToWaitingProcesses to RemoteAwarePlatform
The functionality is not posix specific. Also force the usage of the
gdb-remote process plugin in the gdb platform class.

This is not sufficient to make TestPlatformConnect pass on windows (it
seems it suffers from module loading issues, unrelated to this test),
but it at least makes it shut down correctly, so I change the skip to an
xfail.
2021-03-14 22:43:52 +01:00
Jason Molenda 22e9753271 Don't load kexts/kernels without dSYMs present
One of the backup schemes I use for finding kexts and kernels
on the local filesystem is to load a solitary binary when I don't
find any with a dSYM.  This usually is a more confusing behavior
than helpful; people expect to get no binary loaded, or a binary
with debug information.  This change stops loading kexts and
kernels that do not have an associated dSYM.

rdar://74291888
2021-03-12 17:20:44 -08:00
Dave Lee f3b07f9c5d [lldb] Remove unused StackFrame::TrackGlobalVariable
Last used by the Go plugin which was removed in https://reviews.llvm.org/D54057.
2021-03-12 08:51:25 -08:00
Jan Kratochvil 08d33aa680 [nfc] [lldb] Remove variable ranges_base in DWARFUnit::AddUnitDIE 2021-03-10 23:36:07 +01:00
Vedant Kumar ac29c35207 [lldb/Platform] Skip very slow xcrun queries for simulator platforms, NFC
GetXcodeSDK() consistently takes over 1 second to complete if the
queried SDK is missing, because `xcrun` doesn't cache negative lookups.

Because there are multiple simulator platforms, this can add 4+ seconds
to `lldb -b some_object_file.o`.

To work around this, skip the call to GetXcodeSDK() when setting up
simulator platforms if the specified arch doesn't have what looks like a
simulator triple.

Some other ways to fix this:
- Fix caching in xcrun (rdar://74882205)
- Test for arch compat before calling SomePlatform::CreateInstance() (much
  larger change)

Differential Revision: https://reviews.llvm.org/D98272
2021-03-10 13:57:10 -08:00
Michał Górny 771c4c9cf6 [lldb] [Process/FreeBSD] Introduce aarch64 hw break/watchpoint support
Split out the common base of Linux hardware breakpoint/watchpoint
support for AArch64 into a Utility class, and use it to implement
the matching support on FreeBSD.

Differential Revision: https://reviews.llvm.org/D96548
2021-03-10 18:36:19 +01:00
Jason Molenda ea659ea101 Log in SetPrivateState when unwind logging enabled
It is easier to read the unwind logging when you can see
when the inferior resumes / stops and we're doing new unwinds.
2021-03-09 16:22:46 -08:00
Jordan Rupprecht b4825a6d9c [lldb][gui] Fix uninitialized variable in SourceFileWindowDelegate.
After 5419b67137 (which is `[SimplifyCFG] Update FoldTwoEntryPHINode to handle and/or of select and binop equally`), this uninitialized value is detected by msan.
2021-03-09 10:57:00 -08:00
Pavel Labath 2e826088b9 [lldb] Fix a bug in D96779 (shared lib directory logic)
This function would fail in debug builds, as the two usages of the
LLDB_PYTHON_RELATIVE_LIBDIR macro would expand to two distinct strings.
The path iterator macros don't support that.

Use a temporary variable to ensure everything points to a single string.
2021-03-09 15:15:45 +01:00
Jan Kratochvil cf806d91d5 [lldb] Fix DWARF-5 DW_FORM_implicit_const (used by GCC)
Differential Revision: https://reviews.llvm.org/D98197
2021-03-09 10:23:05 +01:00
Dave Lee 1200f85818 [lldb] Remove duplicated ThreadPlanStepOverBreakpoint comment
This comment was present twice in the function.
2021-03-08 22:34:56 -08:00
Jan Kratochvil fe7333174f [nfc] [lldb] Removed unused operator== for DWARFAbbreviationDeclaration and DWARFAttribute
Also DWARFAttribute::operator== was buggy as it was ignoring its `m_value`.
2021-03-08 19:18:48 +01:00
Raphael Isemann dc4ca9b0d4 [lldb][NFC] Code style fixes for ClangModulesDeclVendor
Doxygenify comments and remove {} around one line if's.
2021-03-08 17:28:05 +01:00
Jan Kratochvil addbc9b34d [nfc] [lldb] Remove unused function DWARFAttribute::set 2021-03-08 17:04:35 +01:00
Andy Yankovsky 1b7e5d461a [lldb] Fix error message in IRInterpreter
`memory_read_error` -> `memory_write_error`

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D98170
2021-03-08 16:46:38 +01:00
Raphael Isemann 6f3778d31a [lldb][NFC] std::set -> DenseSet in ClangModulesDeclVendor
ModuleID is just an integer so let's use a DenseSet.
2021-03-08 13:13:35 +01:00
Med Ismail Bennani c964741996 [lldb/API] Add CommandInterpreter::{Get,Set}PrintErrors to SBAPI (NFC)
This patch exposes the getter and setter methods for the command
interpreter `print_errors` run option.

rdar://74816984

Differential Revision: https://reviews.llvm.org/D98001

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-05 19:33:33 +01:00
Med Ismail Bennani 36eab4634f [lldb/Interpreter] Add `interpreter.repeat-previous-command` setting
This patch introduces a new interpreter setting to prevent LLDB from
re-executing the previous command when passing an empty command.

This can be very useful when performing actions that requires a long
time to complete.

To preserve the original behaviour, the setting defaults to `true`.

rdar://74983516

Differential Revision: https://reviews.llvm.org/D97999

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-05 19:33:32 +01:00
Dave Lee e7361c8ecc [lldb] Rename QueueFundamentalPlan to QueueBasePlan (NFC)
Minor change for naming consistency.

Differential Revision: https://reviews.llvm.org/D97985
2021-03-04 21:46:49 -08:00
Med Ismail Bennani c16fef19f6 [lldb/Interpreter] Make OptionGroupPythonClassWithDict options non-required
When using `OptionGroupPythonClassWithDict` options in an `OptionGroup`
with other `Options`, it can happen that the combinaison of some options
of each group makes the command invalid.

To solve that issue, this patch adds a bitmask argument to the
`OptionGroupPythonClassWithDict` constuctor that is used to mark each
option as required (or not).

If the `required_options` bitmask isn't passed to the constructor, the
class will keep its default behaviour, making the `--script-class` and
`--python-function` required.

rdar://65508855

Differential Revision: https://reviews.llvm.org/D97910

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-04 20:24:26 +01:00
Pavel Labath bf3ac994c4 [lldb] Apply gdb-remote timeout to platform connections as well
We have a plugin.process.gdb-remote.packet-timeout setting, which can be
used to control how long the lldb client is willing to wait before
declaring the server side dead. Our test suite makes use of this
feature, and sets the setting value fairly high, as the low default
value can cause flaky tests, particularly on slower bots.

After fixing TestPlatformConnect (one of the few tests exercising the
remote platform capabilities of lldb) in 4b284b9ca, it immediately
started being flaky on the arm bots. It turns out this is because the
packet-timeout setting is not being applied to platform connections.

This patch makes the platform connections also respect the value of this
setting. It also adds a test which checks that the timeout value is
being honored.

Differential Revision: https://reviews.llvm.org/D97769
2021-03-04 14:46:02 +01:00
Jason Molenda 266bb78f7d LanguageRuntime for 0th frame unwind, simplify getting pc-for-symbolication
Add calls into LanguageRuntime when finding the unwind method to
use out of the 0th (currently executing) stack frame.

Allow for the LanguageRuntimes to indicate if this stack frames
should be treated like a zeroth-frame -- symbolication should be
done based on the saved pc address, not decremented like normal ABI
function calls.

Add methods to RegisterContext and StackFrame to get a pc value
suitable for symbolication, to reduce the number of places in lldb
where we decrement the saved pc values before symbolication.

<rdar://problem/70398009>
Differential Revision: https://reviews.llvm.org/D97644
2021-03-03 19:29:40 -08:00
Raphael Isemann 820a846609 [lldb][NFC] Delete unused AddressResolverName
That's all just dead code that hasn't been changed in years.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D97760
2021-03-03 13:30:02 +01:00
Andy Yankovsky 3b47bd32f9 [lldb] Fix handling of `DW_AT_decl_file` according to D91014 (attempt #2)
Apply changes from https://reviews.llvm.org/D91014 to other places where DWARF entries are being processed.

Test case is provided by @jankratochvil.
The test is marked to run only on x64 and exclude Windows and Darwin, because the assembly is not OS-independent.

(First attempt https://reviews.llvm.org/D96778 broke the build bots)

Reviewed By: jankratochvil

Differential Revision: https://reviews.llvm.org/D97765
2021-03-03 10:27:35 +01:00
Jonas Devlieghere db8b1598b7 [lldb] Inline objc_opt->version >= 14 to avoid dealing with bool type 2021-03-02 16:41:44 -08:00
Jonas Devlieghere c85d47f7b8 [lldb] Add more logging to __lldb_apple_objc_v2_get_dynamic_class_info 2021-03-02 16:24:59 -08:00
Neal (nealsid) 5826aa48f0 Migrate to llvm::unique_function instead of static member functions for callbacks
A few cleanups suggested in another patch review's comments:

1. Use llvm:unique_function for storing & invoking callbacks from
   Editline to IOHandler
2. Change return type of one of the callback setters from bool to void,
   since it's return value was never used
3. Moved the callback setters inline & made them nonstatic, since that's
   more consistent with other setter definitions
4. Removed the baton parameter since we no longer need it anymore

Differential revision: https://reviews.llvm.org/D50299
2021-03-02 16:13:54 -08:00
Adrian Prantl 14ccba26bd Promote scalars to load addresses when dereferencing them.
This is a follow-up to 188b0747c1. This
is a very narrow fix to a more general problem. LLDB should be better
at distinguishing between implict and memory location descriptions.

rdar://74902042
2021-03-02 14:30:39 -08:00
Jan Kratochvil 1b8fdaacf4 [nfc] [lldb] DWARFDebugInfoEntry::Extract(): reindent 2021-03-02 16:44:07 +01:00
Jan Kratochvil 61c29321b3 [lldb] DWARFDebugInfoEntry::Extract(): Print an error for unsupported DW_FORM_* 2021-03-02 16:39:04 +01:00
Jan Kratochvil 4096ae06f4 [lldb] Support DWARF-5 DW_FORM_line_strp (used by GCC)
LLDB has been failing on binaries produced by new GCC 11.0 with -gdwarf-5.

Differential Revision: https://reviews.llvm.org/D97721
2021-03-02 15:17:23 +01:00
Muhammad Omair Javaid 536783170f Support GDB remote g packet partial read
GDB remote protocol does not specify length of g packet for register read. It depends on remote to include all or exclude certain registers from g packet. In case a register or set of registers is not included as part of g packet then we should fall back to p packet for reading all registers excluded from g packet by remote. This patch adds support for above feature and adds a test-case for the same.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D97498
2021-03-02 17:21:48 +05:00
Yuanfang Chen 5de2d189e6 [Diagnose] Unify MCContext and LLVMContext diagnosing
The situation with inline asm/MC error reporting is kind of messy at the
moment. The errors from MC layout are not reliably propagated and users
have to specify an inlineasm handler separately to get inlineasm
diagnose. The latter issue is not a correctness issue but could be improved.

* Kill LLVMContext inlineasm diagnose handler and migrate it to use
  DiagnoseInfo/DiagnoseHandler.
* Introduce `DiagnoseInfoSrcMgr` to diagnose SourceMgr backed errors. This
  covers use cases like inlineasm, MC, and any clients using SourceMgr.
* Move AsmPrinter::SrcMgrDiagInfo and its instance to MCContext. The next step
  is to combine MCContext::SrcMgr and MCContext::InlineSrcMgr because in all
  use cases, only one of them is used.
* If LLVMContext is available, let MCContext uses LLVMContext's diagnose
  handler; if LLVMContext is not available, MCContext uses its own default
  diagnose handler which just prints SMDiagnostic.
* Change a few clients(Clang, llc, lldb) to use the new way of reporting.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D97449
2021-03-01 15:58:37 -08:00
Med Ismail Bennani 36254f1a0f
[lldb] Revert ScriptedProcess patches
This patch reverts the following commits:
- 5a9c34918b
- 46796762af
- 2cff3dec11
- 182f0d1a34
- d62a53aaf1

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 23:23:27 +00:00
Jonas Devlieghere 6dbea3efc5 [lldb] Add scoped timer to HostInfoMacOSX::GetXcodeSDKPath 2021-03-01 14:57:42 -08:00
Stella Stamenova 801067f4c0 [mlir][lldb] Fix several gcc warnings in mlir and lldb
These warnings are raised when compiling with gcc due to either having too few or too many commas, or in the case of lldb, the possibility of a nullptr.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D97586
2021-03-01 13:48:22 -08:00
Med Ismail Bennani 5a9c34918b [lldb/Plugins] Fix SWIGPythonBridge build issue
This patch should fi the build issue on the windows bots:
https://lab.llvm.org/buildbot/#/builders/83/builds/4214/steps/5/logs/stdio

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 22:37:36 +01:00
Med Ismail Bennani 46796762af [lldb/Plugins] Add ScriptedProcess Process Plugin
This patch introduces Scripted Processes to lldb.

The goal, here, is to be able to attach in the debugger to fake processes
that are backed by script files (in Python, Lua, Swift, etc ...) and
inspect them statically.

Scripted Processes can be used in cooperative multithreading environments
like the XNU Kernel or other real-time operating systems, but it can
also help us improve the debugger testing infrastructure by writting
synthetic tests that simulates hard-to-reproduce process/thread states.

Although ScriptedProcess is not feature-complete at the moment, it has
basic execution capabilities and will improve in the following patches.

rdar://65508855

Differential Revision: https://reviews.llvm.org/D95713

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 21:13:32 +01:00
Med Ismail Bennani 182f0d1a34 [lldb/Interpreter] Add ScriptInterpreter Wrapper for ScriptedProcess
This patch adds a ScriptedProcess interface to the ScriptInterpreter and
more specifically, to the ScriptInterpreterPython.

This interface will be used in the C++ `ScriptProcess` Process Plugin to
call the script methods.

At the moment, not all methods are implemented, they will upstreamed in
upcoming patches.

This patch also adds helper methods to the ScriptInterpreter to
convert `SBAPI` Types (SBData & SBError) to `lldb_private` types
(DataExtractor & Status).

rdar://65508855

Differential Revision: https://reviews.llvm.org/D95711

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 21:13:31 +01:00
Med Ismail Bennani d62a53aaf1 [lldb/Commands] Add command options for ScriptedProcess to ProcessLaunch
This patch adds a new command options to the CommandObjectProcessLaunch
for scripted processes.

Among the options, the user need to specify the class name managing the
scripted process. The user can also use a key-value dictionary holding
arbitrary data that will be passed to the managing class.

This patch also adds getters and setters to `SBLaunchInfo` for the
class name managing the scripted process and the dictionary.

rdar://65508855

Differential Review: https://reviews.llvm.org/D95710

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 21:13:31 +01:00
Med Ismail Bennani 103ad3f907 [lldb/Commands] Fix short option collision for `process launch`
This patch changes the short option used in `CommandOptionsProcessLaunch`
for the `-v|--environment` command option to `-E|--environment`.

The reason for that is, that it collides with the `-v|--structured-data-value`
command option generated by `OptionGroupPythonClassWithDict` that
I'm using in an upcoming patch for the `process launch` command.

The long option `--environment` remains the same.

Differential Review: https://reviews.llvm.org/D95100

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-03-01 21:13:31 +01:00
Jan Kratochvil 011e7bcaa3 Revert "[lldb] Fix handling of `DW_AT_decl_file` according to D91014"
This reverts commit 7ec7876fed.

Non-x86_64 non-Linux bots broke by the testcase.
2021-03-01 20:45:30 +01:00
David Blaikie e913a75414 Fix a warning about named return value not being moved-from.
The use of an rvalue reference here was using reference lifetime
extension needlessly - the code is simpler and more efficient without
it.
2021-03-01 09:25:26 -08:00
Michał Górny c41372c8a1 [lldb] Rename NativeRegisterContext{Watchpoint => DBReg}_x86
Differential Revision: https://reviews.llvm.org/D97210
2021-03-01 16:23:36 +01:00
Andy Yankovsky 7ec7876fed [lldb] Fix handling of `DW_AT_decl_file` according to D91014
Apply changes from https://reviews.llvm.org/D91014 to other places where DWARF entries are being processed.

Differential Revision: https://reviews.llvm.org/D96778
2021-03-01 16:01:11 +01:00
Tatyana Krasnukha 1d6a6f3b0c [lldb/Target] Remove outdated code
Arg0 callback does work.
2021-02-28 19:23:27 +03:00
Tatyana Krasnukha f0f183ee4a [lldb/Interpreter] Fix deep copying for OptionValue classes
Some implementations of the DeepCopy function called the copy constructor that copied m_parent member instead of setting a new parent. Others just leaved the base class's members (m_parent, m_callback, m_was_set) empty.
One more problem is that not all classes override this function, e.g. OptionValueArgs::DeepCopy produces OptionValueArray instance, and Target[Process/Thread]ValueProperty::DeepCopy produces OptionValueProperty. This makes downcasting via static_cast invalid.

The patch implements idiom "virtual constructor" to fix these issues.
Add a test that checks DeepCopy for correct copying/setting all data members of the base class.

Differential Revision: https://reviews.llvm.org/D96952
2021-02-28 19:23:25 +03:00
Tatyana Krasnukha ef447fe008 [lldb] OptionValueProperties::Get[Set]PropertyAtIndexAsArgs should handle OptionValueArgs 2021-02-28 19:23:22 +03:00
Tatyana Krasnukha b2faf30189 [lldb][NFC] Make OptionValueArgs::GetArgs constant 2021-02-28 19:23:20 +03:00
Tatyana Krasnukha 8cdcd41e38 [lldb/Interpreter][NFC] Remove explicit default initialization of members and base classes
According to clang-tidy's readability-redundant-member-init.
2021-02-28 19:23:18 +03:00
Tatyana Krasnukha 54d03a4985 [lldb/Interpreter][NFC] Replace default constructors/destructors bodies with "=default" 2021-02-28 19:23:16 +03:00
Dave Lee 3a677b29a3 [lldb] Add deref support to libc++ unique_ptr synthetic
Add frame variable dereference suppport to libc++ `std::unique_ptr`.

This change allows for commands like `v *thing_up` and `v thing_up->m_id`. These commands now work the same way they would with raw pointers, and as they would with expression. This is done by adding an unaccounted for child member named `$$dereference$$`.

Without this change, the command would have to be written as `v *thing_up.__value_` or v thing_up.__value_->m_id` which exposes internal structure and is more clumsy to type.

Additionally, the existing tests were updated. See also https://reviews.llvm.org/D97165 which added deref support for `std::shared_ptr`.

Differential Revision: https://reviews.llvm.org/D97524
2021-02-26 07:39:01 -08:00
Med Ismail Bennani b889ef4214 [lldb/Core] Change large function threshold variable into a setting.
This patch replaces the static large function threshold variable with a
global debugger setting (`stop-disassembly-max-size`).

The default threshold is now set to 32KB (instead of 8KB) and can be modified.

rdar://74726362

Differential Revision: https://reviews.llvm.org/D97486

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-02-25 22:35:04 +01:00
Raphael Isemann 86c267233f [lldb][NFC] Document ClangASTImporter 2021-02-25 13:25:34 +01:00
Raphael Isemann 2d6b767c1d [lldb][NFC] Remove some obsolete comments in ClangASTImporter.cpp
The first two comments are incomplete and reference obsolete code. The
last one is just commented out code (that also doesn't look correct).
2021-02-25 11:44:19 +01:00
Raphael Isemann 7cfa6e1cc6 [lldb] Let ClangASTImporter assert that the target AST has an external source
This prevents people from accidentially using this code outside the
intended setup.
2021-02-25 11:42:14 +01:00
Jonas Devlieghere 38dfb235db [lldb] Support debugging utility functions
LLDB uses utility functions to run code in the inferior for its own
internal purposes, such as reading classes from the Objective-C runtime
for example. Because these expressions should be transparent to the
user, we ignore breakpoints and unwind the stack on errors, which
makes them hard to debug.

This patch adds a new setting target.debug-utility-expression that, when
enabled, changes these options to facilitate debugging. It enables
breakpoints, disables unwinding and writes out the utility function
source code to disk so it shows up in the source view.

Differential revision: https://reviews.llvm.org/D97249
2021-02-24 11:36:01 -08:00
Raphael Isemann 6201017d54 [lldb] Prevent double new lines behind errors/warning/messages from LLDB commands
The current API for printing errors/warnings/messages from LLDB commands
sometimes adds newlines behind the messages for the caller. However, this
happens unconditionally so when the caller already specified a trailing newline
in the error message (or is trying to print a generated error message that ends
in a newline), LLDB ends up printing both the automatically added newline and
the one that was in the error message string. This leads to all the randomly
appearing new lines in error such as:

```
(lldb) command a
error: 'command alias' requires at least two arguments
(lldb) apropos a b
error: 'apropos' must be called with exactly one argument.

(lldb) why is there an empty line behind the second error?
```

This code adds a check that only appends the new line if the passed message
doesn't already contain a trailing new line.

Also removes the AppendRawWarning which had only one caller and doesn't serve
any purpose now.

Reviewed By: #lldb, mib

Differential Revision: https://reviews.llvm.org/D96947
2021-02-24 14:42:01 +01:00
Raphael Isemann 0512b01ebe [lldb][NFC] Move trivial ValueObject getters/setters to the header
NFC refactoring that moves the definitions of all the trivial getters/setters to the header file
which is what we usually do in LLVM.

Reviewed By: #lldb, JDevlieghere

Differential Revision: https://reviews.llvm.org/D97298
2021-02-24 14:04:01 +01:00
Raphael Isemann 4631afdeb3 [lldb][NFC] Rename the second ValueObjectManager to ValueObjectUpdater and remove the dead code
`ValueObject.h` contains the `ValueObject::ValueObjectManager` type which is
just a typedef for the ClusterManager that takes care of the whole ValueObject
memory management. However, there is also `ValueObjectManager` defined in the
same header which is only used in the curses UI implementation and consists
mostly of dead and completely untested code.

This code been around since a while (it was added in 2016 as
8369b28da0), so I think we shouldn't just revert
the whole patch.

Instead this patch just moves the class to its own header that it isn't just
hiding in the ValueObject header and renames it to `ValueObjectUpdater` that it
at least has a unique name (which I hope also slightly better reflects the
purpose of this class). I also deleted all the dead code branches and functions.

Reviewed By: #lldb, mib, JDevlieghere

Differential Revision: https://reviews.llvm.org/D97287
2021-02-24 13:58:01 +01:00
Raphael Isemann 2105912ee0 [lldb] Add asserts that prevent construction of cycles in the decl origin tracking
LLDB tracks where any imported `clang::Decl` originally came from via a simple
map from 'imported decl' to 'original decl'. That information is used to later
complete parts of the Decl when more information is requested about a certain
Decl (e.g., via the ExternalASTSource interface from Clang).

When finding the 'original decl' for a given decl, the ASTImporterDelegate
essentially just recursively follows the previously mentioned map from
'imported' to 'original decl' until it can find any further 'original decl'. The
final found decl is then the one that will be imported. The recursion is
necessary as in LLDB we don't just import decls from one ASTContext to another,
but also from one ASTContext to another via a (potentially temporary)
ASTContext. For example, the expression parser creates a temporary ASTContext
for parsing the current expression.

The problem with the recursion is however that if we somehow get a cycle into
our mapping, then the ASTImporterDelegate will just infinite recurse. As the
infinite recursion usually happens after the cycle was already created in a code
path such as completing a type, the crash backtraces we get for these bugs are
not very useful. However having the backtrace where the faulty map entry is
created usually makes the code trivial to fix (as there should be some rogue
CopyType call or something similar nearby. See for example D96366).

This patch tries to make these issues easier to track down by putting a bunch of
sanity asserts in the code that fills out the map. All the asserts are just
checking that there is no direct cycle (ASTContext maps to itself) when updating
the origin tracking map.

The assert in the ASTImportDelegate constructor is an `lldbassert` (which also
is getting checked in release builds with disabled asserts) as the code path
there is pretty cold and we can reliably detect a rogue CopyType call from
there.

I also had to update some code in
`ClangASTImporter::ASTImporterDelegate::Imported`. This code already had a
safety check for creating a cycle in the origin tracking map, but it still
constructed an ASTImporter while checking for the cycle (by requesting a
delegate via `GetDelegate` and passing two identical ASTContexts which looks
like a rogue CopyType call to the checks).

Reviewed By: shafik

Differential Revision: https://reviews.llvm.org/D97300
2021-02-24 13:25:49 +01:00
Jorge Gorbe Moya 979ca1c05f Defer the decision whether to use the CU or TU index until after reading the unit header.
In DWARF v4 compile units go in .debug_info and type units go in
.debug_types. However, in v5 both kinds of units are in .debug_info.
Therefore we can't decide whether to use the CU or TU index just by
looking at which section we're reading from. We have to wait until we
have read the unit type from the header.

Differential Revision: https://reviews.llvm.org/D96194
2021-02-23 13:26:11 -08:00
Dave Lee 0ac42fd26d [lldb] Add deref support and tests to shared_ptr synthetic
Add `frame variable` dereference suppport to libc++ `std::shared_ptr`.

This change allows for commands like `v *thing_sp` and `v thing_sp->m_id`. These
commands now work the same way they do with raw pointers. This is done by adding an
unaccounted for child member named `$$dereference$$`.

Also, add API tests for `std::shared_ptr`, previously there were none.

Differential Revision: https://reviews.llvm.org/D97165
2021-02-23 09:03:46 -08:00
Raphael Isemann bea2d5e478 [lldb][NFC] Remove unused ValueObject::LogValueObject functions
Those functions aren't called anywhere. For debugging purposes we usually
have Dump() methods (which already exist in some semi-functional form in
ValueObject).
2021-02-23 12:10:40 +01:00
Raphael Isemann 03310c1e95 [lldb][NFC] Give CompilerType's IsArrayType/IsVectorType/IsBlockPointerType out-parameters default values
We already do this for most functions that have out-parameters, so let's do
the same here and avoid all the `nullptr, nullptr, nullptr` in every call.
2021-02-23 11:15:31 +01:00
Raphael Isemann d77e3c6aec [lldb][NFC] Don't inherit from UserID in ValueObject
ValueObject inherits from UserID which is just a bad idea:

* The inheritance gives ValueObject some member functions that are at best
  misleading (such as `Clear()` which doesn't clear any value beside `id`).

* It allows passing ValueObject to the overloaded operators for UserID (such as
  `==` or `<<` which won't actually compare or print anything in the ValueObject).

* It exposes the `SetID` and `Clear` which both allow users to change the
  internal id value.

Similar to D91699 which did the same for Process

Reviewed By: #lldb, JDevlieghere

Differential Revision: https://reviews.llvm.org/D97205
2021-02-23 10:15:42 +01:00
Raphael Isemann 8f63cf5da3 [lldb][NFC] Cleanup ValueObject construction code
Just code cleanup for ValueObject constructors:

* Use default member initializers where possible.
* Doxygenify the comments for membersa nd constructors where needed.
* Delete the default constructor which isn't defined.
* Initialize the bitfields via a utility struct instead of doing this in the
  different constructors.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D97199
2021-02-23 09:39:18 +01:00
Jonas Devlieghere 5d2850161e [lldb] Reinstate support for LLDB_VERSION_STRING
Reinstate support for specifying -DLLDB_VERSION_STRING="best-lldb"
which seems to have gotten accidentally removed in the past.

rdar://38983903

Differential revision: https://reviews.llvm.org/D97235
2021-02-22 16:56:00 -08:00
António Afonso b19d3b092d Revert "Make sure the interpreter module was loaded before making checks against it"
This reverts commit a83a825e99.
2021-02-21 10:38:25 -08:00
António Afonso a83a825e99 Make sure the interpreter module was loaded before making checks against it
This issue was introduced in https://reviews.llvm.org/D92187.
The guard I'm changing were is supposed to act when linux is loading the linker for the second time (due to differences in paths like symlinks).
This is done by checking `module_sp != m_interpreter_module.lock()` however this will be true when `m_interpreter_module` wasn't initialized, making linux unload the linker module (the most visible result here is that lldb will stop getting notified about new modules loaded by the process, because it can't set the rendezvous breakpoint again after the stepping over it once).
The `m_interpreter_module` is not getting initialize when it goes through this path: dbfdb139f7/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp (L332), which happens when lldb was able to read the address from the dynamic section of the executable.

What I'm not sure about though, is if when we go through this path if we still load the linker twice on linux. If that's the case then it means we need to somehow set the m_interpreter_module instead of the fix I provide here. I've only tested this on Android.

Differential Revision: https://reviews.llvm.org/D96637
2021-02-21 09:28:04 -08:00
Dave Lee b0186c25c6 [lldb] Refine ThreadPlan::ShouldAutoContinue
Adjust `ShouldAutoContinue` to be available to any thread plan previous to the plan that
explains a stop, not limited to the parent to the plan that explains the stop.

Before this change, `Thread::ShouldStop` did the following:

1. find the plan that explains the stop
2. if it's not a master plan, continue processing previous (aka parent) plans
3. first, call `ShouldAutoContinue` on the immediate parent of the explaining plan
4. then loop over previous plans, calling `ShouldStop` and `MischiefManaged`

Of note, the iteration in step 4 does not call `ShouldAutoContinue`, so again only the
plan just prior to the explaining plan is given the opportunity to override whether to
continue or stop.

This commit changes the loop call `ShouldAutoContinue`, giving each plan the opportunity
to override `ShouldStop` of previous plans.

Why? This allows a plan to do the following:

1. mark itself done and be popped off the stack
2. allow parent plans to finish their work, and to also be popped off the stack
3. and finally, have the thread continue, not stop

This is useful for stepping into async functions. A plan will would step far enough
enough to set a breakpoint on the async target, and then use `ShouldAutoContinue` to
unwind the necessary stepping, and then have the calling thread continue.

Differential Revision: https://reviews.llvm.org/D97076
2021-02-20 17:25:31 -08:00
Dave Lee 9d3b9e5799 [lldb] Rename {stop,run}_vote to report_{stop,run}_vote
Rename `stop_vote` and `run_vote` to `report_stop_vote` and `report_run_vote`
respectively. These variables are limited to logic involving (event) reporting only.
This naming is intended to make their context more clear.

Differential Revision: https://reviews.llvm.org/D96917
2021-02-19 13:04:53 -08:00
Jan Kratochvil 08331281af [lldb/Commands] Fix help text typo for 'breakpoint set' -a|--address. 2021-02-19 14:33:42 +01:00
Jason Molenda d82ecb0ac7 LanguageRuntime can provide an UnwindPlan for special occasions
Add a facility in the LanguageRuntime to provide a special
UnwindPlan based on the register values in a RegisterContext,
instead of using the return-pc to find a function and use its
normal UnwindPlans.

Needed when the runtime has special stack frames that we want
to show the user, but aren't actually on the real stack.
Specifically for Swift asynchronous functions.

With feedback from Greg Clayton, Jonas Devlieghere, Dave Lee

<rdar://problem/70398009>

Differential Revision: https://reviews.llvm.org/D96839
2021-02-18 23:23:15 -08:00
Jonas Devlieghere 31fa76fd24 [lldb] Check that files exists before handing them off to FileCollector
The FileCollector asserts that paths passed to addDirectory are indeed
directories. For that to work, the file needs to actually exist. In the
downstream Swift fork we have tests that remove files during testing,
which resulted in this assertion getting triggered.
2021-02-18 16:16:15 -08:00
Jonas Devlieghere 612384f6e0 [lldb] Remove unused code in ScriptInterpreterPython
Remove the unused code I noticed when working on d6e80578fc and do
some other minor cleanups in the vicinity.
2021-02-18 10:38:54 -08:00
Pavel Labath 004a264f8c [lldb] Fix shared library directory computation on windows
Our code for locating the shared library directory works via dladdr (or
the windows equivalent) to locate the path of an address known to reside
in liblldb. This works great for C++ programs, but there's a catch.

When (lib)lldb is used from python (like in our test suite), this dladdr
call will return a path to the _lldb.so (or such) file in the python
directory. To compensate for this, we have code which attempts to
resolve this symlink, to ensure we get the canonical location. However,
here's the second catch.

On windows, this file is not a symlink (but a copy), so this logic
fails. Since most of our other paths are derived from the liblldb
location, all of these paths will be wrong, when running the test suite.
One effect of this was the failure to find lldb-server in D96202.

To fix this issue, I add some windows-specific code to locate the
liblldb directory. Since it cannot rely on symlinks, it works by
manually walking the directory tree -- essentially doing the opposite of
what we do when computing the python directory.

To avoid python leaking back into the host code, I implement this with
the help of a callback which can be passed to HostInfo::Initialize in
order to assist with the directory location. The callback lives inside
the python plugin.

I also strenghten the existing path test to ensure the returned path is
the right one.

Differential Revision: https://reviews.llvm.org/D96779
2021-02-18 15:37:52 +01:00
Raphael Isemann fb1dc77bfd [lldb][NFC] Silence missing case warnings in TypeSystemClang::GetTypeBitAlign due to new RISC-V V types
Those types were added in D92715. This just silences the warning but doesn't
actually add support for those types to LLDB.
2021-02-18 09:03:18 +01:00
Jason Molenda fcdef15d77 Add a new Row setting to mark all un-declared regs as Undefined
Add a new state for UnwindPlan::Row which indicates that any
register not listed is not defined, and should not be found in
stack frames newer than this one and passed up the stack.  Mostly
intended for use with architectural default unwind plans that are
used for jitted stack frames, where we have no unwind information
or start address.  lldb has no way to tell if registers were
spilled in the jitted frame & overwritten, so passing register
values up the stack is not safe to show the user.

Architectural default unwind plans are also used as a fast unwind
plan on x86_64 in particular, and are used as the fallback unwind
plans when lldb thinks it may be able to work around a problem
which causes the unwinder to stop walking the stack early.

For fast unwind plans, when we don't find a register location in
the arch default unwind plan, we fall back to computing & using
the full unwind plan. One small part of this patch is to know that
a register marked as Undefined in the fast unwind plan is a special
case, and we should continue on to the full unwind plan to find what
the real unwind rule is for this register.

Differential Revision: https://reviews.llvm.org/D96829
<rdar://problem/70398009>
2021-02-17 23:52:28 -08:00
Jonas Devlieghere d6e80578fc [lldb] Improve error message for modules with dots or dashes
LLDB does not like to import Python files with dashes or dots in their
name. While the former are technically allowed, it is discouraged. Dots
are allowed for subpackages but not in module names. This patch improves
the user experience by printing a useful error.

Before this patch:

  error: module importing failed: SyntaxError('invalid syntax',
  ('<string>', 1, 11, 'import foo-bar\n'))

After this patch:

  error: module importing failed: Python discourages dashes in module
  names: foo-bar

rdar://74263511

[1] https://www.python.org/dev/peps/pep-0008/#package-and-module-names

Differential revision: https://reviews.llvm.org/D96833
2021-02-17 10:00:29 -08:00
Michał Górny 9f38001bf0 [lldb] [Process/FreeBSD] Ensure that errors are always handled
Ensure that the llvm::Error instances are always considered handled
by replacing LLDB_LOG with LLDB_LOG_ERROR.

Differential Revision: https://reviews.llvm.org/D96558
2021-02-16 22:21:37 +01:00
Pavel Labath 901ea29662 [lldb] Delete superfluous semicolon 2021-02-16 21:07:58 +01:00
Pavel Labath 1db2888e70 [lldb] Remove some nanosleep preprocessor magic
It's obsolete, as we use (portable) std::this_thread::sleep_for now.
2021-02-16 21:07:57 +01:00
Dave Lee 4946f37d84 [lldb] Remove very old misleading comment (NFC) 2021-02-15 18:14:57 -08:00
Dave Lee 22f0aa0d9e [lldb] Remove unused ThreadPlan tracer utilities (NFC)
Delete unused `EnableTracer()` and `SetTracer()` functions on `Thread`. By deleting
these, their `ThreadPlan` counterparts also become unused.

Then, by deleting `ThreadPlanStack::EnableTracer`, `EnableSingleStep` becomes unused.
With no more callers to `EnableSingleStep`, the value `m_single_step` is always true and
can be removed as well.

Differential Revision: https://reviews.llvm.org/D96666
2021-02-15 17:59:25 -08:00
Dave Lee 2a2464eb76 [lldb] Lower GetRealStopInfo into ThreadPlanCallFunction (NFC)
`GetRealStopInfo` has only one call site, and in that call site a reference to the
concrete thread plan is available (`ThreadPlanCallUserExpression`), from which
`GetRealStopInfo` can be called.

Differential Revision: https://reviews.llvm.org/D96687
2021-02-15 17:59:24 -08:00
Dave Lee 65d91b40ae [lldb] Minor refinements to ThreadPlan::RestoreThreadState (NFC)
Correct `RestoreThreadState` to a `void` return type. Also, update the signature of its
callee, `Thread::RestoreThreadStateFromCheckpoint`, by updating it to a `void` return
type, and making it non-`virtual`.

Differential Revision: https://reviews.llvm.org/D96688
2021-02-15 17:57:13 -08:00
Michał Górny bee4d6efe1 [lldb] Rename FreeBSDRemote to FreeBSD (NFC)
Differential Revision: https://reviews.llvm.org/D96557
2021-02-15 13:04:11 +01:00
Michał Górny cd44339856 [lldb] Remove the legacy FreeBSD plugin
The new FreeBSDRemote plugin has reached feature parity with the legacy
plugin, so we can finally remove the latter.  The new plugin will
be renamed to FreeBSD in a separate commit to avoid confusion.

Differential Revision: https://reviews.llvm.org/D96555
2021-02-15 13:04:11 +01:00
Michał Górny 011791dda4 [lldb] [Process/FreeBSDRemote] Fix clang-formatting on ppc commit 2021-02-14 22:34:25 +01:00
Benjamin Kramer 2dbe88db58 [lldb] Fix up SysV ABI implementations after 057efa9916 2021-02-13 01:34:00 +01:00
Adrian Prantl 188b0747c1 Support dereferencing a DWARF scalar stack value
Swift async functions receive function arguments inside a
heap-allocated data structure, similar to how ObjC block captures or
C++ coroutine arguments are implement. In DWARF they are described
relative to an entry value that produces a pointer into that heap
object. At typical location looks like

DW_OP_entry_value [ DW_OP_reg14 ] DW_OP_deref DW_OP_plus_uconst 32 DW_OP_deref

This allows the unwinder (which has special ABI knowledge to restore
the contents of r14) to push the base address onto the stack thus
allowing the deref/offset operations to continue. The result of the
entry value is a scalar, because DW_OP_reg14 is a register location —
as it should be since we want to restore the pointer value contained
in r14 at the beginning of the function and not the historical memory
contents it was pointing to. The entry value should restore the
address, which is still valid, not the contents at function entry.

To make this work, we need to allow LLDB to dereference Scalar stack
results like load addresses, which is what this patch
does. Unfortunately it is difficult to test this in isolation, since
the DWARFExpression unit test doesn't have a process.

Differential Revision: https://reviews.llvm.org/D96549
2021-02-12 16:12:32 -08:00
Adrian Prantl 057efa9916 Make the error condition in Value::ValueType explicit (NFC)
The comment for ValueType claims that all values <1 are errors, but
not all switch statements take this into account. This patch
introduces an explicit Error case and deletes all default: cases, so
we get warned about incomplete switch coverage.

https://reviews.llvm.org/D96537
2021-02-12 16:12:31 -08:00
Shafik Yaghmour 9f175998de [LLDB] Fix LLDB_LOG calls to use correct formatting
It looks like a previous change switched these from LLDB_LOGF but did not update the format strings.

Differential Revision: https://reviews.llvm.org/D96550
2021-02-12 11:09:39 -08:00
Jonas Devlieghere 732534ed64 [lldb] s/TARGET_OS_EMBEDDED/TARGET_OS_IPHONE/
TARGET_OS_EMBEDDED is deprecated, use TARGET_OS_IPHONE and/or
TARGET_OS_SIMULATOR instead.
2021-02-11 20:40:59 -08:00
Jonas Devlieghere 4d3a061c32 [lldb] Fix 'r' and 'run' aliases on Apple Silicon
The 'r' and 'run' aliases were different based on the target
architecture. I suspect the intention was to disable shell expansion on
embedded devices. This fixes TestCustomShell.test on AS.
2021-02-11 20:23:53 -08:00
Peter Collingbourne c314f5ede8 ObjectFileELF: Test whether reloc_header is non-null instead of asserting.
It is possible for the GetSectionHeaderByIndex lookup to fail because
the previous FindSectionContainingFileAddress lookup found a segment
instead of a section. This is possible if the binary does not have
a PLT (which means that lld will in some circumstances set DT_JMPREL
to 0, which is typically an address that is part of the ELF headers
and not in a section) and may also be possible if the section headers
have been stripped. To handle this possibility, replace the assert
with an if.

Differential Revision: https://reviews.llvm.org/D93438
2021-02-11 15:05:18 -08:00
Dave Lee a5ab1dc4ad [lldb] Add step target to ThreadPlanStepInRange constructor
`QueueThreadPlanForStepInRange` accepts a `step_into_target`, but the constructor for
`ThreadPlanStepInRange` does not. Instead, a caller would optionally call
`SetStepInTarget()` in a separate statement.

This change adds `step_into_target` as a constructor argument. This simplifies
construction of `ThreadPlanSP`, by avoiding a subsequent downcast and conditional
assignment. This constructor is already used in downstream repos.

Differential Revision: https://reviews.llvm.org/D96539
2021-02-11 14:57:20 -08:00
Raphael Isemann 71536fd031 [lldb] Fix that running a top level expression without a process fails with a cryptic error
Right now when running `expr --top-level -- void foo() {}`, LLDB just prints a cryptic
`error: Couldn't find $__lldb_expr() in the module` error. The reason for that is
that if we don't have a running process, we try to set our execution policy to always use the
IR interpreter (ExecutionPolicyNever) which works even without a process. However
that code didn't consider the special ExecutionPolicyTopLevel which we use for
top-level expressions. By changing the execution policy to ExecutionPolicyNever,
LLDB thinks we're actually trying to interpret a normal expression inside our
`$__lldb_expr` function and then fails when looking for it.

This just adds an exception for top-level expressions to that code and a bunch of tests.

Reviewed By: shafik

Differential Revision: https://reviews.llvm.org/D91723
2021-02-11 17:07:11 +01:00
Raphael Isemann 19b4d3ce27 [lldb] Don't emit a warning when using Objective-C getters in expressions
Clang emits a warning when accessing an Objective-C getter but not using the result.
This gets triggered when just trying to print a getter value in the expression parser (where
Clang just sees a normal expression like `obj.getter` while parsing).

This patch just disables the warning in the expression parser (similar to what we do with
the C++ equivalent of just accessing a member variable but not doing anything with it).

Reviewed By: kastiglione

Differential Revision: https://reviews.llvm.org/D94307
2021-02-11 16:48:41 +01:00
Raphael Isemann e87b8e4498 [lldb] Log the actual expression result in UserExpression::Evaluate
This used to be a LLDB_LOGF call that used the printf %s syntax.
0ab109d43d changed it to LLDB_LOG but didn't
update this format string to use formatv's syntax so this just printed '%s'.
2021-02-11 16:15:01 +01:00
Adrian Prantl 585e7a359d Diagnose unhandled cases in DW_OP_deref 2021-02-10 17:27:02 -08:00
Dave Lee 309d40f052 [lldb] Use internal_dict name over dict in python examples
Follow up to https://reviews.llvm.org/rG483ec136da7193de781a5284f1c37929cc27c05c
2021-02-10 15:11:00 -08:00
Dave Lee 606c3be85d [lldb] Minor cleanups to ThreadPlan.h (NFC)
While learning about ThreadPlan, I did a bit of cleanup:

* Remove unused code
* Move functions to protected where applicable
* Remove virtual for functions that are not overridden

Differential Revision: https://reviews.llvm.org/D96277
2021-02-10 13:36:38 -08:00
Jim Ingham 483ec136da Use internal_dict everywhere we refer to the python session dict in docs. 2021-02-09 17:48:47 -08:00
Shafik Yaghmour 4f14c17df7 [LLDB] Remove uneeded CopyType from BlockPointerSyntheticFrontEnd
BlockPointerSyntheticFrontEnd does a CopyType which results in it copying the type
back into its own context. This will result in a call to ASTImporterDelegate::setOrigin
with &decl->getASTContext() == origin.ctx this can result in an infinite recursion
later on in ASTImporter since it will attempt to find the decl in its origin which will be itself.

Differential Revision: https://reviews.llvm.org/D96366
2021-02-09 16:11:28 -08:00
Jim Ingham ffd7be65d0 Remove trailing spaces after \ in comments. 2021-02-09 16:06:47 -08:00
Jim Ingham 365b186c24 Add documentation for the extra_args parameter to breakpoint commands.
Differential Revision: https://reviews.llvm.org/D96368
2021-02-09 15:33:36 -08:00
Michał Górny bd03f6df51 [lldb] [Process/FreeBSDRemote] Introduce powerpc support
Introduce a minimal support for the 32-bit powerpc platform.  This
includes support for GPR and FPR registers.  I also needed to add
software breakpoint opcode for PPC32/PPC64 (big endian), and to fix
offsets in RegisterInfos_powerpc.h (used only by FreeBSD register
context to be globally unique rather than relative to each struct).

Differential Revision: https://reviews.llvm.org/D95947
2021-02-09 21:10:45 +01:00
Dave Lee 2309392449 [lldb] Inline invariant params to AppleThreadPlanStepThrough (NFC)
These two `AppleThreadPlanStepThrough` thread plans have parameterized behavior
that is unutilized. To make their interface and implementation simpler, this
change inlines those outside parameters.

Differential Revision: https://reviews.llvm.org/D96276
2021-02-09 08:03:51 -08:00
Dave Lee 7dc324aafa [lldb] Fix crash in FormatEntity for mangled-name
Check a `Block` pointer before dereferencing.

Using `function.mangled-name` led to a crash for a frame where the symbol
context had no block info. In my case, the frame's function was a system frame.

Differential Revision: https://reviews.llvm.org/D96307
2021-02-08 18:38:08 -08:00
Michał Górny 8244fc505d [lldb] [Process/FreeBSDRemote] Introduce mips64 support
Introduce mips64 support to match the legacy FreeBSD plugin. Similarly
to the legacy plugin, the code does not support FPU registers at the
moment.  The support for them will be submitted separately as it
requires changes to the register context shared by both plugins.

This also includes software single-stepping support that is moved from
the Linux plugin into a common Utility class.  The FreeBSD code also
starts explicitly ignoring EINVAL from PT_CLEARSTEP since this is easier
to implement than checking whether hardware single-stepping were used.

Differential Revision: https://reviews.llvm.org/D95802
2021-02-08 18:27:26 +01:00
Frederik Gossen 5a63045fe7 [LLDB] Fix `Wunused-result` warning 2021-02-08 18:10:08 +01:00
Tatyana Krasnukha 36de94cf54 Reland "[lldb] Make CommandInterpreter's execution context the same as debugger's one" 2021-02-08 15:09:09 +03:00
Tatyana Krasnukha a39bcbca92 [lldb] Debugger: reuse ExecutionContextRef to create ExecutionContext from Target
The Debugger didn't take the Process's run lock, that causes deadlocks and races
after applying https://reviews.llvm.org/D92164 revision. Since ExecutionContextRef
does the same job correctly, Debugger::GetSelectedExecutionContext just can use it
to build execution context upon the selected target.
2021-02-08 15:09:08 +03:00
Muhammad Omair Javaid 8561ad9296 Use remote regnums in expedited list, value regs and invalidate regs
Native register descriptions in LLDB specify lldb register numbers in
value_regs and invalidate_regs lists. These register numbers may not
match with Process gdb-remote register numbers which are generated by
native process after counting all registers in its register sets.

It was coincidentally not causing any problems as we never came across
a native target with dynamically changing register sets and register
numbers generated by counter matched with LLDB native register numbers.
This came up while testing target AArch64 SVE which can choose register
sets based on underlying hardware.

This patch fixes this behavior and always tries to use remote register
numbers while reading/writing registers over gdb-remote protocol.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D77043
2021-02-08 14:09:15 +05:00
Djordje Todorovic 9abd8c1a4c [elf-core] Improve reading memory from core file
This patch tries to improve memory-read from core files
(in order to improve disassembly functionality).

I am using RHEL 7.7 (linux kernel 3.10) and for a lot of cases,
I was not able to disassemble some functions from backtrace when
debugging crashes from core files. It outputs some dummy code.

The cause of the problem was the fact we are returning all the zeros
from ProcessElfCore::ReadMemory() that is being called within
Disassembler::ParseInstructions() and it disassembles some dummy
opcodes from the buffer returned. Therefore, we are removing zero
bytes filling (padding) completely.

Differential Revision: https://reviews.llvm.org/D93939
2021-02-08 00:14:32 -08:00
Raphael Isemann 6e1afd8587 [lldb][NFC] Minor comment and inlining fixes for Args
The element count getter can just be in the header. Also doxygenify some of the
comments and document m_argv's terminating nullptr element that the other
comments keep mentioning.
2021-02-05 10:17:16 +01:00
Adrian Prantl 644ef58073 Print the "no plugin" warning only when there is no plugin
... and not when the typesystem failed to initialize.

rdar://72562341

Differential Revision: https://reviews.llvm.org/D95992
2021-02-04 11:06:10 -08:00
Jonas Devlieghere 98e50a7d4c [lldb] Honor the CPU type & subtype when launching on macOS
Honor the CPU type (and subtype) when launching the inferior on macOS.

Part of this functionality was thought to be no longer needed and
removed in 85bd436961, however it's still
needed, for example to launch binaries under Rosetta 2 on Apple Silicon.

This patch will use posix_spawnattr_setarchpref_np if available and
fallback to posix_spawnattr_setbinpref_np if not.

Differential revision: https://reviews.llvm.org/D95922
2021-02-03 13:42:00 -08:00
Med Ismail Bennani 608ee55a31
[lldb/test] Stop recording fundamental return types (NFC)
It seems that recording fundamental return type is bogus.

This can trigger asserts when running a test with reproducers so this
patch updates the `SBTarget::IsLoaded` test to stop recording them.

Differential Revision: https://reviews.llvm.org/D95686

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-02-03 02:57:26 +01:00
Raphael Isemann 0f2be195d5 Revert "[lldb] Use current execution context in SBDebugger"
This reverts commit 754ab803b8.

As pointed out in https://reviews.llvm.org/D95761, this patch could lead to
having the wrong execution context in some situations (thanks Jim!).

D92164 is addressing the same issue and will replace this patch, so I'll
revert this one.
2021-02-02 14:41:48 +01:00
Nathan Hawes ecb00a7762 [VFS] Add support to RedirectingFileSystem for mapping a virtual directory to one in the external FS.
Previously file entries in the -ivfsoverlay yaml could map to a file in the
external file system, but directories had to list their contents in the form of
other file entries or directories. Allowing directory entries to map to a
directory in the external file system makes it possible to present an external
directory's contents in a different location and (in combination with the
'fallthrough' option) overlay one directory's contents on top of another.

rdar://problem/72485443
Differential Revision: https://reviews.llvm.org/D94844
2021-02-02 14:56:17 +10:00
Andy Yankovsky 754ab803b8 [lldb] Use current execution context in SBDebugger
Use `GetSelectedExecutionContext()` instead of
`GetCommandInterpreter().GetExecutionContext()` in
`SBDebugger::GetInternalVariableValue/SBDebugger::SetInternalVariable`. The
execution context in the command interpreter might be empty, if no commands has
been executed yet (it is updated only when handling commands or completions --
e.g.
https://github.com/llvm/llvm-project/blob/main/lldb/source/Interpreter/CommandInterpreter.cpp#L1855).

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D95761
2021-02-01 13:12:42 +01:00
Med Ismail Bennani b8923c0022 [lldb/API] Expose Module::IsLoadedInTarget() to SB API (NFC)
This patch adds an `SBTarget::IsLoaded(const SBModule&) const` endpoint
to lldb's Scripting Bridge API. As the name suggests, it will allow the
user to know if the module is loaded in a specific target.

rdar://37957625

Differential Review: https://reviews.llvm.org/D95686

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-02-01 12:16:33 +01:00
Michał Górny 9d029362d1 [lldb] [Process/FreeBSDRemote] Introduce arm (32-bit) support
Introduce a NativeRegisterContextFreeBSD for 32-bit ARM platform.
This includes support for GPR + VFP registers as exposed by FreeBSD's
ptrace(2) API.  Hardware breakpoints or watchpoints are not supported
due to missing kernel support.  The code is roughly based on the arm64
context.

It also includes an override for GetSoftwareBreakpointTrapOpcode() based
on the matching code in the PlatformFreeBSD plugin.

Differential Revision: https://reviews.llvm.org/D95696
2021-01-31 19:52:08 +01:00
Michał Górny f43c0707f6 [lldb] [Process/FreeBSDRemote] Introduce arm64 support
Introduce arm64 support in the FreeBSDRemote plugin.  The code
is roughly based on Linux and reuses the same POSIX RegisterInfos
(but the buffers need to be a few bytes larger due to stricter struct
member alignment in FreeBSD structures -- luckily, they do not affect
the actual member offsets).  It supports reading and writing
general-purpose and FPU registers.  SVE and hardware watchpoint support
is missing due to the limitations of FreeBSD ptrace(2) API.

Differential Revision: https://reviews.llvm.org/D95297
2021-01-31 19:52:08 +01:00
Nathan Hawes 719f778441 [VFS] Combine VFSFromYamlDirIterImpl and OverlayFSDirIterImpl into a single implementation (NFC)
As a fixme notes, both of these directory iterator implementations are
conceptually similar and duplicate the functionality of returning and uniquing
entries across two or more directories. This patch combines them into a single
class 'CombiningDirIterImpl'.

This also drops the 'Redirecting' prefix from RedirectingDirEntry and
RedirectingFileEntry to save horizontal space. There's no loss of clarity as
they already have to be prefixed with 'RedirectingFileSystem::' whenever
they're referenced anyway.

rdar://problem/72485443
Differential Revision: https://reviews.llvm.org/D94857
2021-01-30 11:10:10 +10:00
Raphael Isemann e2a1a718bb [lldb] Add move_iterator to supported template list
Identical to previous commits that just add a standard library template to the
supported template list and test it. Adding this rather obscure class to the
template list is mostly caused by the std::deque test unexpectedly referencing
this type when testing against newer libc++ versions on macOS.

Fixes TestQueueFromStdModule and TestQueueFromStdModule on macOS.
Fixes rdar://73213589
2021-01-27 13:52:42 +01:00
Jim Ingham 7636b1f6ef Make SBDebugger::CreateTargetWithFileAndArch work with lldb::LLDB_DEFAULT_ARCH
Second try, handling both a bogus arch string and the "null file & arch" used
to create an empty but valid target.
Also check in that case before logging (previously the logging would have
crashed.)
2021-01-26 12:17:39 -08:00
Raphael Isemann 48e09faa94 [lldb][NFC] Another attempt to fix GCC 5.x compilation
37510f69b4 tried to fix GCC 5.x compilation
by making the enum which is used as a unordered_map key unscoped. However it
seems that in GCC 5.x, enum keys are not supported *at all* in unordered_maps
(at least that's what some trial&error on godbolt tells me). This updates the
workaround to just use an int until GCC 5.x support is dropped.
2021-01-26 19:13:12 +01:00
Dave Lee 90b8ae016b [lldb] Remove unused ThreadPlanStack::GetStackOfKind (NFC)
This function isn't used.

Differential Revision: https://reviews.llvm.org/D95411
2021-01-26 09:22:25 -08:00
Richard Smith 8b11714885 Revert "Fix SBDebugger::CreateTargetWithFileAndArch to accept LLDB_ARCH_DEFAULT."
Also revert "Follow on to: f05dc40c31d1883b46b8bb60547087db2f4c03e3"

After these changes, multiple lldb tests are failing. Calls to
CreateTargetWithFileAndArch(None, None) appear to fail after these
changes.

This reverts commit f05dc40c31 and
1fba21778f.
2021-01-25 18:05:17 -08:00
Duncan P. N. Exon Smith 8b6aedc4c9 ExpressionParser: Migrate to FileEntryRef in ParseInternal, NFC
Migrate to the `FileEntryRef` overload of `SourceManager::createFileID`
(using `FileManager::getOptionalFileRef`) in
`ClangExpressionParser::ParseInternal`.

No functionality change here.

Differential Revision: https://reviews.llvm.org/D92957
2021-01-25 16:38:42 -08:00
Pedro Tammela 532e4203c5 [lldb/Lua] add support for Lua function breakpoint
Adds support for running a Lua function when a breakpoint is hit.

Example:
   breakpoint command add -s lua -F abc

The above runs the Lua function 'abc' passing 2 arguments. 'frame', 'bp_loc' and 'extra_args'.

A third parameter 'extra_args' is only present when there is structured data
declared in the command line.

Example:
   breakpoint command add -s lua -F abc -k foo -v bar

Differential Revision: https://reviews.llvm.org/D93649
2021-01-25 23:40:57 +00:00
Jim Ingham 1fba21778f Follow on to: f05dc40c31
When you pass in a bogus ArchSpec, TargetList.CreateTarget
makes a target with the arch of the executable.  That wasn't the
case with a bogus triple, so this change caused one of the bogus
input data tests to fail.  So check that the ArchSpec is valid
before passing it to CreateTarget.
2021-01-25 14:25:51 -08:00
Jim Ingham f05dc40c31 Fix SBDebugger::CreateTargetWithFileAndArch to accept LLDB_ARCH_DEFAULT.
The API docs in SBDebugger.i claim this should work but it doesn't.  This
should fix it.

Differential Revision: https://reviews.llvm.org/D95164
2021-01-25 12:53:37 -08:00
Walter Erquinigo 4bb6244871 [ThreadPlan] fix exec on Linux 2021-01-25 11:30:48 -08:00
Muhammad Omair Javaid 2fd4d923a8 [LLDB] Define AUXV_AT_HWCAP2 in AuxVector.h
This patch defines AUXV_AT_HWCAP2 for accessing Aux extensions.
2021-01-25 20:48:16 +05:00
Muhammad Omair Javaid b45020cf63 [LLDB] Remove leftovers and typos from RegisterInfos_arm64_sve.h
This patch removes a couple of left-overs and a typo from
RegisterInfos_arm64_sve.h and RegisterInfoPOSIX_arm64.h.
2021-01-25 20:48:15 +05:00
David Blaikie 78d41a1295 lldb: Add support for printing variables with DW_AT_ranges on DW_TAG_subprograms
Finishing out the support (to the best of my knowledge/based on current
testing running the whole check-lldb with a clang forcibly using
DW_AT_ranges on all DW_TAG_subprograms) for this feature.

Differential Revision: https://reviews.llvm.org/D94064
2021-01-24 18:39:06 -08:00
Augusto Noronha 2afaf072f5 Implement vAttachOrWait
Implements the required functions on gdb-remote so the '--include-existing' flag of process attach works correctly on Linux.

Reviewed By: labath, clayborg

Differential Revision: https://reviews.llvm.org/D94672
2021-01-24 21:30:09 +01:00
Jonas Devlieghere 3a50ed84f4 [lldb] FixFileSystem::GetExternalPath for VFS API change 2021-01-22 15:04:17 -08:00
Shafik Yaghmour dc057e87f6 [LLDB] Fix how ObjCBOOLSummaryProvider deals with BOOL
ObjCBOOLSummaryProvider was incorrectly treating BOOL as unsigned and this is now fixed.
Also adding tests for one bit bit-fields of BOOL and unsigned char.
2021-01-22 10:05:24 -08:00
Raphael Isemann 37510f69b4 [lldb][NFC] Fix build with GCC<6
GCC/libstdc++ before 6.1 can't handle scoped enums as unordered_map keys. LLVM
(and some build) bots officially support some GCC 5.x versions, so this patch
just makes the enum unscoped until we can require GCC 6.x.
2021-01-21 15:04:41 +01:00
Raphael Isemann 99b7b41edf [lldb][import-std-module] Do some basic file checks before trying to import a module
Currently when LLDB has enough data in the debug information to import the `std` module,
it will just try to import it. However when debugging libraries where the sources aren't
available anymore, importing the module will generate a confusing diagnostic that
the module couldn't be built.

For the fallback mode (where we retry failed expressions with the loaded module), this
will cause the second expression to fail with a module built error instead of the
actual parsing issue in the user expression.

This patch adds checks that ensures that we at least have any source files in the found
include paths before we try to import the module. This prevents the module from being
loaded in the situation described above which means we don't emit the bogus 'can't
import module' diagnostic and also don't waste any time retrying the expression in the
fallback mode.

For the unit tests I did some refactoring as they now require a VFS with the files in it
and not just the paths. The Python test just builds a binary with a fake C++ module,
then deletes the module before debugging.

Fixes rdar://73264458

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D95096
2021-01-21 12:32:51 +01:00
Jonas Devlieghere baf6c2987e [lldb] Upstream eCore_arm_arm64e enum value in ArchSpec
Upstream the eCore_arm_arm64e enum value in ArchSpec. All the other
arm64e triple changes already landed in LLVM.

Differential revision: https://reviews.llvm.org/D95110
2021-01-20 19:39:47 -08:00
Jim Ingham bff389120f Fix a bug with setting breakpoints on C++11 inline initialization statements.
If they occurred before the constructor that used them, we would refuse to
set the breakpoint because we thought they were crossing function boundaries.

Differential Revision: https://reviews.llvm.org/D94846
2021-01-20 17:58:34 -08:00
Med Ismail Bennani 8fc9b6c2c5
[lldb/Commands] Align process launch --plugin with process attach (NFC)
Following `7169d3a315f4cdc19c4ab6b8f20c6f91b46ba9b8`, this patch updates
the short option for the plugin command option to (`-p` to `-P`) to
align with the `process attach` command options.

The long option remains the same since there are already the same for both
commands.

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-01-20 21:01:23 +01:00
Med Ismail Bennani 7169d3a315 [lldb/Commands] Refactor ProcessLaunchCommandOptions to use TableGen (NFC)
This patch refactors the current implementation of
`ProcessLaunchCommandOptions` to be generated by TableGen.

The patch also renames the class to `CommandOptionsProcessLaunch` to
align better with the rest of the codebase style and moves it to
separate files.

Differential Review: https://reviews.llvm.org/D95059

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2021-01-20 18:53:06 +01:00
Hans Wennborg 8ba442bc21 Revert "Following up on PR48517, fix handling of template arguments that refer"
Combined with 'da98651 - Revert "DR2064:
decltype(E) is only a dependent', this change (5a391d3) caused verifier
errors when building Chromium. See https://crbug.com/1168494#c1 for a
reproducer.

Additionally it reverts changes that were dependent on this one, see
below.

> Following up on PR48517, fix handling of template arguments that refer
> to dependent declarations.
>
> Treat an id-expression that names a local variable in a templated
> function as being instantiation-dependent.
>
> This addresses a language defect whereby a reference to a dependent
> declaration can be formed without any construct being value-dependent.
> Fixing that through value-dependence turns out to be problematic, so
> instead this patch takes the approach (proposed on the core reflector)
> of allowing the use of pointers or references to (but not values of)
> dependent declarations inside value-dependent expressions, and instead
> treating template arguments as dependent if they evaluate to a constant
> involving such dependent declarations.
>
> This ends up affecting a bunch of OpenMP tests, due to OpenMP
> imprecisely handling instantiation-dependent constructs, bailing out
> early instead of processing dependent constructs to the extent possible
> when handling the template.
>
> Previously committed as 8c1f2d15b8, and
> reverted because a dependency commit was reverted.

This reverts commit 5a391d38ac.

It also restores clang/test/SemaCXX/coroutines.cpp to its state before
da986511fb.

Revert "[c++20] P1907R1: Support for generalized non-type template arguments of scalar type."

> Previously committed as 9e08e51a20, and
> reverted because a dependency commit was reverted. This incorporates the
> following follow-on commits that were also reverted:
>
> 7e84aa1b81 by Simon Pilgrim
> ed13d8c667 by me
> 95c7b6cadb by Sam McCall
> 430d5d8429 by Dave Zarzycki

This reverts commit 4b574008ae.

Revert "[msabi] Mangle a template argument referring to array-to-pointer decay"

> [msabi] Mangle a template argument referring to array-to-pointer decay
> applied to an array the same as the array itself.
>
> This follows MS ABI, and corrects a regression from the implementation
> of generalized non-type template parameters, where we "forgot" how to
> mangle this case.

This reverts commit 18e093faf7.
2021-01-20 15:55:35 +01:00
Muhammad Omair Javaid e448ad787e [LLDB] Add support to resize SVE registers at run-time
This patch builds on previously submitted SVE patches regarding expedited
register set and per thread register infos. (D82853 D82855 and D82857)

We need to resize SVE register based on value received in expedited list.
Also we need to resize SVE registers when we write vg register using
register write vg command. The resize will result in a updated offset
for all of fpr and sve register set. This offset will be configured
in native register context by RegisterInfoInterface and will also be
be updated on client side in GDBRemoteRegisterContext.

A follow up patch will provide a API test to verify this change.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D82863
2021-01-19 15:01:32 +05:00
Richard Smith 4b574008ae [c++20] P1907R1: Support for generalized non-type template arguments of scalar type.
Previously committed as 9e08e51a20, and
reverted because a dependency commit was reverted. This incorporates the
following follow-on commits that were also reverted:

7e84aa1b81 by Simon Pilgrim
ed13d8c667 by me
95c7b6cadb by Sam McCall
430d5d8429 by Dave Zarzycki
2021-01-18 21:05:01 -08:00
Muhammad Omair Javaid b9993fcbf5 DynamicRegisterInfo calculate offsets in separate function
This patch pull offset calculation logic out of DynamicRegisterInfo::Finalize
into a separate function. We are going to call this function whenever we
update SVE register sizes.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D94008
2021-01-15 16:21:18 +05:00
Muhammad Omair Javaid 4fd77668b2 [LLDB] Add per-thread register infos shared pointer in gdb-remote
In gdb-remote process we have register infos defind as a refernce object of
GDBRemoteDynamicRegisterInfo class. In past register infos have remained
constant througout the life time of a process.

This has changed after AArch64 SVE support where register infos will have
per-thread configuration. SVE registers will have per-thread size and can
be updated while running. This patch aims to build up for that support by
changing GDBRemoteDynamicRegisterInfo reference to a shared pointer deinfed
per-thread.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D82857
2021-01-15 16:11:17 +05:00
Joseph Tremoulet 85dfcaadc5 [LLDB] MinidumpParser: Prefer executable module even at higher address
When a program maps one of its own modules for reading, and then
crashes, breakpad can emit two entries for that module in the
ModuleList.  We have logic to identify this case by checking permissions
on mapped memory regions and report just the module with an executable
region.  As currently written, though, the check is asymmetric -- the
entry with the executable region must be the second one encountered for
the preference to kick in.

This change makes the logic symmetric, so that the first-encountered
module will similarly be preferred if it has an executable region but
the second-encountered module does not.  This happens for example when
the module in question is the executable itself, which breakpad likes to
report first -- we need to ignore the other entry for that module when
we see it later, even though it may be mapped at a lower virtual
address.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D94629
2021-01-14 13:17:57 -05:00
Pavel Labath 4b284b9ca8 [lldb] Fix TestPlatformProcessConnect.py
The test was marked as remote-only, which means it was run ~never, and
accumulated various problems. This commit modifies the test to run
locally and includes a couple of other fixes necessary to make it run:
- moves the "invoke" method into the "Base" test class
- adds []'s around the IP address in a couple more places to make things
  work with IPv6

The test is now marked as skipped when running the remote test suite. It
would be possible to make it run both locally and remotely, but this
would require writing a lot special logic for the remote case, and that
is not worth it.
2021-01-14 09:49:19 +01:00
Augusto Noronha 2bbf724fee Implement vAttachWait in lldb-server
This commit vAttachWait in lldb-server, so --waitfor can be used on
Linux

Reviewed By: labath, clayborg

Differential Revision: https://reviews.llvm.org/D93895
2021-01-14 09:25:15 +01:00
Philip Pfaffe 7ad54d1938 [lldb][wasm] Parse DWO section names
Mirror ELF section parsing to support DWARF section names for
debug fission.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D93621
2021-01-14 08:45:02 +01:00
Pavel Labath 13dea030b3 [lldb] Fix some bugs in the Pipe class and add tests
- s/createUniqueFile/createUniquePath -- we don't want to create the file,
  just the file name
- s/data()/str().c_str()/ -- paths given to system apis must be
  null-terminated
2021-01-10 21:59:16 +01:00
Adrian Prantl aa1943a2d1 Don't take the address of a temporary 2021-01-08 13:24:07 -08:00
Raphael Isemann b0dc54e08a [lldb][NFC] Refactor setup code for Clang diagnostics 2021-01-08 14:26:04 +01:00
Jonas Devlieghere 57e0cd3562 [lldb] Make DoReadMemory a protected method.
DoReadMemory is LLDB's internal implementation and shouldn't be called
directly.

Differential revision: https://reviews.llvm.org/D94284
2021-01-07 21:06:36 -08: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
Luís Marques 15f5971150 [LLDB][RISCV] Add RISC-V ArchSpec and rv32/rv64 variant detection
Adds the RISC-V ArchSpec bits contributed by @simoncook as part of D62732,
plus logic to distinguish between riscv32 and riscv64 based on ELF class.

The patch follows the implementation approach previously used for MIPS.
It defines RISC-V architecture subtypes and inspects the ELF header,
namely the ELF class, to detect the right subtype.

Differential Revision: https://reviews.llvm.org/D86292
2021-01-07 23:02:55 +00:00
David Blaikie 274afac9a1 lldb: Add support for DW_AT_ranges on DW_TAG_subprograms
gcc already produces debug info with this form
-freorder-block-and-partition
clang produces this sort of thing with -fbasic-block-sections and with a
coming-soon tweak to use ranges in DWARFv5 where they can allow greater
reuse of debug_addr than the low/high_pc forms.

This fixes the case of breaking on a function name, but leaves broken
printing a variable - a follow-up commit will add that and improve the
test case to match.

Differential Revision: https://reviews.llvm.org/D94063
2021-01-07 14:28:03 -08:00
David Spickett 801c7866e6 [lldb][ARM/AArch64] Update disasm flags to latest v8.7a ISA
Add optional memory tagging extension on AArch64.

Use isAArch64() instead of listing the AArch64 triples,
which fixes us not recognising aarch64_be.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D94084
2021-01-07 10:51:47 +00:00
Pedro Tammela d853bd7a4e [lldb/Lua] add support for multiline scripted breakpoints
1 - Partial Statements

The interpreter loop runs every line it receives, so partial
Lua statements are not being handled properly. This is a problem for
multiline breakpoint scripts since the interpreter loop, for this
particular case, is just an abstraction to a partially parsed function
body declaration.

This patch addresses this issue and as a side effect improves the
general Lua interpreter loop as well. It's now possible to write partial
statements in the 'script' command.

Example:
   (lldb) script
   >>>   do
   ..>   local a = 123
   ..>   print(a)
   ..>   end
   123

The technique implemented is the same as the one employed by Lua's own REPL implementation.
Partial statements always errors out with the '<eof>' tag in the error
message.

2 - CheckSyntax in Lua.h

In order to support (1), we need an API for just checking the syntax of string buffers.

3 - Multiline scripted breakpoints

Finally, with all the base features implemented this feature is
straightforward. The interpreter loop behaves exactly the same, the
difference is that it will aggregate all Lua statements into the body of
the breakpoint function. An explicit 'quit' statement is needed to exit the
interpreter loop.

Example:
   (lldb) breakpoint command add -s lua
   Enter your Lua command(s). Type 'quit' to end.
   The commands are compiled as the body of the following Lua function
   function (frame, bp_loc, ...) end
   ..> print(456)
   ..> a = 123
   ..> quit

Differential Revision: https://reviews.llvm.org/D93481
2021-01-07 00:31:36 +00:00
Jonas Devlieghere 6d94eeadd2 [lldb] Ad os_signpost support to lldb_private::Timer
Emit os_signposts when supported from LLDB's timer class. A vast amount
of performance sensitive places in LLDB are already instrumented with
the Timer class.

By emitting signposts we can examine this information in Instruments. I
recommend looking at Daniel's differential for why this is so powerful:
https://reviews.llvm.org/D52954.

Differential revision: https://reviews.llvm.org/D93657
2021-01-06 15:16:09 -08:00
Jorge Gorbe Moya a39b19821b Make DWARFUnit use the dwo_id from the DWARF5 CU header.
In split DWARF v5 files, the DWO id is no longer in the DW_AT_GNU_dwo_id
attribute. It's in the CU header instead. This change makes lldb look in
both places.

Differential Revision: https://reviews.llvm.org/D93444
2021-01-05 16:40:37 -08:00
Jonas Devlieghere c82beaba31 [lldb] Add timers to Reproducer::Keep and Reproducer::Discard 2021-01-05 09:54:31 -08:00
Michał Górny d5317b41c5 [Process/NetBSD] Copy changes from FreeBSDRemote and reformat
Copy changes, including:

- NativeProcessNetBSD::GetLoadedModuleFileSpec()
  and NativeProcessNetBSD::GetFileLoadAddress() methods

- split x86 register sets by CPU extensions

- use offset/size-based register reading/writing

Differential Revision: https://reviews.llvm.org/D93541
2021-01-02 19:15:12 +01:00
Peter Collingbourne 7e5a187de3 CrashReason: Add MTE tag check faults to the list of crash reasons.
As of Linux 5.10, the kernel may report either of the two following
crash reasons:
- SEGV_MTEAERR: async MTE tag check fault
- SEGV_MTESERR: sync MTE tag check fault

Teach LLDB about them.

Differential Revision: https://reviews.llvm.org/D93495
2020-12-29 14:36:50 -08:00
Jonas Devlieghere d97e9f1a3d [lldb] Simplify ObjectFile::FindPlugin (NFC)
Use early return to reduce the levels of indentation. Extract logic to
find object in container into helper function.
2020-12-23 14:06:40 -08:00
Jonas Devlieghere a9448872fe [lldb] Refactor and simplify GetCommandSPExact interface
GetCommandSPExact is called exaclty once with include_aliases set to
true, so make it a default argument. Use early returns to simplify the
implementation.
2020-12-23 10:43:13 -08:00
Jonas Devlieghere fcf9479f7d [lldb] Don't instrument demangling.
Don't instrument demangling calls. These functions are very hot and
instrumenting them quickly results in too much data to be useful.
2020-12-23 10:43:13 -08:00
Arthur Eubanks 6283d2aa51 Revert "[LLDB] Unbreak the build after recent clang changes"
This reverts commit 430d5d8429.

Depends on a reverted change.
2020-12-22 10:34:04 -08:00
Andy Yankovsky 1432ae57bf [lldb] Add SBType::GetEnumerationIntegerType method
Add a method for getting the enumeration underlying type.

Differential revision: https://reviews.llvm.org/D93696
2020-12-22 10:08:22 -08:00
Andy Yankovsky e17a00fc87 [lldb] Add SBType::IsScopedEnumerationType method
Add a method to check if the type is a scoped enumeration (i.e. "enum
class/struct").

Differential revision: https://reviews.llvm.org/D93690
2020-12-22 10:08:21 -08:00
Jonas Devlieghere 5c1c8443eb [lldb] Abstract scoped timer logic behind LLDB_SCOPED_TIMER (NFC)
This patch introduces a LLDB_SCOPED_TIMER macro to hide the needlessly
repetitive creation of scoped timers in LLDB. It's similar to the
LLDB_LOG(F) macro.

Differential revision: https://reviews.llvm.org/D93663
2020-12-22 09:10:27 -08:00
Michał Górny bd2e83333e [lldb] [Process/FreeBSDRemote] Remove anonymous namespace 2020-12-21 22:26:54 +01:00
Pavel Labath 3f3ab03ab7 [lldb] Remove anonymous namespace from NativeRegisterContextLinux_x86_64
Use "static" instead.
2020-12-21 20:39:05 +01:00
Jonas Devlieghere a913a583f0 [lldb] Simplify the is_finalized logic in process and make it thread safe.
This is a speculative fix when looking at the finalization code in
Process. It tackles the following issues:

 - Adds synchronization to prevent races between threads.
 - Marks the process as finalized/invalid as soon as Finalize is called
   rather than at the end.
 - Simplifies the code by using only a single instance variable to track
   finalization.

Differential revision: https://reviews.llvm.org/D93479
2020-12-18 18:41:33 -08:00
David Zarzycki 430d5d8429 [LLDB] Unbreak the build after recent clang changes
9e08e51a20 introduced a new enum case.
2020-12-18 07:54:36 -05:00
Michał Górny 835f8de850 [lldb] [Process/FreeBSDRemote] Use RegSetKind consistently [NFC]
Use RegSetKind enum for register sets everything, rather than int.
Always spell it as 'RegSetKind', without unnecessary 'enum'.  Add
missing switch case.  While at it, use uint32_t for regnums
consistently.

Differential Revision: https://reviews.llvm.org/D93450
2020-12-17 18:01:46 +01:00
Michał Górny 9ead4e7b4a [lldb] [Process/FreeBSDRemote] Replace GetRegisterSetCount()
Replace the wrong code in GetRegisterSetCount() with a constant return.
The original code passed register index in place of register set index,
effectively getting always true.  Correcting the code to check for
register set existence is not possible as LLDB supports only eliminating
last register sets.  Just return the full number for now which should
be NFC.

Differential Revision: https://reviews.llvm.org/D93396
2020-12-17 18:01:14 +01:00
Pavel Labath 122a4ebde3 Revert "[lldb] Make CommandInterpreter's execution context the same as debugger's one."
This reverts commit a01b26fb51, because it
breaks the "finish" command in some way -- the command does not
terminate after it steps out, but continues running the target. The
exact blast radius is not clear, but it at least affects the usage of
the "finish" command in TestGuiBasicDebug.py. The error is *not*
gui-related, as the same issue can be reproduced by running the same
steps outside of the gui.

There is some kind of a race going on, as the test fails only 20% of the
time on the buildbot.
2020-12-17 17:47:53 +01:00
Raphael Isemann b8338983e6 [lldb] Add std::array to the supported template list of the CxxModuleHandler
Identical to the other patches that add STL containers to the supported
templated list.
2020-12-17 11:47:58 +01:00
Raphael Isemann 722247c812 [lldb] Unify the two CreateTypedef implementations in TypeSystemClang
To get LLDB one step closer to fulfil the software redundancy requirements of
modern aircrafts, we apparently decided to have two separately maintained
implementations of `CreateTypedef` in TypeSystemClang. Let's pass on the idea of
an LLDB-powered jetliner and deleted one implementation.

On a more serious note: This function got duplicated a long time ago when the
idea of CompilerType with a backing TypeSystemClang subclass happened
(56939cb310). One implementation was supposed to
be called from CompilerType::CreateTypedef and the other has just always been
around to create typedefs. By accident one of the implementations is only used
by the PDB parser while the CompilerType::CreateTypedef backend is used by the
rest of LLDB.

We also had some patches over the year that only fixed one of the two functions
(D18099 for example only fixed up the CompilerType::CreateTypedef
implementation). D51162 and D86140 both fixed the same missing `addDecl` call
for one of the two implementations.

This patch:
* deletes the `CreateTypedefType` function as its only used by the PDB parser
  and the `CreateTypedef` implementation is anyway needed as it's the backend
  implementation of CompilerType.
* replaces the calls in the PDB parser by just calling the CompilerType wrapper.
* moves the documentation to the remaining function.
* moves the check for empty typedef names that was only in the deleted
  implementation to the other (I don't think this fixes anything as I believe
  all callers are already doing the same check).

I'll fix up the usual stuff (not using StringRef, not doing early exit) in a NFC
follow-up.

This patch is not NFC as the PDB parser now calls the function that has the fix
from D18099.

Reviewed By: labath, JDevlieghere

Differential Revision: https://reviews.llvm.org/D93382
2020-12-17 10:49:26 +01:00
Michał Górny dbfdb139f7 [lldb] [POSIX-DYLD] Update the cached exe path after attach
Fix the POSIX-DYLD plugin to update the cached executable path after
attaching.  Previously, the path was cached in DYLDRendezvous
constructor and not updated afterwards.  This meant that if LLDB was
attaching to a process (e.g. via connecting to lldb-server), the code
stored the empty path before DidAttach() resolved it.  The fix updates
the cached path in DidAttach().

This fixes a new instance of https://llvm.org/pr17880

Differential Revision: https://reviews.llvm.org/D92264
2020-12-17 09:31:22 +01:00
Michał Górny 8666b9057f [lldb] [POSIX-DYLD] Add libraries from initial rendezvous brkpt hit
Explicitly consider the libraries reported on the initial rendezvous
breakpoint hit added.  This is necessary on FreeBSD since the dynamic
loader issues only a single 'consistent' state rendezvous breakpoint hit
for all the libraries present in DT_NEEDED.  It is also helpful on Linux
where it ensures that ld-linux is considered loaded as well
as the shared system libraries reported afterwards.

Reenable memory maps on FreeBSD since this fixed the issue triggered
by them.

Differential Revision: https://reviews.llvm.org/D92187
2020-12-17 09:31:10 +01:00
Fangrui Song c70f36865e Use basic_string::find(char) instead of basic_string::find(const char *s, size_type pos=0)
Many (StringRef) cannot be detected by clang-tidy performance-faster-string-find.
2020-12-16 23:28:32 -08:00
Jordan Rupprecht 869f8363c4 [lldb][NFC] Apply performance-faster-string-find (`str.find("X")` -> `str.find('x')`) 2020-12-16 10:53:18 -08:00