Commit Graph

14178 Commits

Author SHA1 Message Date
Muhammad Omair Javaid b69c09bf43 Support custom expedited register set in gdb-remote
This patch adds capability to introduce a custom expedited register set
in gdb remote. Currently we send register set 0 as expedited register set
but for the case of AArch64 SVE we intend to send additional information
about SVE registers size/offset configuration which can be calculated
from vg register. Therefore we will expedited Vg register in case of
AArch64 is in SVE mode to speedup register configuration calculations.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D82853
2020-11-30 17:34:19 +05:00
David Spickett a7f8d96b16 [lldb] Use llvm::Optional for port in LaunchGDBServer
Previously we used UINT16_MAX to mean no port/no specifc
port. This leads to confusion because 65535 is a valid
port number.

Instead use an optional. If you want a specific port call
LaunchGDBServer as normal, otherwise pass an empty optional
and it will be set to the port that gets chosen.
(or left empty in the case where we fail to find a port)

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D92035
2020-11-30 11:20:39 +00:00
David Spickett 98e87f76d0 [lldb] Error when there are no ports to launch a gdbserver on
Previously if you did:
$ lldb-server platform --server <...> --min-gdbserver-port 12346
--max-gdbserver-port 12347
(meaning only use port 12346 for gdbservers)

Then tried to launch two gdbservers on the same connection,
the second one would return port 65535. Which is a real port
number but it actually means lldb-server didn't find one it was
allowed to use.

send packet: $qLaunchGDBServer;<...>
read packet: $pid:1919;port:12346;#c0
<...>
send packet: $qLaunchGDBServer;<...>
read packet: $pid:1927;port:65535;#c7

This situation should be an error even if port 65535 does happen
to be available on the current machine.

To fix this make PortMap it's own class within
GDBRemoteCommunicationServerPlatform.

This almost the same as the old typedef but for
GetNextAvailablePort() returning an llvm::Expected.
This means we have to handle not finding a port,
by returning an error packet.

Also add unit tests for this new PortMap class.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D91634
2020-11-30 10:19:14 +00:00
Richard Smith 3fb0879867 Refactor and simplify class scope name lookup.
This is partly in preparation for an upcoming change that can change the
order in which DeclContext lookup results are presented.

In passing, fix some obvious errors where name lookup's notion of a
"static member function" missed static member function templates, and
where its notion of "same set of declarations" was confused by the same
declarations appearing in a different order.
2020-11-25 16:25:33 -08:00
Muhammad Omair Javaid 2bd4540f38 [LLDB] Fix typo in RegisterContextPOSIXProcessMonitor_arm64
This patch fixes a minor typo in RegisterContextPOSIXProcessMonitor_arm64
constructor where memset target was wrongly specified as m_fpr instead of
m_gpr_arm64.
2020-11-24 07:09:00 +05:00
Michał Górny 18e4272a4f [lldb] Prevent 'process connect' from using local-only plugins
Add a 'can_connect' parameter to Process plugin initialization, and use
it to filter plugins to these capable of remote connections.  This is
used to prevent 'process connect' from picking up a plugin that can only
be used locally, e.g. the legacy FreeBSD plugin.

Differential Revision: https://reviews.llvm.org/D91810
2020-11-23 09:48:55 +01:00
Michał Górny 8018e7b447 [lldb] [Process/FreeBSDRemote] Fix regset names and related tests
Restore Linux-alike regset names for AVX/MPX registers
as TestLldbGdbServer seems to depend on them.  At the same time, fix
TestRegisters to be aware that they are not available on FreeBSD
and NetBSD, at least until we figure out a better way of reporting
unsupported register sets.

Differential Revision: https://reviews.llvm.org/D91923
2020-11-23 09:28:20 +01:00
Michał Górny 8f2f9a82e2 [lldb] [Process/Utility] Declare register overlaps between ST and MM
Explicitly declare register overlaps/invalidation between ST(i) and MMi
registers.

Differential Revision: https://reviews.llvm.org/D91728
2020-11-23 09:23:14 +01:00
Michał Górny 7b7c372e3f [lldb] [Process/FreeBSD] Add missing 'override' kws to POSIXStopInfo
Differential Revision: https://reviews.llvm.org/D91934
2020-11-23 09:22:41 +01:00
Michał Górny 8aea95f3cb [lldb] Reland "Use translated full ftag values"
Translate between abridged and full ftag values in order to expose
the latter in the gdb-remote protocol while the former are used by
FXSAVE/XSAVE...  This matches the gdb behavior.

The Shell/Register tests now rely on the new behavior, and therefore
are run on non-Darwin systems only.  The Python (API) test relies
on the legacy behavior, and is run on Darwin only.

Differential Revision: https://reviews.llvm.org/D91504
2020-11-21 17:11:38 +01:00
Nathan Lanza 33c79f76af Revert "[lldb] add a missing dependency on intrinsics_gen"
This reverts commit 137ff73317.

This belongs in Apple's Swift fork since this is a direct fix for
unified Swift + llvm + lldb builds.
2020-11-20 16:02:16 -05:00
Dave Lee dbcc69217a [lldb] Add examples and reword source-map help string
Update the help string for `target.source-map` to remove the use of the word
"duple" and to add examples. Additionally I rewrote parts with the goal of
making the description more concrete.

rdar://68736012

Differential Revision: https://reviews.llvm.org/D91742
2020-11-20 10:01:36 -08:00
Raphael Isemann ffb3fd8f18 Partially revert '[MachO] Update embedded part of ObjectFileMachO for Mangled API change'
Commit f3aa9e36d9 fixed the embedded OS
build by removing all passed args for `GetName`/`GetDemangledName`. The motivation
for this was that these arguments were apparently removed in
commit 22b044877d. However, only `GetName`'s language
argument was removed but the mangling preference argument was *not* removed
(and unfortunately had a default argument). So when that commit removed all
the args it didn't just fix the build but it also changed all the mangling
preferences to 'demangled' for all `GetName` calls.

Also some `GetName` calls were outside the TARGET_OS_EMBEDDED ifdef, so
this change ended up breaking the following tests on macOS:

  lldb-api :: lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py
  lldb-api :: lang/objc/objc-super/TestObjCSuper.py

From what I can see f3aa9e36d9 removed 12 ePreferMangled args and this patch
re-adds 12 args with roughly the same line numbers, so this *should* restore the
old behaviour and also keep the embedded build working. On the other hand,
ObjectFileMachO::ParseSymtab is a very successful attempt at writing
the longest possible function within LLVM, so this fix is partly based
on the engineering principle known as "hoping for the best".
2020-11-20 13:31:36 +01:00
David Spickett 32541685b2 [lldb][AArch64/Linux] Show memory tagged memory regions
This extends the "memory region" command to
show tagged regions on AArch64 Linux when the MTE
extension is enabled.

(lldb) memory region the_page
[0x0000fffff7ff8000-0x0000fffff7ff9000) rw-
memory tagging: enabled

This is done by adding an optional "flags" field to
the qMemoryRegion packet. The only supported flag is
"mt" but this can be extended.

This "mt" flag is read from /proc/{pid}/smaps on Linux,
other platforms will leave out the "flags" field.

Where this "mt" flag is received "memory region" will
show that it is enabled. If it is not or the target
doesn't support memory tagging, the line is not shown.
(since majority of the time tagging will not be enabled)

Testing is added for the existing /proc/{pid}/maps
parsing and the new smaps parsing.
Minidump parsing has been updated where needed,
though it only uses maps not smaps.

Target specific tests can be run with QEMU and I have
added MTE flags to the existing helper scripts.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D87442
2020-11-20 11:21:59 +00:00
Raphael Isemann 47b7138b48 [lldb] Fix incorrect error handling in GDBRemoteCommunicationClient::SendGetSupportedTraceType
GDBRemoteCommunicationClient::SendGetSupportedTraceType is checking whether the
response is `!response.IsNormalResponse()` and infers from that that it is an error response.
However, it could be either "unsupported" or "error". If we get an unsupported response,
the code then tries to generate an llvm::Expected from the non-error response which then asserts.

Debugserver doesn't implement `jLLDBTraceSupportedType`, so we get an unsupported response
whenever this function is called on macOS.

This fixes the TestAproposWithProcess on macOS (where the `apropos` command will query
the CommandObjectTraceStart which then sends the trace type query package).

Reviewed By: wallace, shafik

Differential Revision: https://reviews.llvm.org/D91801
2020-11-19 19:14:04 +01:00
Raphael Isemann b7a09de10f [lldb][NFC] Add a FIXME for ClangASTSource::FindExternalLexicalDecls's unused 'decls' parameter 2020-11-19 17:15:14 +01:00
Mikhail Goncharov 193a9b374e Revert "[lldb] Use translated full ftag values"
This reverts commit c43abf0436.

Test commands/register/register/register_command/TestRegisters.py fails.
Buildbot http://lab.llvm.org:8011/#/changes/4149
2020-11-19 15:24:59 +01:00
Michał Górny c43abf0436 [lldb] Use translated full ftag values
Translate between abridged and full ftag values in order to expose
the latter in the gdb-remote protocol while the former are used by
FXSAVE/XSAVE...  This matches the gdb behavior.

Differential Revision: https://reviews.llvm.org/D91504
2020-11-19 13:23:12 +01:00
Michał Górny d8ff269f67 [lldb] Add explicit 64-bit fip/fdp registers on x86_64
The FXSAVE/XSAVE data can have two different layouts on x86_64.  When
called as FXSAVE/XSAVE..., the Instruction Pointer and Address Pointer
registers are reported using a 16-bit segment identifier and a 32-bit
offset.  When called as FXSAVE64/XSAVE64..., they are reported using
a complete 64-bit offsets instead.

LLDB has historically followed GDB and unconditionally used to assume
the 32-bit layout, with the slight modification of possibly
using a 32-bit segment register (i.e. extending the register into
the reserved 16 upper bits).  When the underlying operating system used
FXSAVE64/XSAVE64..., the pointer was split into two halves,
with the upper half repored as the segment registers.  While
reconstructing the full address was possible on the user end (and e.g.
the FPU register tests did that), it certainly was not the most
convenient option.

Introduce a two additional 'fip' and 'fdp' registers that overlap
with 'fiseg'/'fioff' and 'foseg'/'foff' respectively, and report
the complete 64-bit address.

Differential Revision: https://reviews.llvm.org/D91497
2020-11-19 13:23:12 +01:00
Walter Erquinigo fb19f11ef4 [trace][intel-pt] Scaffold the 'thread trace start | stop' commands
Depends on D90490.

The stop command is simple and invokes the new method Trace::StopTracingThread(thread).

On the other hand, the start command works by delegating its implementation to a CommandObject provided by the Trace plugin. This is necessary because each trace plugin needs different options for this command. There's even the chance that a Trace plugin can't support live tracing, but instead supports offline decoding and analysis, which means that "thread trace dump instructions" works but "thread trace start" doest. Because of this and a few other reasons, it's better to have each plugin provide this implementation.

Besides, I'm using the GetSupportedTraceType method introduced in D90490 to quickly infer what's the trace plug-in that works for the current process.

As an implementation note, I moved CommandObjectIterateOverThreads to its header so that I can use it from the IntelPT plugin. Besides, the actual start and stop logic for intel-pt is not part of this diff.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D90729
2020-11-18 18:24:36 -08:00
Jonas Devlieghere f3aa9e36d9 [MachO] Update embedded part of ObjectFileMachO for Mangled API change
Mangled::GetName and Mangled::GetDemangledName no longer take any
arguments.
2020-11-18 14:47:31 -08:00
Raphael Isemann ccd9091d4a [lldb][NFC] Don't let Process inherit from UserID
I noticed that Process is inheriting from UserID to store its PID value. This patch
replaces this with a dedicated field in the Process class. This is NFC, but has some
small effects on the code using Process:
* `GetID()` now returns a `lldb::pid_t` like all other process code instead of `lldb::user_id_t`. Both are typedefs for `uint64_t`, so no change in behaviour.
* The equality operators defined for UserID no longer accept Process instances.
* Removes the inherited method `Process::Clear()` which didn't actually clear anything beside the PID value.

We maybe should also remove the getters/setters to `S/GetPID` or something like that. I can update all the code for that
in a follow-up NFC commit.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D91699
2020-11-18 14:33:48 +01:00
Muhammad Omair Javaid 661e4040ac [LLDB] Fix SVE reginfo for sequential offset in g packet
This moves in the direction of our effort to synchronize register descriptions
between LLDB and GDB xml description. We want to able to send registers in a
way that their offset fields can be re-constructed based on register sizes
in the increasing order of register number.

In context to Arm64 SVE, FPCR and FPSR are same registers in FPU regset and
SVE regset. Previously FPSR/FPCR offset was set at the end of SVE data
because Linux ptrace data placed FPCR and FPSR at the end of SVE register set.

Considering interoperability with other stubs like QEMU and that g packets
should generate register data in increasing order of register numbers. We
have to move FPCR/FPSR offset up to its original location according to
register numbering scheme of ARM64 registers with SVE registers included.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D90741
2020-11-17 17:18:34 +05:00
Muhammad Omair Javaid fcca6fe93f [LLDB] Update SVE Z reg info to remove invalidate regs
In our recent discussion we are aiming to make LLDB registers exchange minimum
possible information in qRegisterInfo or XMl register descriptions.
For SVE registers, Z registers are catagorized as primary registers and should
not have any infomration about any pseudo registers. All pseudo registers
should have the information on which primary register they belong to.
This patch removes invalidate_regs list from Z registers and will mitigate its
impact on SVE resize patch in a follow up update.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D91057
2020-11-17 17:14:44 +05:00
Aaron Ballman fa72ce346c Another speculative fix for lldb related to ConstexprSpecKind 2020-11-16 14:39:34 -05:00
Aaron Ballman 1941d9651c Speculatively fix the lldb build
Pick up the changes from 41b65f166b.
2020-11-16 14:23:04 -05:00
Raphael Isemann a8350ce79d [lldb] Add support for using variables with C++ keywords names in non-C++ expressions
LLDB is currently always activating C++ when parsing expressions as LLDB itself
is using C++ features when creating the final AST that will be codegen'd
(specifically, references to variables, namespaces and using declarations are
used).

This is causing problems for users that have variables in non-C++ programs (e.g.
plain C or Objective-C) that have names which are keywords in C++. Expressions
referencing those variables fail to parse as LLDB's Clang parser thinks those
identifiers are C++ keywords and not identifiers that may belong to a
declaration.

We can't just disable C++ in the expression parser for those situations as
replacing the functionality of the injected C++ code isn't trivial. So this
patch is just disabling most keywords that are exclusive to C++ in LLDB's Clang
parser when we are in a non-C++ expression. There are a few keywords we can't
disable for now:

* `using` as that's currently used in some situations to inject variables into the expression function.
* `__null` as that's used by LLDB to define `NULL`/`Nil`/`nil`.

Getting rid of these last two keywords is possible but is a large enough change
that this will be handled in follow up patches.

Note that this only changes the keyword status of those tokens but this patch
does not remove any C++ functionality from the expression parser. The type
system still follows C++ rules and so does the rest of the expression parser.

There is another small change that gives the hardcoded macro definitions in LLDB
a higher precedence than the macros imported from the Objective-C modules. The
reason for this is that the Objective-C modules in LLDB are actually parsed in
Objective-C++ mode and they end up providing the C++ definitions of certain
system macros (like `NULL` being defined as `nullptr`). So we have to move the
LLDB definition forward and surround the definition from the module with an
`#ifdef` to make sure that we use the correct LLDB definition that doesn't
reference C++ keywords. Or to give an example, this is how the expression source
code changes:

Before:
```
 #define NULL (nullptr) // injected module definition
 #ifndef NULL
 #define NULL (__null) // hardcoded LLDB definition
 #endif
```

After:
```
 #ifndef NULL
 #define NULL (__null) // hardcoded LLDB definition
 #endif
 #ifndef NULL
 #define NULL (nullptr) // injected module definition
 #endif
```

Fixes rdar://10356912

Reviewed By: shafik

Differential Revision: https://reviews.llvm.org/D82770
2020-11-16 16:04:44 +01:00
Michał Górny b9734c6b44 [lldb] [Process/FreeBSDRemote] Optimize regset pointer logic
Create a helper GetOffsetRegSetData() method to get pointer
to the regset data accounting for the necessary offset.  Establish
the offsets in the constructor and store them in the structure.  This
avoids having to add new Get*Offset() methods and combines some common
code.

Differential Revision: https://reviews.llvm.org/D91411
2020-11-16 13:03:02 +01:00
Michał Górny 68ca01eb50 [lldb] [Process/FreeBSDRemote] Modernize and simplify YMM logic
Eliminate the remaining swith-case code for register getters,
and migrate YMM registers to regset-oriented model.  Since these
registers are recombined from XMM and YMM_Hi128 XSAVE blocks, while LLDB
gdb-server protocol transmits YMM registers whole, the offset-based
model will not work here.  Nevertheless, some improvement was possible.

Replace generic 'XSaveRegSet' along with sub-sets for XSAVE components
with 'YMMRegSet' (and more regsets in the future as further components
are implemented).  Create a helper GetYMMSplitReg() method that obtains
pointers to the appropriate XMM and YMM_Hi128 blocks to reduce code
duplication.

Differential Revision: https://reviews.llvm.org/D91293
2020-11-16 13:03:01 +01:00
Michał Górny 6adb55877c [lldb] [Process/FreeBSDRemote] Access debug registers via offsets
Use offset-based method to access x86 debug registers.  This also
involves adding a test for the correctness of these offsets, and making
GetDR() method of NativeRegisterContextWatchpoint_x86 public to avoid
duplicate code.

Differential Revision: https://reviews.llvm.org/D91268
2020-11-16 13:03:01 +01:00
Michał Górny e520487bf4 [lldb] [Process/FreeBSDRemote] Access FPR via RegisterInfo offsets
Use offset-based method to access base x87 FPU registers, using offsets
relative to the position of 'struct FPR', as determined by the location
of first register in it (fctrl).  Change m_fpr to use a fixed-size array
matching FXSAVE size (512 bytes).  Add unit tests for verifying
RegisterInfo offsets and sizes against the FXSAVE layout.

Differential Revision: https://reviews.llvm.org/D91248
2020-11-16 13:03:01 +01:00
Michał Górny 58abbf821c [lldb] [Process/FreeBSDRemote] Access GPR via reginfo offsets
Read and write registers from m_gpr using offsets from RegisterInfo
rather than explicit switch-case.  This eliminates a lot of redundant
code, and avoids mistakes such as type mismatches seen recently (wrt
segment registers).  The same logic will be extended to other register
sets in the future.

Make m_gpr an uint8_t std::array to ease accesses.  Ideally, we could
avoid including <machine/reg.h> entirely in the future and instead
get the correct GPR size from Utility/RegisterContextFreeBSD_* somehow.

While at it, modify register set logic to use an explicit enum with
llvm::Optional<>, making the code cleaner and at the same time enabling
compiler warnings for unhandled sets.

Since now we're fully relying on 'struct GPR' defined
in Utility/RegisterContextFreeBSD_* being entirely in sync with
the system structure, add unit tests to verify the field offsets
and sizes.

Differential Revision: https://reviews.llvm.org/D91216
2020-11-16 12:19:37 +01:00
Jonas Devlieghere 6c0cd5676e [lldb] Make `process connect` behave the same in sync and async mode.
I think the check for whether the process is connected is totally bogus
in the first place, but on the off-chance that's it's not, we should
behave the same in synchronous and asynchronous mode.
2020-11-13 17:39:30 -08:00
Jim Ingham 5a4b2e1541 The AssertRecognizer used the module from a frames SC without checking it was non-null.
I only have a crash report for this.  I could reproduce it with a slightly older
lldb by running an expression that called pthread_kill, but we started making modules
for our expression JIT code, so that no longer triggers the bug.  I can't think of another
good way to test it but the fix is obvious.
2020-11-13 11:41:32 -08:00
Jonas Devlieghere 406ad18748 [lldb/DataFormatters] Display null C++ pointers as nullptr
Display null pointer as `nullptr`, `nil` and `NULL` for C++,
Objective-C/Objective-C++ and C respectively. The original motivation
for this patch was to display a null std::string pointer as nullptr
instead of "", but the fix seemed generic enough to be done for all
summary providers.

Differential revision: https://reviews.llvm.org/D77153
2020-11-12 15:24:06 -08:00
shafik bae9aedb34 [LLDB] Fix handling of bit-fields in a union
When parsing DWARF and laying out bit-fields we don't properly take into account when they are in a union, they will all have a zero offset.

Differential Revision: https://reviews.llvm.org/D91118
2020-11-12 14:09:27 -08:00
Raphael Isemann b4b836563a [lldb][NFC] Move OptionDefinition from lldb-private-types.h to its own Utility header
Also moves the curious isprint8 function (which was used to check whether we have a
valid short option) into the struct and documents it.
2020-11-12 15:30:26 +01:00
Michał Górny a8bfee2a35 [lldb] [Process/Utility] Fix DR offsets for FreeBSD
Fix Debug Register offsets to be specified relatively to UserArea
on FreeBSD/amd64 and FreeBSD/i386, and add them to UserArea on i386.
This fixes overlapping GPRs and DRs in gdb-remote protocol, making it
impossible to correctly get and set debug registers from the LLDB
client.

Differential Revision: https://reviews.llvm.org/D91254
2020-11-12 14:09:03 +01:00
Raphael Isemann 1115d1d083 Revert "Generalize regex matching std::string variants to compensate for recent"
This reverts commit 856fd98a17. The type formatters
use inline namespaces to find the formatter that fits the type ABI, so they
can't just ignore the inline namespaces.

The failing tests should be fixed by da121fff11 .
2020-11-12 14:01:22 +01:00
Raphael Isemann da121fff11 [lldb] Introduce a LLDB printing policy for Clang type names that suppressed inline namespaces
Commit 5f12f4ff90 made suppressing inline namespaces
when printing typenames default to true. As we're using the inline namespaces
in LLDB to construct internal type names (which need internal namespaces in them
to, for example, differentiate libc++'s std::__1::string from the std::string
from libstdc++), this broke most of the type formatting logic.
2020-11-12 14:00:33 +01:00
Richard Smith 856fd98a17 Generalize regex matching std::string variants to compensate for recent
improvements to Clang's type printing.
2020-11-11 17:55:47 -08:00
Walter Erquinigo 21555fff4d [intel-pt][trace] Implement a "get supported trace type" packet
Depends on D89283.

The goal of this packet (jTraceGetSupportedType) is to be able to query the gdb-server for the tracing technology that can work for the current debuggeer, which can make the user experience simpler but allowing the user to simply type

  thread trace start

to start tracing the current thread without even telling the debugger to use "intel-pt", for example. Similarly, `thread trace start [args...]` would accept args beloging to the working trace type.

Also, if the user typed

  help thread trace start

We could directly show the help information of the trace type that is supported for the target, or mention instead that no tracing is supported, if that's the case.

I added some simple tests, besides, when I ran this on my machine with intel-pt support, I got

  $ process plugin packet send "jTraceSupportedType"
    packet: jTraceSupportedType
  response: {"description":"Intel Processor Trace","pluginName":"intel-pt"}

On a machine without intel-pt support, I got

  $ process plugin packet send "jTraceSupportedType"
    packet: jTraceSupportedType
  response: E00;

Reviewed By: clayborg, labath

Differential Revision: https://reviews.llvm.org/D90490
2020-11-11 10:35:58 -08:00
Vedant Kumar 04cd6c6217 [ThreadPlan] Delete unused ThreadPlanStepInRange code, NFC 2020-11-10 16:15:03 -08:00
Vedant Kumar ba21376883 [Command] Fix accidental word concatenation in Options.td
Split up words that appear to have been accidentally concatenated.

This looks to be exhaustive: to find these in vim, use:

/\v[^ ]"\n +"[^ ]
2020-11-10 16:13:39 -08:00
Michał Górny f21e704d4a [lldb] [Process/NetBSD] Copy the recent improvements from FreeBSD
Copy the recent improvements from the FreeBSDRemote plugin, notably:

- moving event reporting setup into SetupTrace() helper

- adding more debug info into SIGTRAP handling

- handling user-generated (and unknown) SIGTRAP events

- adding missing error handling to the generic signal handler

- fixing attaching to processes

- switching watchpoint helpers to use llvm::Error

- minor style and formatting changes

This fixes a number of tests, mostly related to fixed attaching.

Differential Revision: https://reviews.llvm.org/D91167
2020-11-10 20:20:44 +01:00
Jonas Devlieghere 8da14fb76c [lldb] Propagate llvm::Error to report_fatal_error
Instead of having a custom error message, propagate the llvm::Error from
SystemInitializerCommon. I didn't realize we had this overload until
Pavel mentioned it in D90987 today.
2020-11-10 08:19:47 -08:00
Pavel Labath 4edb7e34f8 [lldb/DWARF] Fix sizes of DW_OP_const[1248][us] and DW_OP_litN results
Dwarf says (Section 2.5.1.1. of DWARF v5) that these operations should
push "generic" (pointer-sized) values. This was not the case for
DW_OP_const operations (which were pushing values based on the size of
arguments), nor DW_OP_litN (which were always pushing 64-bit values).

The practical effect of this that were were unable to display the values
of variables if the size of the DW_OP_const opcode was smaller than the
value of the variable it was describing. This would happen because we
would store this (small) result into a buffer and then would not be able
to read sufficient data out of it (in Value::GetValueAsData). Gcc emits
debug info like this.

Other (more subtle) effects are also possible.

The same fix should be applied to DW_OP_const[us] (leb128 versions), but
I'm not doing that right now, because that would cause us to display
wrong (truncated) values of variables on 32-bit targets (pr48087).

Differential Revision: https://reviews.llvm.org/D90840
2020-11-10 16:10:08 +01:00
Michał Górny 4c54399b7e [lldb] [Process/FreeBSDRemote] Explicitly copy dbregs to new threads
Explicitly copy dbregs to new threads to ensure that watchpoints
are propagated properly.  Fixes the test failure due to apparent kernel
race between reporting a new thread and resuming main thread execution
that makes implicit inheritance of dbregs unreliable.  By copying them
explicitly, we ensure that the new thread correctly respects watchpoints
that were set after the thread was created but before it was reported.

The code is copied from the NetBSD plugin and modernized to use
llvm::Error.

Differential Revision: https://reviews.llvm.org/D91032
2020-11-10 14:18:03 +01:00
Michał Górny 194c5accb2 [lldb] [Process/FreeBSDRemote] Correct DS/ES/FS/GS register sizes
Fix DS/ES/FS/GS register sizes in getter/setter for FreeBSD.  Apparently
only CS and SS registers are specified as 64/32-bit in LLDB, while
the others are specified as 16-bit.  This fixes the failing
StandardStartupTest.TestStopReplyContainsThreadPcs lldb-server unittest.

Differential Revision: https://reviews.llvm.org/D91076
2020-11-10 14:18:03 +01:00
Michał Górny e637602e7a [lldb] [Process/FreeBSDRemote] Fix handling user-generated SIGTRAP
Update the SIGTRAP handler to account for the possibility of SIGTRAP
being generated by the user, i.e. not having any specific debugging
event associated with it, as well as receiving unknown SIGTRAPs.  These
instances of SIGTRAP are passed to the regular signal handler.

Differential Revision: https://reviews.llvm.org/D91007
2020-11-10 14:18:03 +01:00
Stefan Gränitz 203b4774b8 [lldb][ObjectFile] Relocate sections for in-memory objects (e.g. received via JITLoaderGDB)
Part 2 of a fix for JITed code debugging. This has been a regression from 5.0 to 6.0 and it's still reproducible on current master: https://bugs.llvm.org/show_bug.cgi?id=36209 Part 1 was D61611 a while ago.

The in-memory object files we obtain from JITLoaderGDB are not yet relocated. It looks like this used to happen on the LLDB side and my guess is that it broke with D38142. (However, it's hard to tell because the whole thing was broken already due to the bug in part 1.) The patch moved relocation resolution to a later point in time and didn't apply it to in-memory objects. I am not aware of any reason why we wouldn't resolve relocations per-se, so I made it unconditional here. On Debian, it fixes the bug for me and all tests in `check-lldb` are still fine.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D90769
2020-11-10 11:37:53 +01:00
Jonas Devlieghere b2fa3b922e [lldb] Make GetSelectedOrDummyTarget return the target by reference (NFC)
Return references from GetDummyTarget and GetSelectedOrDummyTarget. This
matches how the APIs are already used in practice.
2020-11-09 15:42:27 -08:00
Michał Górny ed3ac6c110 [lldb] [Process/NetBSD] Correct DS/ES/FS/GS register sizes
Fix DS/ES/FS/GS register sizes in getter/setter for NetBSD.  Apparently
only CS and SS registers are specified as 64/32-bit in LLDB, while
the others are specified as 16-bit.

Differential Revision: https://reviews.llvm.org/D91090
2020-11-09 22:14:58 +01:00
António Afonso d7be9a4647 Revert "Check if debug line sequences are starting after the first code segment"
This reverts commit 265a38fbc5.
2020-11-09 11:45:35 -08:00
António Afonso a9dcd15f50 Revert "Ignores functions that have a range starting outside of a code section"
This reverts commit df30bc0168.
2020-11-09 09:07:48 -08:00
Jonas Devlieghere b31d787949 [lldb] Avoid confusing reproducer crashes when initialization failed
During active replay, the ::Initialize call is replayed like any other
SB API call and the return value is ignored. Since we can't intercept
this, we terminate here before the uninitialized debugger inevitably
crashes.

Differential revision: https://reviews.llvm.org/D90987
2020-11-09 08:50:10 -08:00
António Afonso df30bc0168 Ignores functions that have a range starting outside of a code section
This is a similar patch to https://reviews.llvm.org/D87172. Greg said we should also do it for functions.

Reviewed By: clayborg, labath

Differential Revision: https://reviews.llvm.org/D87173
2020-11-09 08:26:08 -08:00
António Afonso 265a38fbc5 Check if debug line sequences are starting after the first code segment
I found a few cases where entries in the debug_line for a specific line of code have invalid entries (the address is outside of a code section or no section at all) and also valid entries. When this happens lldb might not set the breakpoint because the first line entry it will find in the line table might be the invalid one and since it's range is "invalid" no location is resolved. To get around this I changed the way we parse the line sequences to ignore those starting at an address under the first code segment.
Greg suggested to implement it this way so we don't need to check all sections for every line sequence.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D87172
2020-11-09 08:26:00 -08:00
Michał Górny bc125665c5 [lldb] [Host/freebsd] Set Arg0 for 'platform process list -v'
Same fix as in NetBSD (a6712889f5).

Differential Revision: https://reviews.llvm.org/D91026
2020-11-09 12:09:12 +01:00
Michał Górny 2384c4f971 Revert "[lldb] [Host/freebsd] Set Arg0 for 'platform process list -v'"
Accidentally referenced the wrong diff.

This reverts commit fce8e75889.
2020-11-09 12:09:12 +01:00
Michał Górny fce8e75889 [lldb] [Host/freebsd] Set Arg0 for 'platform process list -v'
Same fix as in NetBSD (a6712889f5).

Differential Revision: https://reviews.llvm.org/D91012
2020-11-09 11:35:11 +01:00
Michał Górny 9e1409aa1e [lldb] [Process/FreeBSDRemote] Handle exec() from inferior
Differential Revision: https://reviews.llvm.org/D90938
2020-11-09 11:35:11 +01:00
Jan Kratochvil 24f07531a3 [lldb] Fix DW_AT_decl_file from DW_AT_specification from a different CU
This would be reproducible in future DWZ category of the testsuite as:
  Failed Tests (1):
    lldb-api :: python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py

Differential Revision: https://reviews.llvm.org/D91014
2020-11-09 10:52:48 +01:00
Richard Howell 137ff73317 [lldb] add a missing dependency on intrinsics_gen
Sometimes builds will fail with errors like:

```
In file included from /build/external/llvm-project/lldb/source/Symbol/SwiftASTContext.cpp:52:
In file included from /build/external/swift/include/swift/IRGen/Linking.h:22:
In file included from /build/external/swift/include/swift/SIL/SILFunction.h:24:
In file included from /build/external/swift/include/swift/SIL/SILBasicBlock.h:23:
In file included from /build/external/swift/include/swift/SIL/SILInstruction.h:21:
In file included from /build/external/swift/include/swift/AST/Builtins.h:24:
**/build/external/llvm-project/llvm/include/llvm/IR/Attributes.h:74:14: fatal error: 'llvm/IR/Attributes.inc' file not found**
**^~~~~~~~~~~~~~~~~~~~~~~~**
```
This change ensures the `Attributes.inc` file is generated before building `SwiftASTContext.cpp`.

Differential Revision: https://reviews.llvm.org/D90857
2020-11-06 13:15:08 -05:00
Walter Erquinigo cfd96f057b [trace][intel-pt] Implement the basic decoding functionality
Depends on D89408.

This diff finally implements trace decoding!

The current interface is

  $ trace load /path/to/trace/session/file.json
  $ thread trace dump instructions

  thread #1: tid = 3842849, total instructions = 22
    [ 0] 0x40052d
    [ 1] 0x40052d
    ...
    [19] 0x400521

  $ # simply enter, which is a repeat command
    [20] 0x40052d
    [21] 0x400529
    ...

This doesn't do any disassembly, which will be done in the next diff.

Changes:
- Added an IntelPTDecoder class, that is a wrapper for libipt, which is the actual library that performs the decoding.
- Added TraceThreadDecoder class that decodes traces and memoizes the result to avoid repeating the decoding step.
- Added a DecodedThread class, which represents the output from decoding and that for the time being only stores the list of reconstructed instructions. Later it'll contain the function call hierarchy, which will enable reconstructing backtraces.
- Added basic APIs for accessing the trace in Trace.h:
  - GetInstructionCount, which counts the number of instructions traced for a given thread
  - IsTraceFailed, which returns an Error if decoding a thread failed
  - ForEachInstruction, which iterates on the instructions traced for a given thread, concealing the internal storage of threads, as plug-ins can decide to generate the instructions on the fly or to store them all in a vector, like I do.
- DumpTraceInstructions was updated to print the instructions or show an error message if decoding was impossible.
- Tests included

Differential Revision: https://reviews.llvm.org/D89283
2020-11-05 18:38:03 -08:00
Vedant Kumar 65d15fefe3 [TargetList] Delete the destructor
AFAICT, ~TargetList simply implements the default destructor, plus some
locking.

The history is murky, so I'm not sure why we do this locking. Perhaps,
at some point, it was possible to delete the same TargetList instance
from two different threads, setting up a race. If that were true, then
the locking would protect against the race.

Since TargetList is uniquely owned by Debugger (m_target_list), no such
race is possible today.

Testing: check-lldb

Differential Revision: https://reviews.llvm.org/D90895
2020-11-05 16:56:37 -08:00
Vedant Kumar 16e5a347e7 [TargetList] Simplify dummy target creation
Factor out dummy target creation from CreateTargetInternal.

This makes it impossible for dummy target creation to accidentally fail
due to too-strict checking in one of the CreateTargetInternal overloads.

Testing: check-lldb

rdar://70630655

Differential Revision: https://reviews.llvm.org/D90872
2020-11-05 16:04:02 -08:00
Pedro Tammela ca17571051 [LLDB-lua] modify Lua's 'print' to respect 'io.stdout'
This patch changes the implementation of Lua's `print()` function to
respect `io.stdout`.

The original implementation uses `lua_writestring()` internally, which is
hardcoded to `stdout`.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D90787
2020-11-05 21:23:20 +00:00
Michał Górny 40140e122f [lldb] [Process/FreeBSDRemote] Remove thread name caching
Remove the thread name caching code.  It does not handle the possibility
of thread name changing between requests, therefore breaking
TestGdbRemoteThreadName.  While technically we could cache the results
and reset the cache on resuming process, the gain from doing that
does not seem worth the effort.

Differential Revision: https://reviews.llvm.org/D90863
2020-11-05 20:45:34 +01:00
Michał Górny 2c2eb5e670 [lldb] Enable FreeBSDRemote plugin by default and update test status
The new FreeBSDRemote plugin has reached feature parity on i386
and amd64 targets.  Use it by default on these architectures, while
allowing the use of the legacy plugin via FREEBSD_LEGACY_PLUGIN envvar.

Revisit the method of switching plugins.  Apparently, the return value
of PlatformFreeBSD::CanDebugProcess() is what really decides whether
the legacy or the new plugin is used.

Update the test status.  Reenable the tests that were previously
disabled on FreeBSD and do not cause hangs or are irrelevant to FreeBSD.
Mark all tests that fail reliably as expectedFailure.  For now, tests
that are flaky (i.e. produce unstable results) are left enabled
and cause unpredictable test failures.

Differential Revision: https://reviews.llvm.org/D90757
2020-11-05 17:49:46 +01:00
Raphael Isemann 79d16764dd [lldb][NFC] Fix compiler warnings after removal of eValueTypeVector
5d64574301 removes this enum value and now
all the switch statements that previously relied on handling this in the
'default' branch are causes compiler warnings due to redundant default cases.

This just removes the now unreachable code in there.
2020-11-05 17:17:33 +01:00
Pavel Labath 586c375fa3 [lldb] Remove [US]IntValueIsValidForSize from CommandObjectMemory
Use llvm::is(U)IntN (MathExtras.h) instead.
2020-11-04 16:28:10 +01:00
Pavel Labath ac6799d25a [lldb] Improve RegisterValue::GetScalarValue
Using Scalar::SetValueFromData, we make the code simpler, handle
big-endian systems properly, _and_ avoid type aliasing issues.
2020-11-04 14:53:06 +01:00
Pavel Labath 5d64574301 [lldb] Delete Value::Vector class
This class and it's surroundings contain a lot of shady code, but as far
as I can tell all of that code is unreachable (there is no code actually
setting the value to eValueTypeVector).

According to history this class was introduced in 2012 in
r167033/0665a0f09. At that time, the code seemed to serve some purpose,
and it had two entry points (in Value::SetContext and
ClangExpressionDeclMap::LookupDecl). The first entry point was deleted
in D17897 and the second one in r179842/44342735.

The stated purpose of the patch introducing this class was to fix
TestRegisters.py, and "expr $xmm0" in particular. Both of these things
function perfectly well these days without this class.
2020-11-04 10:21:56 +01:00
Jordan Rupprecht 33945cdd62 [NFC] Fix call to lldb RegisterValue constructor 2020-11-03 13:24:06 -08:00
Andy Yankovsky f35a82384d Return actual type from SBType::GetArrayElementType
SBType::GetArrayElementType should return the actual type, not the
canonical type (e.g. int32_t, not the underlying int).

Added a test case to validate the new behavior. I also ran all other
tests on Linux (ninja check-lldb), they all pass.

Differential revision: https://reviews.llvm.org/D90318
2020-11-03 10:53:44 -08:00
Michał Górny fbc0d41bb0 [lldb] [Process/FreeBSDRemote] Fix "Fix attaching via lldb-server"
One of the changes seems to have been lost in rebase.  Reapply.
2020-11-03 17:16:57 +01:00
Pavel Labath d2700b7873 [lldb/Utility] Add unit tests for RegisterValue::GetScalarValue
Buggy cases are commented out.

Also sneak in a modernization of a RegisterValue constructor.
2020-11-03 16:12:32 +01:00
Pedro Tammela 4b9fa3b705 [LLDB][NFC] treat Lua error codes in a more explicit manner
This patch is a minor suggestion to not rely on the fact
that the `LUA_OK` macro is 0.

This assumption could change in future versions of the C API.

Differential Revision: https://reviews.llvm.org/D90556
2020-11-03 09:39:47 +00:00
Michał Górny 952ddc9866 [lldb] [Plugins/FreeBSDRemote] Disable GetMemoryRegionInfo()
Disable GetMemoryRegionInfo() in order to unbreak expression parsing.
For some reason, the presence of non-stub function causes LLDB to fail
to detect system libraries correctly.  Through being unable to find
mmap() and allocate memory, this leads to expression parser being
broken.

The issue is non-trivial and it is going to require more time debugging.
On the other hand, the downsides of missing the function are minimal
(2 failing tests), and the benefit of working expression parser
justifies disabling it temporarily.  Furthermore, the old FreeBSD plugin
did not implement it anyway, so it allows us to switch to the new plugin
without major regressions.

The really curious part is that the respective code in the NetBSD plugin
yields very similar results, yet does not seem to break the expression
parser.

Differential Revision: https://reviews.llvm.org/D90650
2020-11-03 09:45:51 +01:00
Michał Górny 40d26bc4b1 [lldb] [Process/FreeBSDRemote] Remove GetSharedLibraryInfoAddress override
Remove the NetBSD-specific override of GetSharedLibraryInfoAddress(),
restoring the generic implementation from NativeProcessELF.

Differential Revision: https://reviews.llvm.org/D90620
2020-11-03 09:45:50 +01:00
Michał Górny 8e6bcbb417 [lldb] [Process/FreeBSDRemote] Fix attaching via lldb-server
Fix two bugs that caused attaching to a process in a pre-connected
lldb-server to fail.  These are:

1. Prematurely reporting status in NativeProcessFreeBSD::Attach().
   The SetState() call defaulted to notify the process, and LLGS tried
   to send the stopped packet before the process instance was assigned
   to it.  While at it, add an assert for that in LLGS.

2. Duplicate call to ReinitializeThreads() (via SetupTrace()) that
   overwrote the stopped status in threads.  Now SetupTrace() is called
   directly by NativeProcessFreeBSD::Attach() (not the Factory) in place
   of ReinitializeThreads().

This fixes at least commands/process/attach/TestProcessAttach.py
and python_api/hello_world/TestHelloWorld.py.

Differential Revision: https://reviews.llvm.org/D90525
2020-11-03 09:45:50 +01:00
Michał Górny f893b29397 [lldb] [Host/{free,net}bsd] Fix process matching by name
Fix process matching by name to make 'process attach -n ...' work.

The process finding code has an optimization that defers getting
the process name and executable format after the numeric (PID, UID...)
parameters are tested.  However, the ProcessInstanceInfoMatch.Matches()
method has been matching process name against the incomplete process
information as well, and effectively no process ever matched.

In order to fix this, create a copy of ProcessInstanceInfoMatch, set
it to ignore process name and se this copy for the initial match.
The same fix applies to FreeBSD and NetBSD host code.

Differential Revision: https://reviews.llvm.org/D90454
2020-11-03 09:45:50 +01:00
Michał Górny 326d235300 [lldb] [Process/FreeBSDRemote] Implement thread GetName()
Implement NativeThreadFreeBSD::GetName().  This is based
on the equivalent code in the legacy FreeBSD plugin, except it is
modernized a bit to use llvm::Optional and std::vector for data storage.

Differential Revision: https://reviews.llvm.org/D90298
2020-11-03 09:45:49 +01:00
Pedro Tammela 4d7d6f276c [LLDB/Lua] call lua_close() on Lua dtor
This patch calls `lua_close()` on Lua dtor.

This guarantees that the Lua GC finalizers are honored, aside from the
usual internal clean up.

It also guarantees a call to the `__close` metamethod of any active
to-be-closed variable in Lua 5.4.

Since the previous `luaL_openlibs()` was a noop, because the standard
library is cached internally, I've removed it.

Differential Revision: https://reviews.llvm.org/D90557
2020-11-02 16:52:30 +00:00
Nathan James ba447f38f6
[NFC][lldb] Silence unused variable warning 2020-11-01 14:37:06 +00:00
Joseph Tremoulet d20aa7ca42 [lldb] Report old modules from ModuleList::ReplaceEquivalent
This allows the Target to update its module list when loading a shared
module replaces an equivalent one.

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

Reviewed By: jingham

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

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

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

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D89156
2020-10-30 15:14:31 -04:00
Zequan Wu 4348e0eee4 [lldb][NFC] Refactor getUUID functionality
Differential Revision: https://reviews.llvm.org/D90325
2020-10-30 10:44:37 -07:00
Jan Kratochvil a136699b2a [nfc] [lldb] Align `user_id_t` format to the current `DIERef` format
Current user_id_t format is:
        63{isDebugTypes} 62..32{dwo || 7fffffff}
        31..0 {die_offset}
while current DIERef format is (I have made up the bit positions but the
field widths do match):
        63{m_section==isDebugTypes} 62{m_dwo_num_valid} 61..32{m_dwo_num}
        31..0 {m_die_offset}

Proposing to change user_id_t to:
        63{isDebugTypes} 62{dwo_is_valid} 61..32{dwo; 0 if !valid}
        31..0 {die_offset}

There is no benefit of having 31-bits wide dwo_num in user_id_t when it
gets converted to 30-bits width in DIERef.

This patch is for future DWZ patchset which extends the dwo_is_valid bit
into a 2-bit field (normal, DWO, DWZ, DWZcommon) so that both user_id_t
and DIERef can be changed then the same way.

It would be best to somehow unify user_id_t and DIERef but I do not plan
to do that. user_id_t should probably remain a number for the Python API
compatibility while there still needs to be some class with all the
methods to access it.

SymbolFileDWARF::GetDwpSymbolFile() and SymbolFileDWARF::GetDIE use
0x3fffffff for DWP but that does not clash:

formerly:
  31bits32..62:0x7fffffff = normal unit / not any DWO
  31bits32..62:0x3fffffff = DWP
  31bits32..62:others = DWO unit number

after this patch:
  bit62=0 30bits32..61:any = normal unit / not any DWO
  bit62=1 30bits32..61:0x3fffffff = DWP
  bit62=1 30bits32..61:others = DWO unit number

Differential Revision: https://reviews.llvm.org/D90413
2020-10-30 16:50:52 +01:00
Pavel Labath 8485ee781f [lldb/DWARF] Fix dwo flavour of TestTypeGetModule
SymbolFileDWARF::GetTypes was not handling dwo correctly. The fix is
simple -- adding a GetNonSkeletonUnit call -- but I've snuck in a small
refactor as well.
2020-10-30 15:20:27 +01:00
Jim Ingham c8c07b76b2 Use !hasLocalLinkage instead of listing the symbol types
we should be exporting one by one.

Differential Revision: https://reviews.llvm.org/D78972
2020-10-29 14:44:06 -07:00
Jim Ingham a37672e2db Mark the execution of stop-hooks as non-interactive.
The intention is not to allow stop-hook commands to query the
user, so this is correct.  It also works around a deadlock in
switching to the Python Session to execute python based commands
in the stop hook when the Debugger stdin is backed by a FILE *.

Differential Revision: https://reviews.llvm.org/D90332
2020-10-29 14:41:53 -07:00
Ilya Bukonkin 2c0cbc47ca GetModule, GetExeModule methods added 2020-10-29 23:44:51 +03:00
Marcel Hlopko 9bb9b737c5 Remove HAVE_VCS_VERSION_INC, not needed
This preprocessor define was meant to be used to conditionally include VCSVersion.inc. However, the define was always set, and it was the content of the header that was conditionally generated. Therefore HAVE_VCS_VERSION_INC should be cleaned up.

Reviewed By: gribozavr2, MaskRay

Differential Revision: https://reviews.llvm.org/D84623
2020-10-29 13:09:05 -07:00
Jan Kratochvil 41f2bb232c [nfc] [lldb] Remove excessive parentheses in SymbolFileDWARF::GetUID 2020-10-29 18:01:37 +01:00
David Zarzycki 075f661d01 [lldb] Unbreak the build after a recent PowerPC change
40dd4d5233 introduced two new types.
2020-10-29 05:56:38 -04:00
Jonas Devlieghere 49c84fd5a4 Revert "[AppleObjCRuntimeV2] Force lazily allocated class names to be resolved."
We're no longer convinced that this is needed and we have no test
coverage to disprove that. Backing out of this change until we're
convinced otherwise.
2020-10-28 16:53:02 -07:00
Jonas Devlieghere 00bb397b0d [lldb] Support Python imports relative the to the current file being sourced
Make it possible to use a relative path in command script import to the
location of the file being sourced. This allows the user to put Python
scripts next to LLDB command files and importing them without having to
specify an absolute path.

To enable this behavior pass `-c` to `command script import`. The
argument can only be used when sourcing the command from a file.

rdar://68310384

Differential revision: https://reviews.llvm.org/D89334
2020-10-27 09:20:45 -07:00
Raphael Isemann 45c3fc97a2 [lldb][NFC] Make GetResumeCountForLaunchInfo return an unsigned.
The number of resumes should always be positive to let's make this an
unsigned everywhere. Also remove the unused 'localhost' parameter from
ConvertArgumentsForLaunchingInShell.
2020-10-27 16:25:01 +01:00
Michał Górny 4ba8ea4cb0 [lldb] [Process/FreeBSD] Fix missing namespace qualifier
Fixes e4cc6e9bcd
2020-10-27 15:38:00 +01:00
Michał Górny 8e7ea99c38 [lldb] [Process/FreeBSDRemote] Enable watchpoint support
Replace the inline x86 watchpoint handling code with the reusable
NativeRegisterContextWatchpoint_x86.  Implement watchpoint support
in NativeThreadFreeBSD and SIGTRAP handling for watchpoints.

Un-skip all concurrent_events tests as they pass with the new plugin.

Differential Revision: https://reviews.llvm.org/D90102
2020-10-27 15:38:00 +01:00
Jan Kratochvil 7611c5bb42 [nfc] [lldb] Refactor DWARFUnit::GetDIE
Reduce indentation of the code by early returns for failed code paths.
2020-10-26 23:18:19 +01:00
Zequan Wu 242e1e9910 [lldb][PDB] Add ObjectFile PDB plugin
To allow loading PDB file with `target symbols add` command.

Differential Revision: https://reviews.llvm.org/D89812
2020-10-26 10:28:48 -07:00
Andy Yankovsky 206e8d8905 Fix SBError::SetErrorToGenericError
`SBError::SetErrorToGenericError` should call `Status::SetErrorToGenericError`,
not `Status::SetErrorToErrno`.

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D90151
2020-10-26 15:44:38 +01:00
Raphael Isemann d0ee1d8efe [lldb][NFC] Make GetShellSafeArgument simpler and faster
Escaping by inserting characters in the middle of a std::string isn't cheap.
It's much more verbose than just prepending a backslash in a loop.
2020-10-26 15:29:13 +01:00
Pavel Labath e4cc6e9bcd [lldb] Modernize PseudoTerminal::Fork 2020-10-26 12:01:20 +01:00
Pavel Labath 97ca9ca180 [lldb] Fix bitfield "frame var" for pointers (pr47743)
Displaying large packed bitfields did not work if one was accessing them
through a pointer, and he used the "->" notation ("[0]." notation is
fine). The reason for that is that implicit dereference in -> is plumbed
all the way down to ValueObjectChild::UpdateValue, where the process of
fetching the child value was forked for this flag. The bitfield
"sliding" code was implemented only for the branch which did not require
dereferencing.

This patch restructures the function to avoid this mistake. Processing
now happens in two stages.
- first the parent is dereferenced (if needed)
- then the child value is computed (this step includes sliding and is
  common for both branches)

Differential Revision: https://reviews.llvm.org/D89236
2020-10-26 12:01:20 +01:00
Michał Górny f5ca27569e [lldb] [Process/Linux] Reuse NativeRegisterContextWatchpoint_x86
Differential Revision: https://reviews.llvm.org/D90119
2020-10-26 11:55:22 +01:00
Michał Górny a890237665 [lldb] [Process/NetBSD] Set xs_xstate_bv correctly when setting regs
Ensure that xs_xstate_bv is set correctly before calling
WriteRegisterSet().  The bit can be clear if the relevant registers
were at their initial state when they were read, and it needs to be set
in order to apply changes from the XState structure.

Differential Revision: https://reviews.llvm.org/D90105
2020-10-26 11:54:40 +01:00
Michał Górny 7acf2e2e1e [lldb] [Process/FreeBSDRemote] Fix #include for i386 compat
Include <x86/fpu.h> rather than <machine/fpu.h>, as the latter is not
present on i386.

Differential Revision: https://reviews.llvm.org/D90128
2020-10-26 11:53:26 +01:00
Michał Górny d96cb52830 [lldb] [Process/NetBSD] Use XStateRegSet for all FPU registers
Unify the x86 regset API to use XStateRegSet for all FPU registers,
therefore eliminating the legacy API based on FPRegSet.  This makes
the code a little bit simpler but most notably, it provides future
compatibility for register caching.

Since the NetBSD kernel takes care of providing compatibility with
pre-XSAVE processors, PT_{G,S}ETXSTATE can be used on systems supporting
only FXSAVE or even plain FSAVE (and unlike PT_{G,S}ETXMMREGS, it
clearly indicates that XMM registers are not supported).

Differential Revision: https://reviews.llvm.org/D90034
2020-10-24 09:17:53 +02:00
Martin Storsjö 84ce6b9991 [lldb] Fix building with GCC 7. NFC. 2020-10-24 09:33:01 +03:00
David Blaikie 0b05732045 fix lldb for recent libDebugInfoDWARF API change 2020-10-23 19:20:38 -07:00
Walter Erquinigo 48d8af9825 [intel-pt] Disable/Enable tracing to guarantee the trace is correct
As mentioned in the comment inside the code, the Intel documentation
states that the internal CPU buffer is flushed out to RAM only when tracing is
disabled. Otherwise, the buffer on RAM might be stale.

This diff disables tracing when the trace buffer is going to be read. This is a
quite safe operation, as the reading is done when the inferior is paused at a
breakpoint, so we are not losing any packets because there's no code being
executed.

After the reading is finished, tracing is enabled back.

It's a bit hard to write a test for this now, but Greg Clayton and I will
refactor the PT support and writing tests for it will be easier. However
I tested it manually by doing a script that automates
the following flow

```
(lldb) b main
Breakpoint 1: where = a.out`main + 15 at main.cpp:4:7, address = 0x000000000040050f
(lldb) r
Process 3078226 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 1.1
frame #0: 0x000000000040050f a.out`main at main.cpp:4:7
(lldb) processor-trace start
(lldb) b 5
Breakpoint 2: where = a.out`main + 22 at main.cpp:5:12, address = 0x0000000000400516
(lldb) c
Process 3078226 resuming
Process 3078226 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 2.1
frame #0: 0x0000000000400516 a.out`main at main.cpp:5:12
(lldb) processor-trace show-instr-log
thread #1: tid=3078226
0x40050f <+15>: movl $0x0, -0x8(%rbp)

>>> Before, some runs of the script up to this point lead to empty traces

(lldb) b 6
Breakpoint 3: where = a.out`main + 42 at main.cpp:6:14, address = 0x000000000040052a
(lldb) c
Process 3092991 resuming
Process 3092991 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 3.1
frame #0: 0x000000000040052a a.out`main at main.cpp:6:14
(lldb) processor-trace show-instr-log thread #1: tid=3092991
0x40050f <+15>: movl $0x0, -0x8(%rbp)
0x400516 <+22>: movl $0x0, -0xc(%rbp)
0x40051d <+29>: cmpl $0x2710, -0xc(%rbp) ; imm = 0x2710
0x400524 <+36>: jge 0x400546 ; <+70> at main.cpp
0x400524 <+36>: jge 0x400546 ; <+70> at main.cpp

>>> The trace was re-enabled correctly and includes the instruction of the
first reading.
```
Those instructions correspond to these lines
```
3 int main() {
4 int z = 0;
5 for (int i = 0; i < 10000; i++) {
6 z += fun(z)
...
```

Differential Revision: https://reviews.llvm.org/D85241
2020-10-23 16:36:42 -07:00
Jonas Devlieghere 73811d32c7 [lldb] Move copying of files into reproducer out of process
For performance reasons the reproducers don't copy the files captured by
the file collector eagerly, but wait until the reproducer needs to be
generated.

This is a problematic when LLDB crashes and we have to do all this
signal-unsafe work in the signal handler. This patch uses a similar
trick to clang, which has the driver invoke a new cc1 instance to do all
this work out-of-process.

This patch moves the writing of the mapping file as well as copying over
the reproducers into a separate process spawned when lldb crashes.

Differential revision: https://reviews.llvm.org/D89600
2020-10-23 12:33:54 -07:00
Jonas Devlieghere a4459feca4 [lldb] Fix use of undefined type 'lldb_private::UtilityFunction'
We were returning the default constructed unique_pointer from
TypeSystem.h for which the compiler does not have a definition. Move the
implementation into the cpp file.
2020-10-23 11:48:11 -07:00
Jonas Devlieghere de346cf2ac [lldb] Redesign Target::GetUtilityFunctionForLanguage API
This patch redesigns the Target::GetUtilityFunctionForLanguage API:

 - Use a unique_ptr instead of a raw pointer for the return type.
 - Wrap the result in an llvm::Expected instead of using a Status object as an I/O parameter.
 - Combine the action of "getting" and "installing" the UtilityFunction as they always get called together.
 - Pass std::strings instead of const char* and std::move them where appropriate.

There's more room for improvement but I think this tackles the most
prevalent issues with the current API.

Differential revision: https://reviews.llvm.org/D90011
2020-10-23 10:00:23 -07:00
Michał Górny dae7b10034 [lldb] Split out NetBSD/x86 watchpoint impl for unification
Split the current NetBSD watchpoint implementation for x86 into Utility,
and revamp it to improve readability.  This code is meant to be used
as a common class for all x86 watchpoint implementation, particularly
these on FreeBSD and Linux.

The code uses global watchpoint enable bits, as required by the NetBSD
kernel.  If it ever becomes necessary for any platform to use local
enable bits instead, this can be trivially abstracted out.

The code also postpones clearing DR6 until a new different watchpoint
is being set in place of the old one.  This is necessary since LLDB
repeatedly reenables watchpoints on all threads, by clearing
and restoring them.  When DR6 is cleared as a part of that, then pending
events on other threads can no longer be associated with watchpoints
correctly.

Differential Revision: https://reviews.llvm.org/D89874
2020-10-23 12:20:15 +02:00
Jonas Devlieghere 3590a8319a [lldb] Fix bug instroduced by a00acbab45
g_expression_prefix, as the name implies, must be perfixed, not
suffixed.
2020-10-22 22:17:11 -07:00
Jonas Devlieghere a00acbab45 [lldb] Fix missing initialization in UtilityFunction ctor (NFC)
The UtilityFunction ctor was dropping the text argument. Probably for
that reason ClangUtilityFunction was setting the parent's member
directly instead of deferring to the parent ctor. Also change the
signatures to take strings which are std::moved in place.
2020-10-22 21:12:27 -07:00
Med Ismail Bennani efe62b637d [lldb/DWARF] Add support for DW_OP_implicit_value
This patch completes https://reviews.llvm.org/D83560. Now that the
compiler can emit `DW_OP_implicit_value` into DWARF expressions, lldb
needed to learn reading these opcodes for variable inspection and
expression evaluation.

This implicit location descriptor specifies an immediate value with two
operands: the length (ULEB128) followed by a block representing the value
in the target memory representation.

rdar://67406091

Differential revision: https://reviews.llvm.org/D89842

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2020-10-22 18:02:44 +02:00
Jonas Devlieghere 826997c462 [lldb] Fix a regression introduced by D75730
In a new Range class was introduced to simplify and the Disassembler API
and reduce duplication. It unintentionally broke the
SBFrame::Disassemble functionality because it unconditionally converts
the number of instructions to a Range{Limit::Instructions,
num_instructions}. This is subtly different from the previous behavior,
where now we're passing a Range and assume it's valid in the callee, the
original code would propagate num_instructions and the callee would
compare the value and decided between disassembling instructions or
bytes.

Unfortunately the existing tests was not particularly strict:

  disassembly = frame.Disassemble()
  self.assertNotEqual(len(disassembly), 0, "Disassembly was empty.")

This would pass because without this patch we'd disassemble zero
instructions, resulting in an error:

  (lldb) script print(lldb.frame.Disassemble())
  error: error reading data from section __text

Differential revision: https://reviews.llvm.org/D89925
2020-10-22 08:38:03 -07:00
Raphael Isemann bb1d702e25 [lldb][NFC] Make GetShellSafeArgument return std::string and unittest it. 2020-10-22 14:47:10 +02:00
Pavel Labath fa5fa63fd1 [lldb] Port lldb gdb-server to libOption
The existing help text was very terse and was missing several important
options. In the new version, I add a short description of each option
and a slightly longer description of the tool as a whole.

The new option list does not include undocumented no-op options:
--debug and --verbose. It also does not include undocumented short
aliases for long options, with two exceptions: -h, because it's
well-known; and -S (--setsid), as it's used in one test. Using these
options will now produce an error. I believe that is acceptable as users
aren't generally invoking lldb-server directly, and the only way to
learn about the short aliases was by looking at the source.

Differential Revision: https://reviews.llvm.org/D89477
2020-10-21 16:16:18 +02:00
Jan Kratochvil 7bf066a20f [nfc] [lldb] Fix harmless slicing of DWARFDIE
Differential Revision: https://reviews.llvm.org/D89875
2020-10-21 15:49:53 +02:00
Duncan P. N. Exon Smith b333d6e129 lldb: Migrate to MemoryBufferRef for createFileID (after 51d1d585e5)
I missed these two lldb users before deleting the `UnownedTag` API for
`createFileID` in 51d1d585e5. This should
fix the build.
2020-10-20 13:52:39 -04:00
Jason Molenda c932266c8d Add a nul byte to packet str before logging, increase default size.
Add a nul byte to the stream in CommunicationKDP::CheckForPacket
before we send the GetData() to a Log::Printf as a c-str.  Avoids
a crash when logging kdp communications and memory layout isn't
in your favor.
2020-10-20 01:43:31 -07:00
Duncan P. N. Exon Smith f96e16bc15 lldb: Update for change in `clang::Lexer`'s constructor
b3eff6b7bb updated `Lexer::Lexer` to take
`clang::MemoryBufferRef` instead of `clang::MemoryBuffer*`. Update LLDB
to fix the bots.
2020-10-19 20:09:27 -04:00
Walter Erquinigo 8a203bb22d [trace] rename ThreadIntelPT into TraceTrace
Renamed ThreadIntelPT to TreaceThread, making it a top-level class. I noticed that this class can and shuld work for any trace plugin and there's nothing intel-pt specific in it.
With that TraceThread change, I was able to move most of the json file parsing logic to the base class TraceSessionFileParser, which makes adding new plug-ins easier.

This originally was part of https://reviews.llvm.org/D89283

Differential Revision: https://reviews.llvm.org/D89408
2020-10-19 15:15:02 -07:00
Jan Kratochvil 0e5248be86 [nfc] [lldb] Move LookupAddress to DWARFCompileUnit
LookupAddress makes no sense for DWARFTypeUnit.
Also make GetNonSkeletonUnit to preserve the called type.

Differential Revision: https://reviews.llvm.org/D89646
2020-10-19 12:44:33 +02:00
Jan Kratochvil 224caaf69b [nfc] [lldb] Delete an empty trailing line.
A patchset being prepared shows needless diffs.
2020-10-18 10:16:00 +02:00
Dave Lee f16cecf375 [lldb] Implement ObjCExceptionThrowFrameRecognizer::GetName()
Implement `GetName` for `ObjCExceptionThrowFrameRecognizer`. Otherwise, `frame recognizer list` shows "(internal)" for the name.

Differential Revision: https://reviews.llvm.org/D89589
2020-10-16 14:24:03 -07:00
Adrian Prantl cf24508651 Add support for more OS types to AddClangModuleCompilationOptionsForSDKType()
This patch also avoids hardcoding the clang options, which makes it
less likely for them to become out-of-date.

rdar://problem/63791367+66927829

Differential Revision: https://reviews.llvm.org/D89428
2020-10-16 11:43:22 -07:00
Joseph Tremoulet d30797b404 [lldb] Minidump: check for .text hash match with directory
When opening a minidump, we might discover that it reports a UUID for a
module that doesn't match the build ID, but rather a hash of the .text
section (according to either of two different hash functions, used by
breakpad and Facebook respectively).  The current logic searches for a
module by filename only to check the hash; this change updates it to
first search by directory+filename.  This is important when the
directory specified in the minidump must be interpreted relative to a
user-provided sysoort, as the leaf directory won't be in the search path
in that case.

Also add a regression test; without this change, module validation fails
because we have just the placeholder module which reports as its path
the platform path in the minidump.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D89155
2020-10-16 09:32:08 -04:00
Pavel Labath daae4a8482 [lldb] Modernize PseudoTerminal::OpenSecondary 2020-10-16 15:22:55 +02:00
Pavel Labath e338ca7bce [lldb] Fix FreeBSD build for ea3a547 2020-10-16 13:50:53 +02:00
Jim Ingham 6754caa9bf Add an SB API to get the SBTarget from an SBBreakpoint
Differential Revision: https://reviews.llvm.org/D89358
2020-10-15 14:28:44 -07:00
Michał Górny 87d38831d9 [lldb] [Process/FreeBSDRemote] Initial multithreading support
Implement initial support for watching thread creation and termination.
Update ptrace() calls to correctly indicate requested thread.
Watchpoints are not supported yet.

This patch fixes at least multithreaded register tests.

Differential Revision: https://reviews.llvm.org/D89413
2020-10-15 17:37:37 +02:00
Jason Molenda af5504edd6 Increase timeout to find a dSYM in macos DownloadObjectAndSymbolFile
With a large dSYM over a slow home connection, the two minute timeout
would sometimes be exceeded, and we haven't seen instances of a
long timeout causing people any problems, so we're bumping it up.

640 seconds ought to be enough for anyone.

<rdar://problem/67759526>
2020-10-15 00:57:23 -07:00
Michał Górny ff30bff136 [lldb] [Process/FreeBSDRemote] Support YMM reg via PT_*XSTATE
Add a framework for reading/writing extended register sets via
PT_GETXSTATE/PT_GETXSTATE_INFO/PT_SETXSTATE, and use it to support
YMM0..YMM15.  The code is prepared to handle arbitrary XSAVE extensions,
including correct offset handling.

This fixes Shell/Register/*ymm* tests.

Differential Revision: https://reviews.llvm.org/D89193
2020-10-14 19:56:46 +02:00
Pavel Labath ea3a547f0b [lldb] Remove bogus ProcessMonitor forward-decls
This class is not used in those files.
2020-10-14 16:43:45 +02:00
Pavel Labath 2c4226f8ac [lldb-server][linux] Add ability to allocate memory
This patch adds support for the _M and _m gdb-remote packets, which
(de)allocate memory in the inferior. This works by "injecting" a
m(un)map syscall into the inferior. This consists of:
- finding an executable page of memory
- writing the syscall opcode to it
- setting up registers according to the os syscall convention
- single stepping over the syscall

The advantage of this approach over calling the mmap function is that
this works even in case the mmap function is buggy or unavailable. The
disadvantage is it is more platform-dependent, which is why this patch
only works on X86 (_32 and _64) right now. Adding support for other
linux architectures should be easy and consist of defining the
appropriate syscall constants. Adding support for other OSes depends on
the its ability to do a similar trick.

Differential Revision: https://reviews.llvm.org/D89124
2020-10-14 15:02:09 +02:00
Pavel Labath 6bb123b819 [lldb] Modernize PseudoTerminal::OpenFirstAvailablePrimary
replace char*+length combo with llvm::Error
2020-10-14 14:55:03 +02:00
Raphael Isemann cb81e662a5 [lldb] Reject redefinitions of persistent variables
Currently one can redefine a persistent variable and LLDB will just silently
ignore the second definition:

```
(lldb) expr int $i = 1
(lldb) expr int $i = 2
(lldb) expr $i
(int) $i = 1
```

This patch makes this an error and rejects the expression with the second
definition.

A nice follow up would be to refactor LLDB's persistent variables to not just be
a pair of type and name, but also contain some way to obtain the original
declaration and source code that declared the variable. That way we could
actually make a full diagnostic as we would get from redefining a variable twice
in the same expression.

Reviewed By: labath, shafik, JDevlieghere

Differential Revision: https://reviews.llvm.org/D89310
2020-10-14 10:24:35 +02:00
Jonas Devlieghere 3b33b41604 [lldb] Remove lexical block and fix formatting LoadScriptingModule (NFC) 2020-10-13 23:50:57 -07:00
Jonas Devlieghere 1197ee35b8 [lldb] Unconditionally strip the `.py(c)` extension when loading a module
Currently we only strip the Python extension when the file exists on
disk because we assumed that if it didn't exist it was a module.
However, with the change from D89334 this is no longer the case as we
want to be able to import a relative path to a .py as a module. Since we
always import a scripting module as a "python module" we should always
strip the extension if present.

Differential revision: https://reviews.llvm.org/D89352
2020-10-13 23:50:57 -07:00
Adrian Prantl f9586a3b3c Replace bool constants with named constants for improved readibility (NFC) 2020-10-13 17:41:26 -07:00
Adrian Prantl 9b1c06c0e8 Move initialization of Variable::m_loc_is_const_data into constructor (NFC)
This makes it symmetric with all other flags and makes it easier to
not forget to initialize it.

https://reviews.llvm.org/D89351
2020-10-13 17:01:28 -07:00
Raphael Isemann 6733b25447 [lldb][cmake] Remove custom logic for finding VCS file to fix LLDB's VCSVersion.inc generation
We are still implementing our own logic for this that looks for a VCS file in
the place where it was before the monorepo migration. This removes this logic
and just uses the CMake function that LLVM/Clang are using.

Reviewed By: JDevlieghere, kastiglione

Differential Revision: https://reviews.llvm.org/D88950
2020-10-13 17:14:43 +02:00
Raphael Isemann 02114e15da [lldb] Allow limiting the number of error diagnostics when parsing an expression
While debugging another bug I found out that we currently don't set any limit
for the number of diagnostics Clang emits. If a user does something that
generates a lot of errors (like including some long header file from within the
expression function), then we currently spam the LLDB output with potentially
thousands of Clang error diagnostics.

Clang sets a default limit of 20 errors, but given that LLDB is often used
interactively for small expressions I would say a limit of 5 is enough. The
limit is implemented as a setting, so if a user cares about seeing having a
million errors printed to their terminal then they can just increase the
settings value.

Reviewed By: shafik, mib

Differential Revision: https://reviews.llvm.org/D88889
2020-10-13 17:12:43 +02:00
Raphael Isemann 24e07570cc [lldb] Remove all the RegisterInfo name constification code
RegisterInfo's `reg_name`/`reg_alt_name` fields are C-Strings and are supposed
to only be generated from a ConstString. The reason for that is that
`DynamicRegisterInfo::GetRegisterInfo` and
`RegInfoBasedABI::GetRegisterInfoByName` try to optimise finding registers by
name by only comparing the C string pointer values instead of the underlying
strings. This only works if both C strings involved in the comparison come from
a ConstString. If one of the two C strings doesn't come from a ConstString the
comparison won't work (and most likely will silently fail).

I added an assert in b0060c3a78 which checks that
both strings come from a ConstString. Apparently not all ABI plugins are
generating their register names via ConstString, so this code is now not just
silently failing but also asserting.

In D88375 we did a shady fix for the MIPS plugins by just copying the
ConstString setup code to that plugin, but we still need to fix ABISysV_arc,
ABISysV_ppc and ABISysV_ppc64 plugins.

I would say we just fix the remaining plugins by removing the whole requirement
to have the register names coming from ConstStrings. I really doubt that we
actually save any time with the whole ConstString search trick (searching ~50
strings that have <4 characters doesn't sound more expensive than calling the
really expensive ConstString constructor + comparing the same amount of pointer
values). Also whatever small percentage of LLDB's runtime is actually spend in
this function is anyway not worth the complexity of this approach.

This patch just removes all this and just does a normal string comparison.

Reviewed By: JDevlieghere, labath

Differential Revision: https://reviews.llvm.org/D88490
2020-10-13 17:10:29 +02:00
Raphael Isemann 4cd873c4bd [lldb][NFC] Remove property predicate matcher
That's supposed to be used to implement things such as `settings set target.run-args{basename==test&&arch==x86_64} arg1`
but it's not actually fully implemented or tested anywhere.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D88910
2020-10-13 17:09:27 +02:00
Raphael Isemann f4f4d54ae0 [lldb] Fill Watch/AppleTV simulator gaps in PlatformDarwin
When running the test suite against the Watch/AppleTV simulator we currently hitting
the unimplemented parts of PlatformDarwin for the respective simulator platforms.

This just adds the respective switch cases.

This whole code path depends on having a valid Target, so can't just unittest this code
without refactoring it. So instead this is tested by just running the testsuite against
the respective simulators (which is how I found this).

Reviewed By: aprantl

Differential Revision: https://reviews.llvm.org/D89106
2020-10-13 15:06:41 +02:00
Dave Lee 08924b54de [lldb] Remove unused code in GetVersion (NFC)
Small cleanup to `lldb_private::GetVersion()`.

Differential Revision: https://reviews.llvm.org/D88939
2020-10-12 16:31:14 -07:00
Walter Erquinigo 26d861cbbd [trace] Scaffold "thread trace dump instructions"
Depends on D88841

As per the discussion in the RFC, we'll implement both

  thread trace dump [instructions | functions]

This is the first step in implementing the "instructions" dumping command.

It includes:

- A minimal ProcessTrace plugin for representing processes from a trace file. I noticed that it was a required step to mimic how core-based processes are initialized, e.g. ProcessElfCore and ProcessMinidump. I haven't had the need to create ThreadTrace yet, though. So far HistoryThread seems good enough.
- The command handling itself in CommandObjectThread, which outputs a placeholder text instead of the actual instructions. I'll do that part in the next diff.
- Tests

{F13132325}

Differential Revision: https://reviews.llvm.org/D88769
2020-10-12 12:08:18 -07:00
Pavel Labath e2f1fe361a [lldb/Utility] Introduce UnimplementedError
This is essentially a replacement for the PacketUnimplementedError
previously present in the gdb-remote server code.

The reason I am introducing a generic error is because I wanted the
native process classes to be able to signal that they do not support
some functionality. They could not use PacketUnimplementedError as they
are independent of a specific transport protocol. Putting the error
class in the the native process code was also not ideal because the
gdb-remote code is also used for lldb-server's platform mode, which does
not (should not) know how to debug individual processes.

I'm putting it under Utility, as I think it can be generally useful for
notifying about unsupported/unimplemented functionality (and in
particular, for programatically testing whether something is
unsupported).

Differential Revision: https://reviews.llvm.org/D89121
2020-10-12 13:46:17 +02:00
Jan Kratochvil 54434dc4dc [nfc] [lldb] Simplify calling SymbolFileDWARF::GetDWARFCompileUnit
Only SymbolFileDWARF::ParseCompileUnit creates a CompileUnit and it uses
DWARFCompileUnit for that.

Differential Revision: https://reviews.llvm.org/D89165
2020-10-12 13:26:54 +02:00
Martin Storsjö 5d330f435e [lldb] [Windows] Remove unused functions. NFC.
These became unused in 51117e3c51.
2020-10-10 20:47:40 +03:00
Martin Storsjö abaca237c5 [lldb] [Windows] Add missing 'override', silencing warnings. NFC.
Also remove superfluous 'virtual' in overridden methods.
2020-10-10 20:47:40 +03:00
Michał Górny 8dc2faf642 [lldb] [Process/FreeBSDRemote] Fix double semicolon 2020-10-10 18:54:52 +02:00
Michał Górny 9a37587ee3 [lldb] [Process/FreeBSDRemote] Kill process via PT_KILL
Use PT_KILL to kill the stopped process.  This ensures that the process
termination is reported properly and fixes delay/error on killing it.

Differential Revision: https://reviews.llvm.org/D89182
2020-10-10 18:54:05 +02:00
Michał Górny d83cd73e9d [lldb] [Process/FreeBSD] Mark methods override in RegisterContext*
Differential Revision: https://reviews.llvm.org/D89181
2020-10-10 18:52:23 +02:00
Walter Erquinigo ea1f49741e [intel pt] Refactor parsing
With the feedback I was getting in different diffs, I realized that splitting the parsing logic into two classes was not easy to deal with. I do see value in doing that, but I'd rather leave that as a refactor after most of the intel-pt logic is in place. Thus, I'm merging the common parser into the intel pt one, having thus only one that is fully aware of Intel PT during parsing and object creation.

Besides, based on the feedback in https://reviews.llvm.org/D88769, I'm creating a ThreadIntelPT class that will be able to orchestrate decoding of its own trace and can handle the stop events correctly.

This leaves the TraceIntelPT class as an initialization class that glues together different components. Right now it can initialize a trace session from a json file, and in the future will be able to initialize a trace session from a live process.

Besides, I'm renaming SettingsParser to SessionParser, which I think is a better name, as the json object represents a trace session of possibly many processes.

With the current set of targets, we have the following

- Trace: main interface for dealing with trace sessions
- TraceIntelPT: plugin Trace for dealing with intel pt sessions
- TraceIntelPTSessionParser: a parser of a json trace session file that can create a corresponding TraceIntelPT instance along with Targets, ProcessTraces (to be created in https://reviews.llvm.org/D88769), and ThreadIntelPT threads.
- ProcessTrace: (to be created in https://reviews.llvm.org/D88769) can handle the correct state of the traces as the user traverses the trace. I don't think there'll be a need an intel-pt specific implementation of this class.
- ThreadIntelPT: a thread implementation that can handle the decoding of its own trace file, along with keeping track of the current position the user is looking at when doing reverse debugging.

Differential Revision: https://reviews.llvm.org/D88841
2020-10-09 17:32:04 -07:00
Pavel Labath 0610a25a85 [lldb] Delete copy operations on PluginInterface class
This is a polymorphic class, copying it is a bad idea.

This was not a problem because most classes inheriting from it were
deleting their copy operations themselves. However, this enables us to
delete those explicit deletions, and ensure noone forgets to add them in
the future.
2020-10-09 10:37:09 +02:00
Jonas Devlieghere 9d7b08bd06 [lldb] Format remaining signal table (NFC)
Restore the signal tables to its original glory and mark it as not to be
clang-formatted.
2020-10-08 21:51:41 -07:00
Jim Ingham a68ffb19d3 Change the default handling of SIGCONT to nosuppress/nostop/notify
Except for the few people actually debugging shells, stopping on a
SIGCONT doesn't add any value.  And for people trying to run tests
under the debugger, stopping here is actively inconvenient.  So this
patch switches the default behavior to not stop.

Differential Revision: https://reviews.llvm.org/D89019
2020-10-08 15:24:19 -07:00
Pavel Labath 19d64138e6 [lldb] Fix "frame var" for large bitfields
The problem here is in the "sliding" code in
ValueObjectChild::UpdateValue. It modifies m_bitfield_bit_offset and
m_value to ensure the bitfield value fits the window given by the
underlying type.

However, this is broken next time UpdateValue is called, because it
updates the m_value value from the parent. However, the value cannot be
slid again because the m_bitfield_bit_offset is already modified.

It seems this can happen only under specific circumstances. One way to
trigger is is to run an expression which can be interpreted (jitting it
causes a new StackFrame and ValueObject variables to be created).

I fix this bug by modifying m_byte_offset instead of m_scalar, and
ensuring the changes are folded into m_scalar regardless of how many
times UpdateValue is called.

Differential Revision: https://reviews.llvm.org/D88992
2020-10-08 18:42:50 +02:00
Michał Górny 1a600266c3 [lldb] Initial version of FreeBSD remote process plugin
Add a new FreeBSD Process plugin using client/server model.  This plugin
is based on the one used by NetBSD.  It currently supports a subset
of functionality for amd64.  It is automatically used when spawning
lldb-server.  It can also be used by lldb client by setting
FREEBSD_REMOTE_PLUGIN environment variable (to any value).

The code is capable of debugging simple single-threaded programs.  It
supports general purpose, debug and FPU registers (up to XMM) of amd64,
basic signalling, software breakpoints.

Adding the support for the plugin involves removing some dead code
from FreeBSDPlatform plugin (that was not ever used because
CanDebugProcess() returned false), and replacing it with appropriate
code from NetBSD platform support.

Differential Revision: https://reviews.llvm.org/D88796
2020-10-08 16:03:00 +02:00
Jim Ingham 81b11c9107 Fix a macOS build break caused by 3dfb949861. 2020-10-07 15:01:27 -07:00
Pavel Labath 3dfb949861 [lldb] Check for and use ptsname_r if available
ptsname is not thread-safe. ptsname_r is available on most (but not all)
systems -- use it preferentially.

In the patch I also improve the thread-safety of the ptsname fallback
path by wrapping it in a mutex. This should guarantee the safety of a
typical ptsname implementation using a single static buffer, as long as
all callers go through this function.

I also remove the error arguments, as the only way this function can
fail is if the "primary" fd is not valid. This is a programmer error as
this requirement is documented, and all callers ensure that is the case.

Differential Revision: https://reviews.llvm.org/D88728
2020-10-07 15:29:29 +02:00
Jonas Devlieghere 0fcacefd16 [lldb] Format unix signal table (NFC)
Restore unix signal table to its original glory and mark it as not to be
clang-formatted.
2020-10-06 23:36:56 -07:00
Jonas Devlieghere e3b0414b0e [lldb] Change the xcrun (fallback) logic in GetXcodeSDK
This changes the logic in GetXcodeSDK to find an SDK with xcrun. The
code now executes the following steps:

 1. If DEVELOPER_DIR is set in the environment, it invokes xcrun with
    the given developer dir. If this fails we stop and don't fall back.
 2. If the shlib dir is set and exists,it invokes xcrun with the
    developer dir corresponding to the shlib dir. If this fails we fall
    back to 3.
 3. We run xcrun without a developer dir.

The new behavior introduced in this patch is that we fall back to
running xcrun without a developer dir if running it based on the shlib
dir failed.

A situation where this matters is when you're running lldb from an Xcode
that has no SDKs and that is not xcode-selected. Based on lldb's shlib
dir pointing into this Xcode installation, it will do an xcrun with the
developer set to the Xcode without any SDKs which will fail. With this
patch, when that happens, we'll fall back to trying the xcode-selected
Xcode by running xcrun without a developer dir.

Differential revision: https://reviews.llvm.org/D88866
2020-10-06 15:55:06 -07:00
Michał Górny a825eaa90e [lldb] [Platform] Move common ::DebugProcess() to PlatformPOSIX
Move common ::DebugProcess() implementation shared by Linux and NetBSD
(and to be shared by FreeBSD shortly) into PlatformPOSIX, and move
the old base implementation used only by Darwin to PlatformDarwin.

Differential Revision: https://reviews.llvm.org/D88852
2020-10-06 14:38:54 +02:00
Raphael Isemann ce4d15fe14 [lldb] Symlink the Clang resource directory to the LLDB build directory in standalone builds
When doing a standalone build (i.e., building just LLDB against an existing
LLVM/Clang installation), LLDB is currently unable to find any Clang resource
directory that contains all the builtin headers we need to parse real source
code. This causes several tests that actually parse source code on disk within
the expression parser to fail (most notably nearly all the import-std-module
tests).

The reason why LLDB can't find the resource directory is that we search based on
the path of the LLDB shared library path. We assumed that the Clang resource
directory is in the same prefix and has the same relative path to the LLDB
shared library (e.g., `../clang/10.0.0/include`). However for a standalone build
where the existing Clang can be anywhere on the disk, so we can't just rely on
the hardcoded relative paths to the LLDB shared library.

It seems we can either solve this by copying the resource directory to the LLDB
installation, symlinking it there or we pass the path to the Clang installation
to the code that is trying to find the resource directory. When building the
LLDB framework we currently copy the resource directory over to the framework
folder (this is why the import-std-module are not failing on the Green Dragon
standalone bot).

This patch symlinks the resource directory of Clang into the LLDB build
directory. The reason for that is simply that this is only needed when running
LLDB from the build directory. Once LLDB and Clang/LLVM are installed the
already existing logic can find the Clang resource directory by searching
relative to the LLDB shared library.

Reviewed By: kastiglione, JDevlieghere

Differential Revision: https://reviews.llvm.org/D88581
2020-10-06 09:28:39 +02:00
Jim Ingham be66987e20 Fix raciness in the StopHook check for "has the target run".
This was looking at the privateState, but it's possible that
the actual process has started up and then stopped again by the
time we get to the check, which would lead us to get out of running
the stop hooks too early.

Instead we need to track the intention of the stop hooks directly.

Differential Revision: https://reviews.llvm.org/D88753
2020-10-05 15:44:28 -07:00
David Spickett 71cf97e95b Reland "[lldb] Don't send invalid region addresses to lldb server"
This reverts commit c65627a1fe.

The test immediately after the new invalid symbol test was
failing on Windows. This was because when we called
VirtualQueryEx to get the region info for 0x0,
even if it succeeded we would call GetLastError.

Which must have picked up the last error that was set while
trying to lookup "not_an_address". Which happened to be 2.
("The system cannot find the file specified.")

To fix this only call GetLastError when we know VirtualQueryEx
has failed. (when it returns 0, which we were also checking for anyway)

Also convert memory region to an early return style
to make the logic clearer.

Reviewed By: labath, stella.stamenova

Differential Revision: https://reviews.llvm.org/D88229
2020-10-05 11:50:29 +01:00
David Blaikie 8036cf7f54 llvm-dwarfdump: Skip tombstoned address ranges
Make the dumper & API a bit more informative by using the new tombstone
addresses to filter out or otherwise render more explicitly dead code
ranges.
2020-10-04 13:43:29 -07:00
Michał Górny 9821632056 [lldb] [Process/NetBSD] Fix crash on unsupported i386 regs
Multiple fixes related to bugs discovered while debugging a crash
when reading all registers on i386.

The underlying problem was that GetSetForNativeRegNum() did not account
for MPX registers on i386, and since it only compared against upper
bounds of each known register set, the MPX registers were classified
into the wrong set and therefore considered supported.  However, they
were not expected in RegNumX86ToX86_64() and caused the assertion
to fail.

This includes:

- adding (unused) i386 → x86_64 translations for MPX registers
- fixing GetSetForNativeRegNum() to check both lower and upper bound
  for register sets, to avoid wrongly classifying unhandled register
  sets
- adding missing range check for MPX registers on i386
- renaming k_last_mpxr to k_last_mpxr_i386 for consistency
- replacing return-assertions with llvm_unreachable() and adding more
  checks for unexpected parameters

Differential Revision: https://reviews.llvm.org/D88682
2020-10-03 19:54:38 +02:00
Michał Górny 80b108f404 [lldb] [Process/NetBSD] Fix reading FIP/FDP registers
Fix reading FIP/FDP registers to correctly return segment and offset
parts.  On amd64, this roughly matches the Linux behavior of splitting
the 64-bit FIP/FDP into two halves, and putting the higher 32 bits
into f*seg and lower into f*off.  Well, actually we use only 16 bits
of higher half but the CPUs do not seem to handle more than that anyway.

Differential Revision: https://reviews.llvm.org/D88681
2020-10-03 19:54:38 +02:00
Jonas Devlieghere 07c112574a [lldb] Fix bug in fallback logic for finding the resource directory.
Both of the if-clauses modify the raw_path variable and only one of them
was resetting the variable for the fallback. Avoid future bugs like that
by always resetting the variable.

Differential revision: https://reviews.llvm.org/D88704
2020-10-02 09:56:01 -07:00
Jason Molenda a1e97923a0 Have kernel binary scanner load dSYMs as binary+dSYM if best thing found
lldb's PlatforDarwinKernel scans the local filesystem (well known
locations, plus user-specified directories) for kernels and kexts
when doing kernel debugging, and loads them automatically.  Sometimes
kernel developers want to debug with *only* a dSYM, in which case they
give lldb the DWARF binary + the dSYM as a binary and symbol file.
This patch adds code to lldb to do this automatically if that's the
best thing lldb can find.

A few other bits of cleanup in PlatformDarwinKernel that I undertook
at the same time:

1. Remove the 'platform.plugin.darwin-kernel.search-locally-for-kexts'
setting.  When I added the local filesystem index at start of kernel
debugging, I thought people might object to the cost of the search
and want a way to disable it.  No one has.

2. Change the behavior of
'plugin.dynamic-loader.darwin-kernel.load-kexts' setting so it does
not disable the local filesystem scan, or use of the local filesystem
binaries.

3. PlatformDarwinKernel::GetSharedModule into GetSharedModuleKext and
GetSharedModuleKernel for easier readability & maintenance.

4. Added accounting of .dSYM.yaa files (an archive format akin to tar)
that I come across during the scan.  I'm not using these for now; it
would be very expensive to expand the archives & see if the UUID matches
what I'm searching for.

<rdar://problem/69774993>
Differential Revision: https://reviews.llvm.org/D88632
2020-10-01 18:55:37 -07:00
Jordan Rupprecht c3193e464c [lldb/ipv6] Support running lldb tests in an ipv6-only environment.
When running in an ipv6-only environment where `AF_INET` sockets are not available, many lldb tests (mostly gdb remote tests) fail because things like `127.0.0.1` don't work there.

Use `localhost` instead of `127.0.0.1` whenever possible, or include a fallback of creating `AF_INET6` sockets when `AF_INET` fails.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D87333
2020-09-30 11:08:41 -07:00
Michał Górny 762e8f9bbd [lldb] [Process/NetBSD] Fix operating on ftag register 2020-09-30 15:39:31 +02:00
Ed Maste f794160c6c [lldb] Fix FreeBSD Arm Process Plugin build
Add a missing include and some definitions in 7695332166.

Patch by: Brooks Davis

Reviewed by: labath

Differential Revision: https://reviews.llvm.org/D88453
2020-09-30 09:25:27 -04:00
Walter Erquinigo 92e1ebeaa1 [trace] Fix destructor declaration
The destructor must be defined in the implementation class so that it
can be called, as Vedant Kumar pointed out in:

'''
What were your thoughts, re:

+class Trace : public PluginInterface {
+public:
+  ~Trace() override = default;

   Does this need to be `virtual ~Trace() = ...`?

      Otherwise, when a std::shared_ptr<Trace> is destroyed, the
      destructor for the derived TraceIntelPT instance won't run.
'''
2020-09-29 13:09:52 -07:00
Jim Ingham 1b1d981598 Revert "Revert "Add the ability to write target stop-hooks using the ScriptInterpreter.""
This reverts commit f775fe5964.

I fixed a return type error in the original patch that was causing a test failure.
Also added a REQUIRES: python to the shell test so we'll skip this for
people who build lldb w/o Python.
Also added another test for the error printing.
2020-09-29 12:01:14 -07:00
Jonas Devlieghere b4968c7001 [lldb] Remove redundant ctor call (NFC)
As pointed out by Pavel in D88249.
2020-09-29 10:05:12 -07:00
Jason Molenda 6e54918db7 Once we've found a firmware binary and loaded it, don't search more
Add the flag in ProcessMachCore::DoLoadCore that stops additional
searches for the binaries when we have an LC_NOTE identifying the
firmware/standalone binary as the correct one & we have loaded it
successfully.
2020-09-28 12:51:23 -07:00
Jonas Devlieghere f775fe5964 Revert "Add the ability to write target stop-hooks using the ScriptInterpreter."
This temporarily reverts commit b65966cff6
while Jim figures out why the test is failing on the bots.
2020-09-28 09:04:32 -07:00
Raphael Isemann 0b44bb8d40 [lldb][NFC] Minor cleanup in CxxModuleHandler::tryInstantiateStdTemplate
Using llvm::None and `contains` instead of `find`.
2020-09-28 13:03:45 +02:00
Tatsuo Nomura e779427757 Fix MIPS and MIPS64 ABI to use ConstString in their register info arrays.
RegInfoBasedABI::GetRegisterInfoByName was failing because mips/mips64 ABIs
don't use ConstString in their register info array.

Reviewed By: #lldb, teemperor

Differential Revision: https://reviews.llvm.org/D88375
2020-09-27 12:36:09 +02:00
Jim Ingham b65966cff6 Add the ability to write target stop-hooks using the ScriptInterpreter.
Differential Revision: https://reviews.llvm.org/D88123
2020-09-25 15:44:55 -07:00
Jason Molenda 1bec6eb3f5 Add support for firmware/standalone LC_NOTE "main bin spec" corefiles
When a Mach-O corefile has an LC_NOTE "main bin spec" for a
standalone binary / firmware, with only a UUID and no load
address, try to locate the binary and dSYM by UUID and if
found, load it at offset 0 for the user.

Add a test case that tests a firmware/standalone corefile
with both the "kern ver str" and "main bin spec" LC_NOTEs.

<rdar://problem/68193804>

Differential Revision: https://reviews.llvm.org/D88282
2020-09-25 15:19:22 -07:00
Jonas Devlieghere 6cd4a4cd02 [lldb] Pass reference instead of pointer in protected SBAddress methods.
Every call to the protected SBAddress constructor and the SetAddress
method takes the address of a valid object which means we might as well
pass it as a const reference instead of a pointer and drop the null
check.

Differential revision: https://reviews.llvm.org/D88249
2020-09-25 11:47:05 -07:00
Walter Erquinigo bddebca61e [intel-pt] Refactor the JSON parsing
Recently https://reviews.llvm.org/D88103 introduced a nice API for
converting a JSON object into C++ types, which include nice error
messaging.

I'm using that new functioniality to perform the parsing in a much more
elegant way. As a result, the code looks simpler and more maintainable,
as we aren't parsing anymore individual fields manually.

I updated the test cases accordingly.

Differential Revision: https://reviews.llvm.org/D88264
2020-09-24 16:35:34 -07:00
shafik a079f619b5 [LLDB] Add a defensive check for member__f_
I only have a crash log and was not able to come up with a test case for this.

rdar://problem/69403150
2020-09-24 14:48:21 -07:00
Saleem Abdulrasool 92d42b32a9 Utility: ignore OS version on non-Darwin targets in `ArchSpec`
The OS version field is generally not very helpful for non-Darwin
targets.  On Linux, it identifies the kernel version which moves
out-of-sync with the userspace.  On Windows, this field actually ends up
corresponding to the Visual Studio toolset version instead of the OS
version.  Consider non-Darwin targets without an OS version to be fully
specified.

Differential Revision: https://reviews.llvm.org/D88181
Reviewed By: Jonas Devlieghere, Dave Lee
2020-09-23 18:21:34 -07:00
Sam McCall 751f5c8146 Fix LLDB tweak in 62a47e994fcf5b73e29547d26cd9676b30cb69a3 2020-09-24 01:30:42 +02:00
Sam McCall fa69b60806 [JSON] Add error reporting to fromJSON and ObjectMapper
Translating between JSON objects and C++ strutctures is common.
From experience in clangd, fromJSON/ObjectMapper work well and save a lot of
code, but aren't adopted elsewhere at least partly due to total lack of error
reporting beyond "ok"/"bad".

The recently-added error model should be rich enough for most applications.
It requires tracking the path within the root object and reporting local
errors at appropriate places.
To do this, we exploit the fact that the call graph of recursive
parse functions mirror the structure of the JSON itself.
The current path is represented as a linked list of segments, each of which is
on the stack as a parameter. Concretely, fromJSON now looks like:
  bool fromJSON(const Value&, T&, Path);

Beyond the signature change, this is reasonably unobtrusive: building
the path segments is mostly handled by ObjectMapper and the vector<T> fromJSON.
However the root caller of fromJSON must now create a Root object to
store the errors, which is a little clunky.

I've added high-level parse<T>(StringRef) -> Expected<T>, but it's not
general enough to be the primary interface I think (at least, not usable in
clangd).

All existing users (mostly just clangd) are updated in this patch,
making this change backwards-compatible is a bit hairy.

Differential Revision: https://reviews.llvm.org/D88103
2020-09-24 01:20:09 +02:00