Commit Graph

27269 Commits

Author SHA1 Message Date
Pavel Labath 59656c0492 [lldb] Make CommunicationTest compatible with windows
Our (TCP) socket support is in a much better state than pipes. Use that
for testing the Communication class.

Move the CreateTCPConnectedSockets function
(SocketTestUtilities.{h,cpp}) to a place where it can be used from
Communication tests.
2022-08-26 15:25:46 +02:00
Pavel Labath afdfb3ae6b [lldb] Skip TestCoroutineHandle.py on libstdc++<11 2022-08-26 14:04:04 +02:00
Felipe de Azevedo Piovezan bb26ebb4d1 [lldb] Fix dotest argument order
When running LLDB API tests, a user can override test arguments with
LLDB_TEST_USER_ARGS. However, these flags used to be concatenated with a
CMake-derived variable LLDB_TEST_COMMON_ARGS, as below:

```
set(LLDB_DOTEST_ARGS ${LLDB_TEST_COMMON_ARGS};${LLDB_TEST_USER_ARGS}
    CACHE INTERNAL STRING)
```

This is problematic, because LLDB_TEST_COMMON_ARGS must be processed
first, while LLDB_TEST_USER_ARGS args must be processed last, so that
user overrides are respected. Currently, if a user attempts to override
one of the "inferred" flags, the user's request is ignored. This is the
case, for example, with `--libcxx-include-dir` and
`--libcxx-library-dir`. Both flags are needed by the greendragon bots.

This commit removes the concatenation above, keeping the two original
variables throughout the entire flow, processing the user's flag last.

The variable LLDB_TEST_COMMON_ARGS needs to be a CACHE property, but it
is modified throughout the CMake file with `set` or `list` or `string`
commands, which don't work with properties. As such, a temporary
variable `LLDB_TEST_COMMON_ARGS_VAR` is created.

This was tested locally by invoking CMake with:
-DLLDB_TEST_USER_ARGS="--libcxx-include-dir=blah --libcxx-library-dir=blah2"
and checking that tests failed appropriately.

Differential Revision: https://reviews.llvm.org/D132642
2022-08-26 06:52:40 -04:00
Michael Buch 5955edf8a4 [lldb][Test] Add missing breakpoint in TestNamespaceLookup.py 2022-08-26 10:28:28 +01:00
Michael Buch 2b95b50dd6 [lldb][ClangExpression] Fix LLDB_LOG incorrect format specifier
Previously this would log:
```
 FindExternalLexicalDecls on (ASTContext*)0x00000005CE825200 'Expression
ASTContext for '<user expression 0>'' in 'weak_ptr'
(%sDecl*)ClassTemplateSpecialization
 FindExternalLexicalDecls on (ASTContext*)0x00000005CE825200 'Expression
ASTContext for '<user expression 0>'' in '__shared_count'
(%sDecl*)CXXRecord
```

Note that the `%s` isn't actually respected. This patch fixes this
by providing the format specifiers that `lldb::formatv` supports.

Differential Revision: https://reviews.llvm.org/D132709
2022-08-26 10:06:38 +01:00
Adrian Vogelsgesang 6f88388f61 [lldb][test] Fix nullptr test expctation for 32-bit system
Follow-up to https://reviews.llvm.org/D132415

Fixes https://lab.llvm.org/buildbot/#/builders/17/builds/26630
2022-08-25 17:11:57 -07:00
Jonas Devlieghere e360281fa7
[lldb] Computer the slide when and apply it to each fileset's vm addr
Computer the slide when and apply it to each entry's vm addr when
reading from memory.

Differential revision: https://reviews.llvm.org/D132710
2022-08-25 16:38:01 -07:00
Jonas Devlieghere 48506fbbbf
[lldb] Teach LLDB about Mach-O filesets
This patch teaches LLDB about Mach-O filesets. Filsets are Mach-O files
that contain a bunch of other Mach-O files. Unlike universal binaries,
which have a different header, Filesets use load commands to describe
the different entries it contains.

Differential revision: https://reviews.llvm.org/D132433
2022-08-25 15:24:51 -07:00
Greg Clayton 613336da8c Don't index the skeleton CU when we have a fission compile unit.
When fission is enabled, we were indexing the skeleton CU _and_ the .dwo CU. Issues arise when users enable compiler options that add extra data to the skeleton CU (like -fsplit-dwarf-inlining) and there can end up being types in the skeleton CU due to template parameters. We never want to index this information since the .dwo file has the real definition, and we really don't want function prototypes from this info since all parameters are removed. The index doesn't work correctly if it does index the skeleton CU as the DIE offset will assume it is from the .dwo file, so even if we do index the skeleton CU, the index entries will try and grab information from the .dwo file using the wrong DIE offset which can cause errors to be displayed or even worse, if the DIE offsets is valid in the .dwo CU, the wrong DIE will be used.

We also fix DWO ID detection to use llvm::Optional<uint64_t> to make sure we can load a .dwo file with a DWO ID of zero.

Differential Revision: https://reviews.llvm.org/D131437
2022-08-25 14:48:04 -07:00
John Ericson 34fe6ddce1 Revert "[CMake] Avoid `LLVM_BINARY_DIR` when other more specific variable are better-suited"
This reverts commit ad8c34bc30.
2022-08-25 11:13:46 -04:00
Felipe de Azevedo Piovezan baeb17cdfa [lldb] Add more dylib paths for exception breakpoints
When setting a breakpoint upon throwing exceptions, LLDB only
searches for the libc++abi code inside dylibs named:
  1. libc++abi.dylib
  2. libSystem.B.dylib

However, this fails to account for libs with a version number. For
example, when building the libcxx and libcxxabi runtimes, the following
dylibs are generated:

build/lib/libc++abi.1.0.dylib
build/lib/libc++abi.1.dylib -> libc++abi.1.0.dylib
build/lib/libc++abi.dylib -> libc++abi.1.dylib

If we are debugging a program linked against any of the "versioned"
libs, the breakpoint doesn't work. This commit adds these names to the
search list.

Differential Revision: https://reviews.llvm.org/D132598
2022-08-25 06:46:04 -04:00
Felipe de Azevedo Piovezan 14d5ae2038 [lldb][nfc] Remove unused makefile test variables
The variables LLDB_USING_LIBCPP and LLDB_USING_LIBSTDCPP are no longer
used anywhere.

Differential Revision: https://reviews.llvm.org/D132596
2022-08-25 06:39:01 -04:00
Michael Buch 9427487fdb [lldb][Test] Prevent generating DW_AT_location for unused argument
This test simply checks whether we can print an optimized
function argument. With recent changes to Clang the assumption
that we don't generate a `DW_AT_location` attribute for the
unused funciton parameter breaks.

This patch tries harder to get Clang to drop the location
from DWARF by making it generate an `undef` for `unused1`.
Drop the check for `unused2` since it adds no benefit.

Differential Revision: https://reviews.llvm.org/D132635
2022-08-25 08:49:13 +01:00
Zequan Wu b6d56ddac1 [LLDB] Clean up after command fails
`CommandObject::CheckRequirements()` requires m_exe_ctx being cleaned up.

Differential Revision: https://reviews.llvm.org/D132397
2022-08-24 16:00:50 -07:00
Pirama Arumuga Nainar ee9d52a281 [lldb] Remove obsolete Android-specific definitions
Bionic's <sys/procfs.h> defines the necessary symbols.  Remove the
specialization for Android and the now-unnecessary include of
<sys/ptrace.h>.  This also helps resolve issues when building the
x86/x86_64 lldb-server for Android.

Curiously, the default branch to include <sys/procfs.h> doesn't seem
necessary on Linux.  I'll remove it and add it back if it breaks other
builders.

Differential Revision: https://reviews.llvm.org/D132514
2022-08-24 21:47:13 +00:00
Adrian Vogelsgesang 91389000ab [LLDB] Add data formatter for std::coroutine_handle
This patch adds a formatter for `std::coroutine_handle`, both for libc++
and libstdc++. For the type-erased `coroutine_handle<>`, it shows the
`resume` and `destroy` function pointers. For a non-type-erased
`coroutine_handle<promise_type>` it also shows the `promise` value.

With this change, executing the `v t` command on the example from
https://clang.llvm.org/docs/DebuggingCoroutines.html now outputs

```
(task) t = {
  handle = coro frame = 0x55555555b2a0 {
    resume = 0x0000555555555a10 (a.out`coro_task(int, int) at llvm-example.cpp:36)
    destroy = 0x0000555555556090 (a.out`coro_task(int, int) at llvm-example.cpp:36)
  }
}
```

instead of just

```
(task) t = {
  handle = {
    __handle_ = 0x55555555b2a0
  }
}
```

Note, how the symbols for the `resume` and `destroy` function pointer
reveal which coroutine is stored inside the `std::coroutine_handle`.
A follow-up commit will use this fact to infer the coroutine's promise
type and the representation of its internal coroutine state based on
the `resume` and `destroy` pointers.

The same formatter is used for both libc++ and libstdc++. It would
also work for MSVC's standard library, however it is not registered
for MSVC, given that lldb does not provide pretty printers for other
MSVC types, either.

The formatter is in a newly added  `Coroutines.{h,cpp}` file because there
does not seem to be an already existing place where we could share
formatters across libc++ and libstdc++. Also, I expect this code to grow
as we improve debugging experience for coroutines further.

**Testing**

* Added API test

Differential Revision: https://reviews.llvm.org/D132415
2022-08-24 14:40:53 -07:00
Jonas Devlieghere f01208781f
[lldb] Remove unused functions in ObjectContainer (NFC) 2022-08-24 14:26:16 -07:00
Muhammad Omair Javaid 849ca4626e [LLDB] Skip TestFunctionTemplateSpecializationTempArgs for Arm64/Windows
This test fails on buildbot while passes on standalone builds. I am
marking it as skipped until actual problem is found and resolved.
2022-08-24 20:07:00 +05:00
John Ericson ad8c34bc30 [CMake] Avoid `LLVM_BINARY_DIR` when other more specific variable are better-suited
A simple sed doing these substitutions:

- `${LLVM_BINARY_DIR}/(\$\{CMAKE_CFG_INTDIR}/)?lib(${LLVM_LIBDIR_SUFFIX})?\>` -> `${LLVM_LIBRARY_DIR}`
- `${LLVM_BINARY_DIR}/(\$\{CMAKE_CFG_INTDIR}/)?bin\>` -> `${LLVM_TOOLS_BINARY_DIR}`

where `\>` means "word boundary".

The only manual modifications were reverting changes in

- `compiler-rt/cmake/Modules/CompilerRTUtils.cmake
- `runtimes/CMakeLists.txt`

because these were "entry points" where we wanted to tread carefully not not introduce a "loop" which would end with an undefined variable being expanded to nothing.

This hopefully increases readability overall, and also decreases the usages of `LLVM_LIBDIR_SUFFIX`, preparing us for D130586.

Reviewed By: sebastian-ne

Differential Revision: https://reviews.llvm.org/D132316
2022-08-24 10:14:05 -04:00
Michał Górny 03b8f79048 [lldb] [gdb-remote] Use Communication::WriteAll() over Write()
Replace the uses of Communication::Write() with WriteAll() to avoid
partial writes.  None of the call sites actually accounted for that
possibility and even if it is unlikely to actually happen, there doesn't
seem to be any real harm from using WriteAll() instead.

Ideally, we'd remove Write() from the public API.  However, that would
change the API of SBCommunication.  The alternative would be to alias it
to WriteAll().

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D132395
2022-08-23 15:49:16 +02:00
Dave Lee c21dfa9e49 [lldb] Remove prefer-dynamic-value test override
Remove the test override of `target.prefer-dynamic-value`.

Previously, the lldb default was `no-dynamic-values`. In rG9aa7e8e9ffbe (in
2015), the default was changed to `no-run-target`, but at that time the tests
were changed to be run with `no-dynamic-value`. I don't know the reasons for
not changing the tests, perhaps to avoid determining which tests to change, and
what about them to change.

Because `no-run-target` is the lldb default, I think it makes sense to make it
the test default too. It puts the test config closer to what's used in
practice.

This change removes the `target.prefer-dynamic-value` override, and for those
tests that failed, they have been updated to explicitly use
`no-dynamic-values`. Future changes could update these tests to use dynamic
values too, or they can be left as is to exercise non-dynamic typing.

Differential Revision: https://reviews.llvm.org/D132382
2022-08-22 15:46:03 -07:00
Greg Clayton ae376feb0b Modify all register values whose byte size matches the address size to be formatter as eFormatAddressInfo.
This allows users to see similar output to what the "register read" command emits in LLDB's command line.

Added a test to verify that the PC has the correct value with contains a pointer followed by the module + function name and the source line info. Something like:

0x0000000100000a64 a.out`main + 132 at main.cpp:17:11

Differential Revision: https://reviews.llvm.org/D129528
2022-08-22 14:48:16 -07:00
Greg Clayton f0697d7c3f Don't create sections for SHN_ABS symbols in ELF files.
Symbols that have the section index of SHN_ABS were previously creating extra top level sections that contained the value of the symbol as if the symbol's value was an address. As far as I can tell, these symbol's values are not addresses, even if they do have a size. To make matters worse, adding these extra sections can stop address lookups from succeeding if the symbol's value + size overlaps with an existing section as these sections get mapped into memory when the image is loaded by the dynamic loader. This can cause stack frames to appear empty as the address lookup fails completely.

This patch:
- doesn't create a section for any SHN_ABS symbols
- makes symbols that are absolute have values that are not addresses
- add accessors to SBSymbol to get the value and size of a symbol as raw integers. Prevoiusly there was no way to access a symbol's value from a SBSymbol because the only accessors were:

  SBAddress SBSymbol::GetStartAddress();
  SBAddress SBSymbol::GetEndAddress();

  and these accessors would return an invalid SBAddress if the symbol's value wasn't an address
- Adds a test to ensure no ".absolute.<symbol-name>" sections are created
- Adds a test to test the new SBSymbol APIs

Differential Revision: https://reviews.llvm.org/D131705
2022-08-22 14:46:27 -07:00
Michael Buch 09f608fda5 [lldb][ClangExpression] Remove storage-class check when creating AsmLabel
This check was put in place to prevent static functions
from translation units outside the one that the current
expression is evaluated from taking precedence over functions
in the global namespace. However, this is really a different
bug. LLDB lumps functions from all CUs into a single AST and
ends up picking the file-static even when C++ context rules
wouldn't allow that to happen.

This patch removes the check so we apply the AsmLabel to all
FunctionDecls we create from DWARF if we have a linkage name
available. This makes the code-path easier to reason about and
allows calling static functions in contexts where we previously
would've chosen the wrong function.

We also flip the XFAILs in the API test to reflect what effect
this change has.

**Testing**

* Fixed API tests and added XFAIL

Differential Revision: https://reviews.llvm.org/D132231
2022-08-22 13:22:20 +01:00
Michael Buch 6f19f98710 [lldb][Test] Replace expect() with expect_expr() in TestNamespaceLookup.py
This will be useful in preparation for some reshuffling
of assertions in this file since we won't have to
adjust the persitent variable names during the process.

sed commands:
```
s/expect("expr -- /expect_expr("/g
s/startstr="(int) [$0-9]* = /result_type="int", result_value="/g
```

**Testing**

* API tests still pass

Differential Revision: https://reviews.llvm.org/D132271
2022-08-22 13:22:19 +01:00
Martin Storsjö b21de9b38f [lldb] Silence a GCC warning about missing returns after a fully covered switch. NFC. 2022-08-22 14:53:29 +03:00
Emmmer 65f6a8c23b [LLDB] Fix: make m_target_arch private
Using GetTargetArchitecture() instead of m_target_arch, and set m_target_arch to private.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D132353
2022-08-22 18:01:44 +08:00
Kazu Hirata ec5eab7e87 Use range-based for loops (NFC) 2022-08-20 21:18:32 -07:00
Kazu Hirata 258531b7ac Remove redundant initialization of Optional (NFC) 2022-08-20 21:18:28 -07:00
Kazu Hirata ce377df57e Ensure newlines at the end of files (NFC) 2022-08-20 21:18:23 -07:00
John Ericson 3adda398ce [clang][lldb][cmake] Use new `*_INSTALL_LIBDIR_BASENAME` CPP macro
Use this instead of `*_LIBDIR_SUFFIX`, from which it is computed.

This gets us ready for D130586, in which `*_LIBDIR_SUFFIX` is
deprecated.

Differential Revision: https://reviews.llvm.org/D132300
2022-08-20 12:52:21 -04:00
Kazu Hirata 347c462e97 [lldb] Use Any::has_value instead of ANy::hasValue (NFC) 2022-08-20 07:28:06 -07:00
Michał Górny d92f49fc4b Reland "[lldb] [test] Disable new CommunicationTests on Windows"
This change was wrongly reverted and re-broke the Windows buildbot.

Sponsored by: The FreeBSD Foundation
2022-08-20 08:32:55 +02:00
Michał Górny 2f50883c13 [lldb] [gdb-remote] Include PID in vCont packets if multiprocess
Try to always send vCont packets and include the PID in them if running
multiprocess.  This is necessary to ensure that with the upcoming full
multiprocess support always resumes the correct process without having
to resort to the legacy Hc packets.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D131758
2022-08-20 08:21:32 +02:00
Kazu Hirata c38bc421b1 [lldb] Use Optional::value instead of Optional::getValue (NFC) 2022-08-19 21:40:48 -07:00
Kazu Hirata 2b46625516 [lldb] Use Optional::transform instead of Optional::map (NFC) 2022-08-19 21:40:47 -07:00
Jonas Devlieghere cc0b5ebf7f
[lldb] Support specifying a custom libcxx for the API tests
This patch combines D129166 (to always pick the just-built libc++) and
D132257 (to allow customizing the libc++ for testing). The common goal
is to avoid picking up an unexpected libc++ for testing.

Differential revision: https://reviews.llvm.org/D132263
2022-08-19 15:20:41 -07:00
Michael Buch 1dc8fcff0e Revert "[lldb] [gdb-remote] Include PID in vCont packets if multiprocess" - Part 2
This reverts commit ccb9d4d4ad.

Reverts the associated tests
2022-08-19 19:31:14 +01:00
Michael Buch 5517401f93 Revert "[lldb] [gdb-remote] Include PID in vCont packets if multiprocess"
This reverts commit ccb9d4d4ad.

https://reviews.llvm.org/D131758

Differential Revision: https://reviews.llvm.org/D132250
2022-08-19 18:05:41 +01:00
Adrian Prantl fe0f72d5c5 Revert "[lldb] [test] Add synchronization to TestContinue"
This reverts commit 7aadecae40.

I'm reverting this commit because it appears to break the green dragon
incremental LLDB bot.

https://reviews.llvm.org/D131758

See LLDB Incremental buildbot: https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/46215/execution/node/70/log/
2022-08-19 09:23:18 -07:00
Adrian Prantl 00c4852561 Revert "[lldb] [test] Disable new CommunicationTests on Windows"
This reverts commit d38985a36b.
because I'm also reverting D131758.
2022-08-19 09:23:17 -07:00
Michał Górny d38985a36b [lldb] [test] Disable new CommunicationTests on Windows
Sponsored by: The FreeBSD Foundation
2022-08-19 16:23:39 +02:00
Michał Górny 7aadecae40 [lldb] [test] Add synchronization to TestContinue
Sponsored by: The FreeBSD Foundation
2022-08-19 15:49:35 +02:00
Michał Górny d6e1e01da9 [lldb] [Core] Harmonize Communication::Read() returns w/ thread
Harmonize the status and error values of Communication::Read() when
running with and without read thread.  Prior to this change, Read()
would return eConnectionStatusSuccess if read thread was enabled
and the read timed out or reached end-of-file, rather than
the respective states that are returned if read thread was disabled.
Now, it correctly returns eConnectionStatusTimedOut
and eConnectionStatusEndOfFile, and sets the error respectively.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D132217
2022-08-19 15:36:03 +02:00
Pavel Labath c74c17f37a [lldb] Use WSAEventSelect for MainLoop polling on windows
This patch switches the MainLoop class to use the WSAEventSelect
mechanism to wait for multiple sockets to become readable. The
motivation for doing that is that this allows us to wait for other kinds
of events as well (as long as they can be converted to WSAEvents). This
will allow us to avoid (abstract away) pipe-based multiplexing
mechanisms in the generic code, since pipes cannot be combined with
sockets on windows.

Since the windows implementation will now look completely different than
the posix (file descriptor-based) implementations, I have split the
MainLoop class into two (MainLoopPosix and MainLoopWindows), with the
common code going into MainLoopBase.

Differential Revision: https://reviews.llvm.org/D131159
2022-08-19 13:25:25 +02:00
Michał Górny 8b50ffe9fd [lldb] [test] Remove test_step_multiprocess, it's unreliable
Sponsored by: The FreeBSD Foundation
2022-08-19 10:08:11 +02:00
Michał Górny 58157087b0 [lldb] [test] Skip step packet test on non-amd64
Sponsored by: The FreeBSD Foundation
2022-08-19 09:48:13 +02:00
Michał Górny ccb9d4d4ad [lldb] [gdb-remote] Include PID in vCont packets if multiprocess
Try to always send vCont packets and include the PID in them if running
multiprocess.  This is necessary to ensure that with the upcoming full
multiprocess support always resumes the correct process without having
to resort to the legacy Hc packets.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D131758
2022-08-19 09:02:20 +02:00
John Ericson e941b031d3 Revert "[cmake] Use `CMAKE_INSTALL_LIBDIR` too"
This reverts commit f7a33090a9.

Unfortunately this causes a number of failures that didn't show up in my
local build.
2022-08-18 22:46:32 -04:00
John Ericson f7a33090a9 [cmake] Use `CMAKE_INSTALL_LIBDIR` too
We held off on this before as `LLVM_LIBDIR_SUFFIX` conflicted with it.
Now we return this.

`LLVM_LIBDIR_SUFFIX` is kept as a deprecated way to set
`CMAKE_INSTALL_LIBDIR`. The other `*_LIBDIR_SUFFIX` are just removed
entirely.

I imagine this is too potentially-breaking to make LLVM 15. That's fine.
I have a more minimal version of this in the disto (NixOS) patches for
LLVM 15 (like previous versions). This more expansive version I will
test harder after the release is cut.

Reviewed By: sebastian-ne, ldionne, #libc, #libc_abi

Differential Revision: https://reviews.llvm.org/D130586
2022-08-18 15:33:35 -04:00
Jim Ingham 33722848fc Use a SmallPtrSet rather than a SmallVector in ClusterManager.
The m_objects store in this class is only used to check whether
this ClusterManager already owns this pointer.  With a SmallVector
the is_contained call was non-linear in number of children, and for
instance printing all the elements of a 16M element std::vector
didn't complete in the time I was willing to wait for it (hours).

Since we are only doing insert & contains, some kind of set is a
better data structure.  In this patch I used SmallPtrSet.  With
that, the same array prints out in 30 seconds.  I also tried a
std::unordered_set but that was slightly slower and used a fair bit
more memory.

Other than performance, this is NFC.

Differential Revision: https://reviews.llvm.org/D131996
2022-08-18 09:34:28 -07:00
Slava Gurevich 5a197772ee [LLDB][NFC] Suppress spurious static inspection warnings
Suppress coverity false positives.
This diff contains comments only, including the hints for Coverity static code inspection
to suppress the warning originating at the next line after the comment.

Differential Revision: https://reviews.llvm.org/D131998
2022-08-17 16:12:42 -07:00
Zequan Wu 71d778f33e [LLDB][NativePDB] Switch to use DWARFLocationList.
Before, NativePDB uses scoped range as a workaround for value range, that causes
problems (e.g. a variable's value can only have one range, but usually a
variable's value is located at different address ranges, each at different
locations, in optimized build).
This patch let NativePDB switch to DWARFLocationList so a variable's value can
be described at multiple non-overlapped address ranges and each range maps to a
location.
Because overlapping ranges exists, here's peference when choosing ranges:
1. Always prefer whole value locations. Suppose a variable size is 8 bytes, one record is that for range [1, 5) first 4 bytes is at ecx, and another record is that for range [2, 8) the 8 bytes value is at rdx. This results: [1, 2) has first 4 bytes at ecx, [2, 8) has the whole value at rdx.
2. Always prefer the locations parsed later. Suppose first record is that for range [1, 5) value is at ecx, second record is that for range [2, 6) value is at eax. This results: [1, 2) -> ecx, [2, 6) -> eax.

Differential Revision: https://reviews.llvm.org/D130796
2022-08-17 13:37:13 -07:00
Slava Gurevich 1633190709 [LLDB][NFC] Fix optons parsing and misc. reliability in CommandObjectThread
* Fix broken option parsing in SetOptionValue()

Differential Revision: https://reviews.llvm.org/D131983
2022-08-17 12:20:10 -07:00
Chelsea Cassanova 9525015c1b [lldb][tests] Test queue-specific breakpoints
This commit adds tests to ensure that queue-specific breakpoints
work as expected, as this feature wasn't being tested before.

Differential Revision: https://reviews.llvm.org/D131605
2022-08-17 12:46:04 -04:00
Michael Buch 33833c8611 [lldb][Tests] Skip static-only tests in TestConstStaticIntegralMember.py for dsym variant
This test fails for Clang versions < 14.0 for `dsym` variants.
`dsymutil` strips debug info for classes with only static members.
Thus move the failing assertions into the XFAIL test case.

Differential Revision: https://reviews.llvm.org/D132004
2022-08-17 15:39:21 +01:00
David Spickett fe4a58214f [LLDB][ARM] Remove expected failure from AnonTypedef test
Thanks to ff9efe240c this test
is now passing.

https://lab.llvm.org/buildbot/#/builders/17/builds/26270
2022-08-17 08:52:58 +00:00
Michael Buch 88d3c1db45 [lldb][ClangExpression] Add asm() label to all FunctionDecls we create from DWARF
When resolving symbols during IR execution, lldb makes a last effort attempt
to resolve external symbols from object files by approximate name matching.
It currently uses `CPlusPlusNameParser` to parse the demangled function name
and arguments for the unresolved symbol and its candidates. However, this
hand-rolled C++ parser doesn’t support ABI tags which, depending on the demangler,
get demangled into `[abi:tag]`. This lack of parsing support causes lldb to never
consider a candidate mangled function name that has ABI tags.

The issue reproduces by calling an ABI-tagged template function from the
expression evaluator. This is particularly problematic with the recent
addition of ABI tags to numerous libcxx APIs.

The issue stems from the fact that `clang::CodeGen` emits function
function calls using the mangled name inferred from the `FunctionDecl`
LLDB constructs from DWARF. Debug info often lacks information for
us to construct a perfect FunctionDecl resulting in subtle mangled
name inaccuracies.

This patch side-steps the problem of inaccurate `FunctionDecl`s by
attaching an `asm()` label to each `FunctionDecl` LLDB creates from DWARF.
`clang::CodeGen` consults this label to get the mangled name as one of
the first courses of action when emitting a function call.

LLDB already does this for C++ member functions as of
[675767a591](https://reviews.llvm.org/D40283)

**Testing**

* Added API tests

Differential Revision: https://reviews.llvm.org/D131974
2022-08-17 09:02:43 +01:00
Pavel Kosov ff9efe240c [LLDB][JIT] Set processor for ARM architecture
Patch sets ARM cpu, before compiling JIT code. This enables FastISel for armv6 and higher CPUs and allows using hardware FPU

~~~

OS Laboratory. Huawei RRI. Saint-Petersburg

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131783
2022-08-17 09:10:21 +03:00
David Blaikie 9fc65658f5 fold assert-only variable into assert to address non-assert -Wunused-variable 2022-08-17 04:10:59 +00:00
Stella Stamenova 0cbaed3e14 Revert "[LLDB][NFC] Fix optons parsing and misc. reliability in CommandObjectThread"
This very much non-NFC change broke the windows lldb bot: https://lab.llvm.org/buildbot/#/builders/83/builds/22557

This reverts commit 461b410159.
2022-08-16 18:11:28 -07:00
Jonas Devlieghere b706f56133
[lldb] Automatically unwrap parameter packs in template argument accessors
When looking at template arguments in LLDB, we usually care about what
the user passed in his code, not whether some of those arguments where
passed as a variadic parameter pack.

This patch extends all the C++ APIs to look at template parameters to
take an additional 'expand_pack' boolean that automatically unwraps the
potential argument packs. The equivalent SBAPI calls have been changed
to pass true for this parameter.

A byproduct of the patch is to also fix the support for template type
that have only a parameter pack as argument (like the OnlyPack type in
the test). Those were not recognized as template instanciations before.

The added test verifies that the SBAPI is able to iterate over the
arguments of a variadic template.

The original patch was written by Fred Riss almost 4 years ago.

Differential revision: https://reviews.llvm.org/D51387
2022-08-16 18:10:14 -07:00
Zequan Wu 9fd54cf5c9 [LLDB][NativePDB] Add nullptr checking. 2022-08-16 17:01:47 -07:00
Slava Gurevich 461b410159 [LLDB][NFC] Fix optons parsing and misc. reliability in CommandObjectThread
* Improve reliability by checking return results for calls to FindLineEntryByAddress()
* Fix broken option parsing in SetOptionValue()

Differential Revision: https://reviews.llvm.org/D131983
2022-08-16 15:30:25 -07:00
Slava Gurevich 1fe72001e8 [LLDB][NFC] Fix memory leak in IntstumentationRuntimeTSan.cpp
ConvertToStructuredArray() relies on its caller to deallocate the heap-allocated object pointer it returns. One of its call-sites, in GetRenumberedThreadIds(), fails to deallocate causing a memory/resource leak. Fix the memory leak by converting the return type to shared_ptr, and clean up the rest of the file to use the typedef-ed shared_ptr types for StructuredData for safety and consistency.

Differential Revision: https://reviews.llvm.org/D131900
2022-08-16 14:34:50 -07:00
Kazu Hirata 50630dcc4c [lldb] Fix warnings
This patch fixes:

  lldb/source/Plugins/Instruction/RISCV/EmulateInstructionRISCV.h:34:5:
  error: default label in switch which covers all enumeration values
  [-Werror,-Wcovered-switch-default]

and:

  lldb/source/Plugins/Instruction/RISCV/EmulateInstructionRISCV.cpp:194:21:
  error: comparison of integers of different signs: 'int' and 'size_t'
  (aka 'unsigned long') [-Werror,-Wsign-compare]
2022-08-16 12:33:21 -07:00
Zequan Wu 7ebbef2b30 [LLDB][NativePDB] Add nullptr checking. 2022-08-16 09:59:09 -07:00
Emmmer 4fc7e9cba2 [LLDB][RISCV] Make software single stepping work
Add:
- `EmulateInstructionRISCV`, which can be used for riscv32 and riscv64.
- Add unittests for EmulateInstructionRISCV.

Note: Compressed instructions set (RVC) was still not supported in this patch.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131759
2022-08-16 23:44:50 +08:00
Emmmer 8ed3e75c96 [LLDB] Handle possible resume thread error
In this switch case we didn't handle possible errors in `ResumeThread()`, it's hard to get helpful information when it goes wrong.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131946
2022-08-16 23:43:28 +08:00
Emmmer 95e2949a53 [LLDB] Fix possible nullptr exception
Some architectures do not have a flag register (like riscv).
In this case, we should set it to `baton.m_register_values.end()` to avoid nullptr exception.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131945
2022-08-16 23:41:00 +08:00
David Spickett 662c1c2881 [LLDB][ARM] Remove unused LoadPseudoRegistersFromFrame function
https://reviews.llvm.org/D131658 identified a bug in this and
turns out it's not used anywhere.

Reviewed By: JDevlieghere, clayborg

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

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

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

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

rdar://76241471

Differential revision: https://reviews.llvm.org/D131328
2022-08-15 17:57:24 -07:00
Jonas Devlieghere 8d36a82d0a
[lldb] Flush the global thread pool in Debugger::Terminate
Use the Initialize/Terminate pattern for the global thread pool to make
sure it gets flushed during teardown.

Differential revision: https://reviews.llvm.org/D131407
2022-08-15 17:57:23 -07:00
Jonas Devlieghere 570e10cb9d
[lldb] Fix warning: comparison of integers of different signs
Fixes a warning about comparison of integers of different signs
'wchar_t' and 'int' in Editline.cpp:

      return out != (int)WEOF;
             ~~~ ^  ~~~~~~~~~
2022-08-15 11:25:46 -07:00
Slava Gurevich fa5124327a [LLDB][NFC] Reliability Fixes for FormatEntity
- Remove dead code
 - Fix incorrect null-reference check

Differential Revision: https://reviews.llvm.org/D131850
2022-08-15 10:16:47 -07:00
Michael Buch ac1bedd584 [lldb][debugserver] Revert "Use llvm::all_of (NFC)" for debugserver
Commit [6d9cd9199a](https://reviews.llvm.org/rG6d9cd9199a6fdeab0412117bcefc28f625510b61) added a dependency on llvm to debugserver.
This breaks the build. Since we don't want to add a dependency on llvm, this
patch reverts the offending commit.

Differential Revision: https://reviews.llvm.org/D131901
2022-08-15 17:35:39 +01:00
David Spickett 9f947abf94 [LLDB] Remove __future__ imports from examples
Not needed now that we require python 3.

Reviewed By: kastiglione, JDevlieghere

Differential Revision: https://reviews.llvm.org/D131772
2022-08-15 09:04:25 +00:00
David Spickett 193259cbce [LLDB] Remove __future__ imports from tests
Not needed now that we require python 3.

Reviewed By: kastiglione, JDevlieghere

Differential Revision: https://reviews.llvm.org/D131761
2022-08-15 08:54:06 +00:00
Walter Erquinigo 4025a8ae93 [NFC][trace][intel pt] add simple documentation line 2022-08-15 00:56:12 -07:00
Kazu Hirata 6d9cd9199a Use llvm::all_of (NFC) 2022-08-14 16:25:36 -07:00
Kazu Hirata 448c466636 Use llvm::erase_value (NFC) 2022-08-13 12:55:50 -07:00
Fangrui Song 115b1899a1 [lldb][ARC] Fix -Wtautological-bitwise-compare warning 2022-08-13 00:18:37 -07:00
Walter Erquinigo e17cae076c [trace][intel pt] Fix per-psb packet decoding
The per-PSB packet decoding logic was wrong because it was assuming that pt_insn_get_sync_offset was being udpated after every PSB. Silly me, that is not true. It returns the offset of the PSB packet after invoking pt_insn_sync_forward regardless of how many PSBs are visited later. Instead, I'm now following the approach described in https://github.com/intel/libipt/blob/master/doc/howto_libipt.md#parallel-decode for parallel decoding, which is basically what we need.

A nasty error that happened because of this is that when we had two PSBs (A and B), the following was happening

1. PSB A was processed all the way up to the end of the trace, which includes PSB B.
2. PSB B was then processed until the end of the trace.

The instructions emitted by step 2. were also emitted as part of step 1. so our trace had duplicated chunks. This problem becomes worse when you many PSBs.

As part of making sure this diff is correct, I added some other features that are very useful.

- Added a "synchronization point" event to the TraceCursor, so we can inspect when PSBs are emitted.
- Removed the single-thread decoder. Now the per-cpu decoder and single-thread decoder use the same code paths.
- Use the query decoder to fetch PSBs and timestamps. It turns out that the pt_insn_sync_forward of the instruction decoder can move past several PSBs (this means that we could skip some TSCs). On the other hand, the pt_query_sync_forward method doesn't skip PSBs, so we can get more accurate sync events and timing information.
- Turned LibiptDecoder into PSBBlockDecoder, which decodes single PSB blocks. It is the fundamental processing unit for decoding.
- Added many comments, asserts and improved error handling for clarity.
- Improved DecodeSystemWideTraceForThread so that a TSC is emitted always before a cpu change event. This was a bug that was annoying me before.
- SplitTraceInContinuousExecutions and FindLowestTSCInTrace are now using the query decoder, which can identify precisely each PSB along with their TSCs.
- Added an "only-events" option to the trace dumper to inspect only events.

I did extensive testing and I think we should have an in-house testing CI. The LLVM buildbots are not capable of supporting testing post-mortem traces of hundreds of megabytes. I'll leave that for later, but at least for now the current tests were able to catch most of the issues I encountered when doing this task.

A sample output of a program that I was single stepping is the following. You can see that only one PSB is emitted even though stepping happened!

```
thread #1: tid = 3578223
    0: (event) trace synchronization point [offset = 0x0xef0]
  a.out`main + 20 at main.cpp:29:20
    1: 0x0000000000402479    leaq   -0x1210(%rbp), %rax
    2: (event) software disabled tracing
    3: 0x0000000000402480    movq   %rax, %rdi
    4: (event) software disabled tracing
    5: (event) software disabled tracing
    6: 0x0000000000402483    callq  0x403bd4                  ; std::vector<int, std::allocator<int>>::vector at stl_vector.h:391:7
    7: (event) software disabled tracing
  a.out`std::vector<int, std::allocator<int>>::vector() at stl_vector.h:391:7
    8: 0x0000000000403bd4    pushq  %rbp
    9: (event) software disabled tracing
    10: 0x0000000000403bd5    movq   %rsp, %rbp
    11: (event) software disabled tracing
```

This is another trace of a long program with a few PSBs.
```
(lldb) thread trace dump instructions -E -f                                                                                                         thread #1: tid = 3603082
    0: (event) trace synchronization point [offset = 0x0x80]
    47417: (event) software disabled tracing
    129231: (event) trace synchronization point [offset = 0x0x800]
    146747: (event) software disabled tracing
    246076: (event) software disabled tracing
    259068: (event) trace synchronization point [offset = 0x0xf78]
    259276: (event) software disabled tracing
    259278: (event) software disabled tracing
    no more data
```

Differential Revision: https://reviews.llvm.org/D131630
2022-08-12 15:13:48 -07:00
Jonas Devlieghere abe9599f04
[lldb] Skip target variable tests on Darwin because of chained fixups
When targeting macOS Ventura, ld64 will use authenticated fixups for
x86_64 as well as arm64 (where that has always been the case). This
results in test failures when using an Xcode 14 toolchain on an Intel
mac running macOS Ventura:

  Failed Tests (3):
    lldb-api :: commands/target/basic/TestTargetCommand.py
    lldb-api :: lang/c/global_variables/TestGlobalVariables.py
    lldb-api :: lang/cpp/char8_t/TestCxxChar8_t.py

Rather than trying to come up with a sophisticated decorator based off
the deployment target, I marked them all as skipped with a comment
explaining why.

Differential revision: https://reviews.llvm.org/D131741
2022-08-12 10:23:15 -07:00
Michał Górny 9ba71d03b0 [lldb] [gdb-remote] Remove unimplemented ProcessIDIsValid() (NFC)
This method is not implemented and not referenced anywhere in the code.

Sponsored by: The FreeBSD Foundation
2022-08-12 11:17:15 +02:00
Med Ismail Bennani 6c58f12d07 [lldb/Symbol] Fix null-deref in TypeList::Dump
This patch should just a crash caused by a null pointer dereferencing
when dumping a type. It makes sure that the pointer is valid.

rdar://97455134

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-11 22:29:06 -07:00
Med Ismail Bennani edc77353da [lldb/crashlog] Improve exception reporting for interactive mode
This patch improve exception reporting when loading a crash report in a
scripted process. Now, we parse the `exception` dictionary from the
crash report use it the create a higher fidelity `MachException` stop info.

This patch also updates the test to reflect that change.

rdar://97096486

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-11 22:29:06 -07:00
Med Ismail Bennani 603f44acc6 [lldb/test] Fix interactive crashlog test failure (NFC)
This patch removes the system library names and mangled symbol from
the expected output for the interactive crashlog tests.

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-11 22:29:06 -07:00
Med Ismail Bennani 300e393092 [lldb/crashlog] Adapt raw text crashlog exception to json format
This patch parses CrashLog exception data from the raw
text format and adapts it to the new JSON format.

This is necessary for feature parity between the 2 formats.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-11 22:29:06 -07:00
Slava Gurevich 3934a31cfa [LLDB][NFC] Reliability fixes for IOHandlerCursesGUI
- checking retval of function calls
- dead code removal
- null dereference fix

Differential Revision: https://reviews.llvm.org/D131615
2022-08-11 21:10:53 -07:00
Slava Gurevich b2cb417ed9 [LLDB][NFC] Reliability fixes for ObjectFileMachO.cpp (part 2)
Add the fixes suggested post-push in D131554

Differential Revision: https://reviews.llvm.org/D131743
2022-08-11 21:08:18 -07:00
Dave Lee 95367da43d [lldb] Remove unused "import unittest2" statements 2022-08-11 19:11:01 -07:00
Dave Lee 56f9cfe30c [lldb] Remove uses of six module (NFC)
With lldb (& llvm) requiring Python 3.6+, use of the `six` module can be removed.

Differential Revision: https://reviews.llvm.org/D131304
2022-08-11 19:06:15 -07:00
Slava Gurevich 256ba7738e [LLDB][NFC] Fix the style issue in TCPSocket
Style fixes for the entire file

Differential Revision: https://reviews.llvm.org/D131543
2022-08-11 18:02:01 -07:00
Jonas Devlieghere ce075dfa19
[lldb] Fix output for unconditionally decorated tests
A missing call to `format` resulted in curly braces getting printed in
the reason a test was modified by a decorator. For example it would
print "{} unconditionally" instead of "skipping unconditionally" for
tests that were marked as such.
2022-08-11 16:20:15 -07:00
Dave Lee 28d0c0c2c8 [lldb] Tidy some regex in crashlog.py (NFC)
A spiritual follow up to D131032. I noticed some regex could be simplified.

This does some of the following:
1. Removes unused capture groups
2. Uses non-capturing `(?:...)` groups where grouping is needed but capturing isn't
3. Removes trailing `.*`
4. Uses `\d` over `[0-9]`
5. Uses raw strings
6. Uses `{N,}` to indicate N-or-more

Also improves the call site of a `re.findall`.

Differential Revision: https://reviews.llvm.org/D131305
2022-08-11 15:24:57 -07:00
Martin Storsjö a5881e8a81 [lldb] Silence a GCC warning about missing returns after a fully covered switch. NFC. 2022-08-12 00:35:32 +03:00
Jonas Devlieghere a8bc9b627e
[lldb] Simplify TestExec's source code (2/2)
I accidentally forgot to stage part of the changes in the previous
commit.
2022-08-11 12:44:38 -07:00
Jonas Devlieghere 181c0373d2
[lldb] Simplify TestExec's source code
Simplify the test's source code, remove unnecessary headers, and convert
it from C++ to C.
2022-08-11 12:36:54 -07:00
Walter Erquinigo c4fb631cee [NFC][lldb][trace] Fix formatting of tracing files
Pavel Labath taught me that clang-format sorts headers automatically
using llvm's rules, and it's better not to have spaces between

So in this diff I'm removing those spaces and formatting them as well.

I used `clang-format -i` to format these files.
2022-08-11 11:00:26 -07:00
Augusto Noronha c6c5944d05 [lldb] Allow DataFileCache to be constructed with a different policy
Differential Revision: https://reviews.llvm.org/D131531
2022-08-11 09:28:30 -07:00
Michael Buch af4cdfe136 [lldb][unittests] Add more test cases to CPlusPlusNameParser unit-tests
Add test cases for the possible function qualifiers that the
`CPlusPlusNameParser` supports.

Differential Revision: https://reviews.llvm.org/D131332
2022-08-11 15:05:48 +01:00
Emmmer 55e511f9f6 [LLDB][RISCV] Fix risc-v target build
Fixed an inconsistency between D130985 and D130342

This should be a follow-up of D130985

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131667
2022-08-11 21:42:44 +08:00
Pavel Kosov be98d93879 [LLDB] Disable FP test for arm 32 bit
Test was introduced in https://reviews.llvm.org/D126359

~~~

OS Laboratory. Huawei RRI. Saint-Petersburg
2021-09-14 18:57:03 +03:00
David Spickett 14913fa5d0 [LLDB][ARM] Extend testing for vpush emulation
https://reviews.llvm.org/D131658 found a bug in
ReadPseudoRegisterValue which would mean we read out
of bounds if the s register number was high enough.

This adds a memory check to vpush-1-thumb, which
should have been doing that anyway. Then copies that
test and uses the last 4 s registers instead.

Without the mentioned fix we see random values in
the final memory, with the fix it passes.

Reviewed By: fixathon

Differential Revision: https://reviews.llvm.org/D131663
2022-08-11 10:02:37 +00:00
Slava Gurevich ab6a0823af [LLDB] Fix out-of-bounds memory access in EmulationStateArm
Functionally broken code for reading and writing registers, likely due to typos,
and could cause out-of-bounds memory access.

Differential Revision: https://reviews.llvm.org/D131658
2022-08-11 01:34:18 -07:00
Emmmer 0247b5aaae [LLDB][RISCV] Add riscv software breakpoint trap code
Added:
- Take RISC-V `ebreak` instruction as breakpoint trap code, so our breakpoint works as expected now.

Further work:
- RISC-V does not support hardware single stepping yet. A software implementation may come in future PR.
- Add support for RVC extension (the trap code, etc.).

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D131566
2022-08-11 14:26:22 +08:00
Emmmer 7bece0f03b [LLDB][RISCV] Add riscv register definition and read/write
This patch is based on the minimal extract of D128250.

What is implemented:
- Use the same register layout as Linux kernel and mock read/write for `x0` register (the always zero register).
- Refactor some duplicate code, and delete unused register definitions.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D130342
2022-08-11 14:24:06 +08:00
Tom Stellard 9c6c4d675b lldb: Disable unittests if llvm_gtest target does not exist
This fixes the stand-alone build configuration where LLVM_MAIN_SRC_DIR
does not exist.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D124314
2022-08-10 16:56:08 -07:00
Med Ismail Bennani 3f3db13525 [lldb/crashlog] Add `-V|--version` option
This patch introduces a new option to the crashlog command to get the
the script version.

Since `crashlog.py` is not actually versioned, this returns lldb's
version instead.

rdar://98392669

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-10 16:18:46 -07:00
Slava Gurevich f4c21ab8b3 [LLDB][NFC] Clean up dead code
Remove unreachable code that will never execute.

Differential Revision: https://reviews.llvm.org/D131613
2022-08-10 15:22:15 -07:00
Slava Gurevich db9322b206 [LLDB][NFC] Reliability fixes for ObjectFileMachO.cpp
Static code inspection guided fixes for the following issues:
- dead code
- buffer not null-terminated
- null-dereference
- out-of-bounds access

Differential Revision: https://reviews.llvm.org/D131554
2022-08-10 15:16:37 -07:00
Pavel Kosov f63e2cfb7f [LLDB] Add basic floating point ops to IR interpreter
Patch adds support for fadd, fsub, fdiv, fmul and fcmp to IR interpreter.

~~~

OS Laboratory. Huawei RRI. Saint-Petersburg

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D126359
2022-08-10 16:34:52 +03:00
David Spickett 552dccf311 [LLDB][AArch64][NFC] Fix some clang-format annotations
We don't want the DEFINE_ macros or the array registers
being clang formatted.

RegisterInfos_arm64.h was missing the off annotation and
RegisterInfos_arm64_sve.h needed the off moving to before
the macro definitions.
2022-08-10 10:22:21 +00:00
David Spickett 5e538c669c [LLDB] Add multi value test for const static enum
1438639a2f removed a test
that was using undefined behaviour setting a non-typed enum
to a value outside its known range.

That test also checked if we formatted the value properly
when it could contain >1 valid enum value.

I don't think there's anything special about how we format
typed vs non-typed enums so I'm adding a test for ScopedEnum
that will expect to see 2 enum values plus extra.

Reviewed By: labath, Michael137, shafik

Differential Revision: https://reviews.llvm.org/D131472
2022-08-10 08:50:12 +00:00
Med Ismail Bennani 66f8819c50 [lldb/crashlog] Refactor the CrashLogParser logic
This patch changes the CrashLogParser class to be both the base class
and a Factory for the JSONCrashLogParser & TextCrashLogParser.

That should help remove some code duplication and ensure both class
have a parse method.

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani 355be8cf80 [lldb/crashlog] Skip null image dsym fetching on interactive mode
Sometimes, it can happen that a crash report has null images in its list
of used binaries. This manifests like such:

```
    0x0 - 0xffffffffffffffff ??? (*) <00000000-0000-0000-0000-000000000000> ???
```

When fetching debug symbols to symbolicate the crashlog stackframe,
having null images causes `dsymForUUID` to hang for few seconds.

This patch addresses that by skipping null images from being load by the
scripted process.

rdar://97419487

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani 41c1a5f9bd [lldb/crashlog] Add `-s|--skip-status` option to interactive mode
This patch introduces a new option for the interactive crashlog mode,
that will prevent it from dumping the `process status` & `thread backtrace`
output to the debugger console.

This is necessary when lldb in running from an IDE, to prevent flooding
the console with information that should be already present in the UI.

rdar://96813296

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani 13aa780f37 [lldb/crashlog] Remove 'process_path' parsing logic
In can happen when creating stackshot crash report that that key is missing.

Moreover, we try to parse that key but don't use it, or need it, since we
fetch images and symbolicate the stackframes using the binaries UUIDs.

This is why this patch removes everything that is related to the
`process_path`/`procPath` parsing.

rdar://95054188

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani 81cbc29457 [lldb/crashlog] Update frame regex matcher
This patch updates the regular expression matching stackframes in
crashlog to allow addresses that are 7 characters long and more (vs. 8
characters previously).

It changes the `0x[0-9a-fA-F]{7}[0-9a-fA-F]+` by `0x[0-9a-fA-F]{7,}`.

rdar://97684839

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani a07a75180c [lldb/crashlog] Surface error using SBCommandReturnObject argument
This patch allows the crashlog script to surface its errors to lldb by
using the provided SBCommandReturnObject argument.

rdar://95048193

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani a633c5e11b [lldb/crashlog] Add '-t|--target' option to interactive mode
This patch introduces a new flag for the interactive crashlog mode, that
allow the user to specify, which target to use to create the scripted
process.

This can be very useful when lldb already have few targets created:
Instead of taking the first one (zeroth index), we will use that flag to
create a new target. If the user didn't provide a target path, we will rely
on the symbolicator to create a targer.If that fails and there are already
some targets loaded in lldb, we use the first one.

rdar://94682869

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 21:01:37 -07:00
Med Ismail Bennani 4c2fb2e551 [lldb/crashlog] Fix interactive crashlog test
This patch should fix the interactive crashlog test by checking in the
binary as a yaml to regeneate the binary with the addresses and offsets
when running the test.

rdar://93655633

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-08-09 16:33:31 -07:00
Jim Ingham 36a461b8c2 @skipIfAsan for the other long test in TestMemoryRegion.py
These two tests were each of them too long when running under ASAN,
so we have to skip both to get a clean ASAN bot run.
2022-08-09 14:55:20 -07:00
Jim Ingham 0c86fbb557 The memory region tests have been consistently timing on the ASAN
bot.  This happens because they are building a long result into
a Python string, and the asan checker is making that very slow.

The last two tests here are both slow, but the 'test_command' is the
really slow one.  I'm going to start disabling just that one and see
if that gets the ASAN bots clean.
2022-08-09 12:52:18 -07:00
Jorge Gorbe Moya fe01292457 Move FormattersMatchCandidate flags to a struct.
This removes some error-prone repetition in
FormatManager::GetPossibleMatches, where the same three boolean flags
are passed in a row multiple times as arguments to recursive calls to
GetPossibleMatches.

Instead of:
```
  // same flags, but with did_strip_typedef set to true.
  GetPossibleMatches(..., did_strip_ptr, did_strip_ref, true);
```
we can now say
```
  GetPossibleMatches(..., current_flags.WithStrippedTypedef());
```
which hopefully makes the intent clearer, and more readable in case we
add another flag.

Reviewed by: DavidSpickett, labath

Differential Revision: https://reviews.llvm.org/D131459
2022-08-09 10:48:49 -07:00
Fangrui Song 5146f84fd6 LLVM_NODISCARD => [[nodiscard]]. NFC 2022-08-09 07:16:34 +00:00
Jonas Devlieghere bd3976fed4
[lldb] Refactor Symbols::DownloadObjectAndSymbolFile
- Reduce indentation
 - Extract caching of the DbgShellCommand and the dsymForUUID executable
   (or equivalent)
 - Check the DBGShellCommands before falling back to
   /usr/local/bin/dsymForUUID
 - Don't check ~rc/bin/dsymForUUID
 - Improve error reporting
 - Don't cache the value of LLDB_APPLE_DSYMFORUUID_EXECUTABLE

Differential revision: https://reviews.llvm.org/D131303
2022-08-08 20:14:07 -07:00
Shafik Yaghmour 1438639a2f [LLDB] Remove undefined behavior in TestConstStaticIntegralMember.py
Setting an enum without a fixed underlying type to a value which is outside the
value range is undefined behavior.

The initializer needs to be a constant expression and therefore this was always
ill-formed we just were not diagnosing it before.

See D130058 and D131307 for more details.

Differential Revision: https://reviews.llvm.org/D131460
2022-08-08 19:23:53 -07:00
Greg Clayton c012408453 Implement better path matching in FileSpecList::FindCompatibleIndex(...).
Currently a FileSpecList::FindFileIndex(...) will only match the specified FileSpec if:
- it has filename and directory and both match exactly
- if has a filename only and any filename in the list matches

Because of this, we modify our breakpoint resolving so it can handle relative paths by doing some extra code that removes the directory from the FileSpec when searching if the path is relative.

This patch is intended to fix breakpoints so they work as users expect them to by adding the following features:
- allow matches to relative paths in the file list to match as long as the relative path is at the end of the specified path at valid directory delimiters
- allow matches to paths to match if the specified path is relative and shorter than the file paths in the list

This allows us to remove the extra logic from BreakpointResolverFileLine.cpp that added support for setting breakpoints with relative paths.

This means we can still set breakpoints with relative paths when the debug info contains full paths. We add the ability to set breakpoints with full paths when the debug info contains relative paths.

Debug info contains "./a/b/c/main.cpp", the following will set breakpoints successfully:
- /build/a/b/c/main.cpp
- a/b/c/main.cpp
- b/c/main.cpp
- c/main.cpp
- main.cpp
- ./c/main.cpp
- ./a/b/c/main.cpp
- ./b/c/main.cpp
- ./main.cpp

This also ensures that we won't match partial directory names, if a relative path is in the list or is used for the match, things must match at the directory level.

The breakpoint resolving code will now use the new FileSpecList::FindCompatibleIndex(...) function to allow this fuzzy matching to work for breakpoints.

Differential Revision: https://reviews.llvm.org/D130401
2022-08-08 15:20:38 -07:00
Walter Erquinigo ddd576ab87 [lldb] Prevent race condition when fetching /proc/cpuinfo
@clayborg found a potential race condition when setting a static
variable. The fix seems simply to use call_once.

All relevant tests pass.

Differential Revision: https://reviews.llvm.org/D131081
2022-08-08 12:31:42 -07:00
Fangrui Song cdeb50c321 [lldb] Remove include/lldb/lldb-private.h
The header from 62e0681afb does something with
LLVM_FALLTHROUGH. Now that llvm-project has switched to C++17 and
LLVM_FALLTHROUGH uses have been migrated to [[fallthrough]], the header is
unneeded.

Reviewed By: JDevlieghere

Differential Revision: https://reviews.llvm.org/D131422
2022-08-08 12:03:53 -07:00
Fangrui Song 59d2495fe2 [lldb] LLVM_FALLTHROUGH => [[fallthrough]]. NFC 2022-08-08 11:31:49 -07:00
Alex Langford 5fff4b75ca [lldb] Pass TestExternCSymbols.py on Windows
This test previously was expected to fail on windows. As of my previous
patch (1d2a62afaf) this test now passes on
windows consistently. This patch adjusts the expectations of the test
accordingly.
2022-08-08 11:01:16 -07:00
Slava Gurevich 06ff46d2d7 [LLDB][NFC] Fix suspicious bitwise expression in PrintBTEntry()
Current application of bitwise-OR to a binary mask always results in True, which seems
inconsistent with the intent of the statement, a likely typo.

Differential Revision: https://reviews.llvm.org/D131312
2022-08-08 09:04:22 -07:00
Michał Górny 9b031d5e3a [lldb] Make Process and subclass constructors protected
Make constructors of the Process and its subclasses class protected,
to prevent accidentally constructing Process on stack when it could be
afterwards accessed via a shared_ptr (since it uses
std::enable_shared_from_this<>).

The only place where a stack allocation was used were unittests,
and fixing them via declaring an explicit public constructor
in the respective mock classes is trivial.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D131275
2022-08-08 17:34:27 +02:00
Jonas Devlieghere d446d91aa3
[lldb] Use single-argument static_assert where applicable (NFC)
Since C++17 the message string for static_assert is optional. Replaces
static asserts with an empty string literal with the single-argument
variant.
2022-08-07 14:26:08 -07:00
Dave Lee c615e467db [lldb] Hoist TraceOn check out of loop (NFC) 2022-08-07 12:19:47 -06:00
Dave Lee 87990fd8f4 [lldb] Fix formatting in python-reference.rst 2022-08-07 12:17:36 -06:00
Dave Lee e49c1568b6 [lldb] Dynamically generate enum names in lldbutil
Change the `<enum>_to_str` functions in lldbutil to be dynamic.

Instead of a manually maintained if/elif switch, the functions now perform
lookup in a dynamically generated dict. The names are determined by stripping
the enum's prefix, and then lowercasing the remaining suffix, ex:

    eStateRunning -> "running"

Differential Revision: https://reviews.llvm.org/D131138
2022-08-07 12:15:51 -06:00
Kazu Hirata 7542e72188 Use llvm::is_contained (NFC) 2022-08-07 00:16:17 -07:00
Slava Gurevich aa4977f2e1 [LLDB][NFC] Reliability fixes to TCPSocket code
Patch the following issues found by static code inspection:
- Unchecked return values from lib calls
- Passing potentially negative arg into a function that requires non-negative input
- Possible socket double-close

Differential Revision: https://reviews.llvm.org/D131294
2022-08-06 23:06:55 -07:00
Tobias Hieta b1356504e6
[LLVM] Update C++ standard to 17
Also make the soft toolchain requirements hard. This allows
us to use C++17 features in LLVM now.

If we find patterns with C++17 that improve readability
it should be recommended in the coding standards.

Reviewed By: jhenderson, cor3ntin, MaskRay

Differential Revision: https://reviews.llvm.org/D130689
2022-08-06 09:42:10 +02:00
Slava Gurevich bcac7b3acb [LLDB] Missing break in a switch statement alters the execution flow.
Looks like a typo from the past code changes.

    Differential Revision: https://reviews.llvm.org/D131244
2022-08-05 18:33:18 -07:00
Jonas Devlieghere 9c81b743e3
[lldb] Improve EXC_RESOURCE exception reason
Jason noted that the stop message we print for a memory high water mark
notification (EXC_RESOURCE) could be clearer. Currently, the stop
reason looks like this:

  * thread #3, queue = 'com.apple.CFNetwork.LoaderQ', stop reason =
    EXC_RESOURCE RESOURCE_TYPE_MEMORY (limit=14 MB, unused=0x0)

It's hard to read the message because the exception and the type
(EXC_RESOURCE RESOURCE_TYPE_MEMORY) blend together. Additionally, the
"observed=0x0" should not be printed for memory limit exceptions.

I wanted to continue to include the resource type from
<kern/exc_resource.h> while also explaining what it actually is. I used
the wording from the comments in the header. With this path, the stop
reason now looks like this:

  * thread #5, stop reason = EXC_RESOURCE (RESOURCE_TYPE_MEMORY: high
    watermark memory limit exceeded) (limit=14 MB)

rdar://40466897

Differential revision: https://reviews.llvm.org/D131130
2022-08-05 11:19:46 -07:00
Jim Ingham 0948f1cf81 Reapply the commits to enable accurate hit-count detection for watchpoints.
This commit combines the initial commit (7c240de609af), a fix for x86_64 Linux
(3a0581501e76) and a fix for thinko in a last minute rewrite that I really
should have run the testsuite on.

Also, make sure that all the "I need to step over watchpoint" plans execute
before we call a public stop.  Otherwise, e.g. if you have N watchpoints and
a Signal, the signal stop info will get us to stop with the watchpoints in a
half-done state.

Differential Revision: https://reviews.llvm.org/D130674
2022-08-05 11:01:27 -07:00
Walter Erquinigo 6fb744be76 [trace][intel pt] Support a new kernel section in LLDB’s trace bundle schema
Add a new "kernel" section with following schema.

```
"kernel": {
  "loadAddress"?: decimal | hex string | string decimal
  # This is optional. If it's not specified, use default address 0xffffffff81000000.
  "file": string
  # path to the kernel image
}
```

Here's more details of the diff:
- If "kernel" section exist, it means current tracing mode is //KernelMode//.
- If tracing mode is //KernelMode//, the "processes" section must be empty and the "kernel" and "cpus" section must be provided. This is tested with `TestTraceLoad`.
- "kernel" section is parsed and turned into a new process with a single module which is the kernel image. The kernel process has N fake threads, one for each cpu.

Reviewed By: wallace

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

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

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

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

Differential Revision: https://reviews.llvm.org/D129682
2022-08-04 11:18:08 -07:00
Jim Ingham b06da9c183 Remove the check for eStateConnected in remote testing sessions.
This check is clearly incorrect, there's no way you should have an
eStateConnected event left on the queue if you've already launched
and hit a breakpoint in the program.  This check fails running remotely
on Darwin systems and on one remote Linux platform.  And if we do
find this failing somewhere, we should fix the bogus eStateConnected,
not the test.
2022-08-04 09:19:55 -07:00
Chelsea Cassanova bcf6ffb87e Reland "[lldb/Fuzzer] Add fuzzer for expression evaluator"
This reverts commit d959324e1e.

The target_include_directories in the clang-fuzzer CMake files
are set to PRIVATE instead of PUBLIC to prevent the clang buildbots
from breaking when symlinking clang into llvm.

The expression evaluator fuzzer itself has been modified to prevent a
bug that occurs when running it without a target.
2022-08-04 11:47:06 -04:00
Pavel Labath b8985ba0ad [lldb] Fix arm breakages from D130985
The kernel was rejecting sizeof(struct GPR) as it was not a multiple of
8. Add a padding field to fix that.

One also wonders whether "cpsr" is right register name for aarch64.
2022-08-04 13:55:35 +02:00
Jonas Devlieghere c988c267cf
[lldb] Re-enable TestCCallingConventions on Apple Silicon
This test was disabled because clang struggled to emit a Windows calling
convention when targeting an Apple environment. This test is now showing
up as an XPASS so someone must have fixed this.
2022-08-03 20:50:05 -07:00
Slava Gurevich 5a906b70c1 [LLDB][NFC] Fix potential div by 0 "count" can be zero potentially causing div by 0
Differential Revision: https://reviews.llvm.org/D130939
2022-08-03 16:08:18 -07:00
Jonas Devlieghere 71ebcd3348
[lldb] Make LLDB resilient against failing dyld introspection SPIs
Make LLDB resilient against failing dyld introspection SPIs:

 - dyld_process_create_for_current_task
 - dyld_process_snapshot_create_for_process
 - dyld_process_snapshot_get_shared_cache

These can all fail and return a nullptr. Instead of having an assert,
which doesn't really make sense, as we have no control over whether
these calls succeed or not, bail out gracefully and use the fallback
logic.

rdar://98070414

Differential revision: https://reviews.llvm.org/D131110
2022-08-03 15:47:58 -07:00
Jonas Devlieghere 9ffcc85fbe
Revert "Revert "[lldb][modules] Disable Clang Modules in source/Host directory on macOS""
This reverts commit c7bd61d4a7 because it
breaks the underlying issue is apparently not yet resolved. This only
affects the modules build.
2022-08-03 14:39:45 -07:00
Jonas Devlieghere 2b61b770df
[lldb] Make TestModuleLoadedNotifys work with dyld from the shared cache
Make TestModuleLoadedNotifys work with a dyld from the expanded shared
cache in the DeviceSupport directory. In that case the module path is:

  ~/Library/Developer/Xcode/iOS DeviceSupport/<...>/Symbols/usr/lib/dyld

instead of just:

  /usr/lib/dyld

This makes the test pass when running against an embedded Darwin device.
2022-08-03 14:24:42 -07:00
Jonas Devlieghere 880b2128ef
[lldb] Mark TestRosetta as skipIfDarwinEmbedded
This test only makes sense on the host.
2022-08-03 14:24:37 -07:00
Adrian Prantl 11e5275cc2 Document why test is disabled on macOS Ventura
Starting with macOS 13 CoreFoundation pulls in Foundation, so we
always get the Foundation object description.

rdar://96224141

Differential Revision: https://reviews.llvm.org/D131025
2022-08-03 13:05:21 -07:00
Augusto Noronha 1f64f8bcab [lldb] Fix 'FileCheck' spelling on symtab regex tests 2022-08-03 11:57:33 -07:00
Jonas Devlieghere 0f821339da
[lldb] Add assertStopReason helper function
Add a function to make it easier to debug a test failure caused by an
unexpected stop reason. This is similar to the assertState helper that
was added in ce825e4674.

Before:

  self.assertEqual(stop_reason, lldb.eStopReasonInstrumentation)
  AssertionError: 5 != 10

After:

  self.assertStopReason(stop_reason, lldb.eStopReasonInstrumentation)
  AssertionError: signal (5) != instrumentation (10)

Differential revision: https://reviews.llvm.org/D131083
2022-08-03 11:44:13 -07:00
Walter Erquinigo 3716107934 [NFC][intel pt] Improve troubleshooting message 2022-08-03 11:34:03 -07:00
Augusto Noronha 3aef968ec3 [lldb] Allow SymbolTable regex search functions to match mangled name
It may be useful to search symbol table entries by mangled instead
of demangled names. Add this optional functionality in the SymbolTable
functions.

Differential Revision: https://reviews.llvm.org/D130803
2022-08-03 10:55:32 -07:00
Jonas Devlieghere 6a48dc092b
[lldb] Add missing newlines after LLDB_INSTRUMENT_VA
Add a newline after LLDB_INSTRUMENT_VA to match the output of lldb-instr
and keep everything consistent.
2022-08-03 10:51:16 -07:00
Michał Górny 3426fc7318 Revert "[lldb] [gdb-remote] Send interrupt packets from async thread"
This reverts commit 446b61cff4.  Of course
it does not work on Windows.
2022-08-03 19:09:35 +02:00
Michał Górny 446b61cff4 [lldb] [gdb-remote] Send interrupt packets from async thread
Refactor the mechanism for sending interrupt packets to send them
from async thread (i.e. the same thread that sends the continue packet
preceding them and that waits for the response), rather than from
the thread requesting the interrupt.  This is going to become especially
important when using the vCtrlC packet as part of the non-stop protocol,
as -- unlike the simple ^c sent in the all-stop mode -- this packet
involves an explicit reply.

Suggested by Pavel Labath in D126614.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D131075
2022-08-03 18:40:25 +02:00
Pavel Labath 69c39e2abc [lldb] Fix TestDeletedExecutable on linux
Currently, lldb-server was opening the executable file to determine the
process architecture (to differentiate between 32 and 64 bit
architecture flavours). This isn't a particularly trustworthy source of
information (the file could have been changed since the process was
started) and it is not always available (file could be deleted or
otherwise inaccessible).

Unfortunately, ptrace does not give us a direct API to access the
process architecture, but we can still infer it via some of its
responses -- given that the general purpose register set of 64-bit
applications is larger [citation needed] than the GPR set of 32-bit
ones, we can just ask for the application GPR set and check its size.

This is what this patch does.

Differential Revision: https://reviews.llvm.org/D130985
2022-08-03 15:44:19 +02:00
Walter Erquinigo d179ea12fd [NFC][trace] format source files
Cleanup formatting diff
2022-08-02 21:16:31 -07:00
Walter Erquinigo d8602bcdfa fix f9b4ea0ce9
This fixes https://lab.llvm.org/buildbot/#/builders/68/builds/37077.
2022-08-02 19:23:28 -07:00
Jakob Johnson f9b4ea0ce9 [trace] Add SBTraceCursor bindings
Add bindings for the `TraceCursor` to allow for programatic traversal of
traces.
This diff adds bindings for all public `TraceCursor` methods except
`GetHwClock` and also adds `SBTrace::CreateNewCursor`. A new unittest
has been added to TestTraceLoad.py that uses the new `SBTraceCursor` API
to test that the sequential and random access APIs of the `TraceCursor`
are equivalent.

This diff depends on D130925.

Test Plan:
`ninja lldb-dotest && ./bin/lldb-dotest -p TestTraceLoad`

Differential Revision: https://reviews.llvm.org/D130930
2022-08-02 16:55:33 -07:00
Jason Molenda 63725ebc18 [NFC] Remove no-op code from x86AssemblyInspectionEngine::jmp_to_reg_p
Slava Gurevich noticed this dead code I wrote in jmp_to_reg_p
is never executed, is duplicated, and has comments that seem to
describe the opposite behavior.  Remove the dead code that cannot
be executed.

Differential Revision: https://reviews.llvm.org/D131029
2022-08-02 16:28:10 -07:00
Jonas Devlieghere c7bd61d4a7
Revert "[lldb][modules] Disable Clang Modules in source/Host directory on macOS"
This reverts commit 7cf4ab13af as it was a
temporary workaround that's no longer needed.
2022-08-02 16:14:02 -07:00
Slava Gurevich 4502e3531f [LLDB][NFC] Fix incorrect return status Some functions always return 'false' for both success and fail return paths.
Differential Revision: https://reviews.llvm.org/D131013
2022-08-02 15:56:23 -07:00
Jakob Johnson 6cbc6e9a6d [LLDB] Add SBInstruction::GetControlFlowKind()
D128477 adds the control flow kind for `Instruction` and displays this
in the `thread trace dump instruction -k` command.

This diff exposes the control flow kind via the new
`SBInstruction::GetControlFlowKind` method.

I've expanded `TestDisassembleRawData` to test this method, but please
let me know if there are any other unittests that should also be updated.

Test Plan:
`./bin/lldb-dotest -p TestDisassembleRawData`

Differential Revision: https://reviews.llvm.org/D131005
2022-08-02 15:42:45 -07:00
Jason Molenda 318454a8e5 Inline my uuid_is_null() implementation in a header file
This either needs to be static, or forced inline, or in a separate
source file.  Given that we only have one function in this
UuidCompatibility.h, I think forced inline for the handful of uses
of it may be best.
2022-08-02 14:24:11 -07:00
Jason Molenda 96d12187b3 Allow firmware binaries to be specified only by load address
Add support to Mach-O corefiles and to live gdb remote serial protocol
connections for the corefile/remote stub to provide a list of load
addresses of binaries that should be found & loaded by lldb, and nothing
else.  lldb will try to parse the binary out of memory, and if it can
find a UUID, try to find a binary & its debug information based on the
UUID, falling back to using the memory image if it must.

A bit of code unification from three parts of lldb that were loading
individual binaries already, so there is a shared method in
DynamicLoader to handle all of the variations they were doing.

Re-landing this with a uuid_is_null() implementation added to
Utility/UuidCompatibility.h for non-Darwin systems.

Differential Revision: https://reviews.llvm.org/D130813
rdar://94249937
rdar://94249384
2022-08-02 14:14:16 -07:00
Jason Molenda 803386da2f Revert "Allow firmware binaries to be specified only by load address"
This reverts commit d8879fba88.

Debian bot failure; I included <uuid/uuid.h> to get uuid_is_null() but
don't get it there.  Will memcmp or whatever & recommit.
2022-08-02 13:53:34 -07:00
Jason Molenda d8879fba88 Allow firmware binaries to be specified only by load address
Add support to Mach-O corefiles and to live gdb remote serial protocol
connections for the corefile/remote stub to provide a list of load
addresses of binaries that should be found & loaded by lldb, and nothing
else.  lldb will try to parse the binary out of memory, and if it can
find a UUID, try to find a binary & its debug information based on the
UUID, falling back to using the memory image if it must.

A bit of code unification from three parts of lldb that were loading
individual binaries already, so there is a shared method in
DynamicLoader to handle all of the variations they were doing.

Differential Revision: https://reviews.llvm.org/D130813
rdar://94249937
rdar://94249384
2022-08-02 13:49:30 -07:00
Slava Gurevich 0a569274cb [LLDB][NFC] Fix LLDB_WATCH_TYPE_IS_VALID macro
LLDB_WATCH_TYPE_IS_VALID would always return true when validating watchpoint type
by using bitwise-or instead of bitwise-and to apply validation flags.

Differential Revision: https://reviews.llvm.org/D130972
2022-08-02 13:05:29 -07:00
Slava Gurevich d735307aa2 [LLDB][Reliability] Remove dead code.
Remove redundant code that can never execute due to preceeding logic checks in the code.

Differential Revision: https://reviews.llvm.org/D130929
2022-08-02 10:09:45 -07:00
Pavel Labath 6093a77caf [lldb] Create an enum to specify the kind of ArchSpec matching
s/true/ArchSpec::ExactMatch
s/false/ArchSpec::CompatibleMatch

Differential Revision: https://reviews.llvm.org/D121290
2022-08-02 16:20:13 +02:00
Muhammad Omair Javaid a1bf0c0894 [LLDB] Skip buildbot failures AArch64/Windows
TestInlineStepping.py is flaky while TestUseSourceCache.py fails on
Windows 11 only. Marked them skipped to make buildbot happy.
2022-08-02 16:59:12 +05:00
Martin Storsjö b7c5683fac [lldb] Silence a GCC warning about missing returns after a fully covered switch. NFC. 2022-08-02 10:57:33 +03:00
Emmmer 768e59d959 [LLDB][RISCV] Add riscv register enums
According to [RISC-V ISA Spec](https://riscv.org/wp-content/uploads/2017/05/riscv-spec-v2.2.pdf) and [riscv-v-spec](https://github.com/riscv/riscv-v-spec/blob/master/v-spec.adoc#3-vector-extension-programmers-model)

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D130899
2022-08-02 11:55:33 +08:00
Slava Gurevich 30b3911197 [LLDB][NFC][Correctness] Fix bad null check
Fix incorrect null-check logic, likely cause by copy-paste

Differential Revision: https://reviews.llvm.org/D130937
2022-08-01 14:45:26 -07:00
Jakob Johnson 3bec33b16d [trace] Replace TraceCursorUP with TraceCursorSP
The use of `std::unique_ptr` with `TraceCursor` adds unnecessary complexity to adding `SBTraceCursor` bindings
Specifically, since `TraceCursor` is an abstract class there's no clean
way to provide "deep clone" semantics for `TraceCursorUP` short of
creating a pure virtual `clone()` method (afaict).

After discussing with @wallace, we decided there is no strong reason to
favor wrapping `TraceCursor` with `std::unique_ptr` over `std::shared_ptr`, thus this diff
replaces all usages of `std::unique_ptr<TraceCursor>` with `std::shared_ptr<TraceCursor>`.

This sets the stage for future diffs to introduce `SBTraceCursor`
bindings in a more clean fashion.

Test Plan:

Differential Revision: https://reviews.llvm.org/D130925
2022-08-01 13:53:53 -07:00
Jakob Johnson 9bab358e39 [trace][intelpt] Update TraceIntelPTBundleSaver.cpp to accommodate FileSpec API changes
D130309 introduced changes to the FileSpec API which broke usages of
`GetCString()` in TraceIntelPTBundleSaver.cpp. This diff replaces usages
of `GetCString()` with `GetPath().c_str()` as suggested by D130309.

Test Plan:
Building with the trace plug-in now succeeds

Differential Revision: https://reviews.llvm.org/D130924
2022-08-01 11:52:15 -07:00
Michał Górny f8603c1f6d [lldb] [llgs] Support resuming multiple processes via vCont w/ nonstop
Support using the vCont packet to resume multiple processes
simultaneously when in non-stop mode.  The new logic now assumes that:

- actions without a thread-id or with process id of "p-1" apply to all
  debugged processes

- actions with a thread-id without process id apply to the current
  process (m_continue_process)

As with the other continue packets, it is only possible to resume
processes that are currently stopped (or stop these that are running).
It is unsupported to resume or stop individual threads of a running
process.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128989
2022-08-01 18:52:47 +02:00
Michał Górny 0806927977 [lldb] [test] Fix test_c_both_nonstop flakiness
Thanks to Pavel Labath for reporting this and suggesting a fix.

Sponsored by: The FreeBSD Foundation
2022-08-01 18:52:47 +02:00
Pavel Labath b53641cb72 [lldb] Fix flakyness in TestProcessList
If the test is too fast it can read the process list before the forked
child process actually manages to exec the process with the right
arguments.

Use our file-based synchronization primitives to ensure the child is
up-and-running before we fetch the process list.
2022-08-01 16:05:01 +02:00
Emmmer f473558647 [LLDB][RISCV] Add DWARF Registers
According to [RISC-V DWARF Specification](https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-dwarf.adoc) add RISCV DWARF Registers.

Don't worry about the difference between riscv32 and riscv64, they just have different bytes of registers.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D130686
2022-07-30 12:05:55 +08:00
Slava Gurevich f7c961cc6b [LLDB][NFC][Reliability] Fixes for int overflow and uninitialized state
Fixing potential int overflow and uninitialized variables.
These were found by Coverity static code inspection.

Differential Revision: https://reviews.llvm.org/D130795
2022-07-29 13:31:17 -07:00
Slava Gurevich 2e6b652229 [LLDB] Fix missing return value in SBBreakpointLocation::GetQueueName()
- Fix a typo in the function that never returns a significant value

- Add unit tests for the getters/setters in SBBreakpointLocation

- Verified the newly added unit test succeeds after the fix:
llvm-lit -sv  lldb/test/API/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py

Differential Revision: https://reviews.llvm.org/D130660
2022-07-28 16:08:35 -07:00
Greg Clayton dc0f452e85 Cache the value for absolute path in FileSpec.
Checking if a path is absolute can be expensive and currently the result is not cached in the FileSpec object. This patch adds caching and also code to clear the cache if the file is modified.

Differential Revision: https://reviews.llvm.org/D130396
2022-07-28 13:31:41 -07:00
Greg Clayton 529a3d87a7 [NFC] Improve FileSpec internal APIs and usage in preparation for adding caching of resolved/absolute.
Resubmission of https://reviews.llvm.org/D130309 with the 2 patches that fixed the linux buildbot, and new windows fixes.

The FileSpec APIs allow users to modify instance variables directly by getting a non const reference to the directory and filename instance variables. This makes it impossible to control all of the times the FileSpec object is modified so we can clear cached member variables like m_resolved and with an upcoming patch caching if the file is relative or absolute. This patch modifies the APIs of FileSpec so no one can modify the directory or filename instance variables directly by adding set accessors and by removing the get accessors that are non const.

Many clients were using FileSpec::GetCString(...) which returned a unique C string from a ConstString'ified version of the result of GetPath() which returned a std::string. This caused many locations to use this convenient function incorrectly and could cause many strings to be added to the constant string pool that didn't need to. Most clients were converted to using FileSpec::GetPath().c_str() when possible. Other clients were modified to use the newly renamed version of this function which returns an actualy ConstString:

ConstString FileSpec::GetPathAsConstString(bool denormalize = true) const;

This avoids the issue where people were getting an already uniqued "const char *" that came from a ConstString only to put the "const char *" back into a "ConstString" object. By returning the ConstString instead of a "const char *" clients can be more efficient with the result.

The patch:
- Removes the non const GetDirectory() and GetFilename() get accessors
- Adds set accessors to replace the above functions: SetDirectory() and SetFilename().
- Adds ClearDirectory() and ClearFilename() to replace usage of the FileSpec::GetDirectory().Clear()/FileSpec::GetFilename().Clear() call sites
- Fixed all incorrect usage of FileSpec::GetCString() to use FileSpec::GetPath().c_str() where appropriate, and updated other call sites that wanted a ConstString to use the newly returned ConstString appropriately and efficiently.

Differential Revision: https://reviews.llvm.org/D130549
2022-07-28 13:28:26 -07:00
Jonas Devlieghere ecda408178
[lldb] Read from the Rosetta shared cache with Xcode 14
Xcode 14 no longer puts the Rosetta expanded shared cache in a directory
named "16.0". Instead, it includes the real version number (e.g. 13.0),
the build string and the architecture, similar to the device support
directory names for iOS, tvOS and watchOS.

Currently, when there are multiple directories, we might end up picking
the wrong one in GetSDKDirectoryForCurrentOSVersion. The problem is that
without the build string we have no way to differentiate between
multiple directories with the same version number. This patch fixes the
problem by using GetOSBuildString which, as the name implies, returns
the build string if known.

This also adds a test for Rosetta debugging on Apple Silicon. Depending
on whether the Rosetta expanded shared cache is present, the test
ensures that there is or isn't a diagnostic about reading out of memory.

rdar://97576121

Differential revision: https://reviews.llvm.org/D130540
2022-07-27 15:26:46 -07:00
Jim Ingham 27893ff1ad Call WatchpointList::RemoveAll in Target::Destroy.
I noticed that the test TestSetWatchpoint.py was failing every so often
on macOS.  The failure was in the last assert, that after destroying the
SBTarget containing it, the SBWatchpoint was still saying it was valid.

IsValid in this case just meant the watchpoint weak pointer could be turned
into a shared pointer.  The watchpoint shared pointers have two strong references
in general, one to the "Target::m_last_created_watchpoint", and one in the
Target::m_watchpoint_list.  Target::Destroy reset the last created watchpoint
but neglected to call RemoveAll on the watchpoint list (it does the analogous
work for the internal & external breakpoint lists...)  This patch does the
equivalent cleanup for the watchpoint list.
2022-07-27 15:15:05 -07:00
Arthur Eubanks 492245d959 [lldb][NFC] Pass ParsedDWARFTypeAttributes as const reference into ParseArrayType()
Fixes a FIXME

Reviewed By: zequanwu

Differential Revision: https://reviews.llvm.org/D130504
2022-07-27 13:39:46 -07:00
Slava Gurevich 2cfcbe295a [LLDB][NFC] Fix possible resource leak
SymbolVendorPECOFF object is leaked on early return at line 110

Differential Revision: https://reviews.llvm.org/D130655
2022-07-27 13:19:13 -07:00
Jonas Devlieghere a8c3d9815e
[DebugInfo] Teach LLVM and LLDB about ptrauth in DWARF
Teach libDebugInfo (llvm-dwarfdump) and lldb about DWARF tags and
attributes for pointer authentication. These values have been emitted by
Apple clang for several releases. Although upstream LLVM doesn't emit
these values yet, we hope to upstream that part sometime soon.

Differential revision: https://reviews.llvm.org/D130215
2022-07-27 11:48:35 -07:00
Slava Gurevich 24301569f0 [LLDB][NFC][Reliability] Fix uninitialized variables from Coverity scan. Part 3
Improve LLDB reliability by fixing the following "uninitialized variables" static code inspection warnings from
scan.coverity.com/projects/llvm:

1355854, 1347549, 1316348, 1372028, 1431625,
1315634, 1315637, 1355855, 1364803, 1420505,
1420563, 1420685, 1366014, 1203966, 1204029,
1204031, 1204032, 1328411, 1325969, 1325968,
1374921, 1094809

Differential Revision: https://reviews.llvm.org/D130602
2022-07-27 10:39:49 -07:00
Pavel Labath 1400a3cb8d [lldb] Always use APFloat for FP dumping
The DumpDataExtractor function had two branches for printing floating
point values. One branch (APFloat) was used if we had a Target object
around and could query it for the appropriate semantics. If we didn't
have a Target, we used host operations to read and format the value.

This patch changes second path to use APFloat as well. To make it work,
I pick reasonable defaults for different byte size. Notably, I did not
include x87 long double in that list (as it is ambibuous and
architecture-specific). This exposed a bug where we were printing
register values using the target-less branch, even though the registers
definitely belong to a target, and we had it available. Fixing this
prompted the update of several tests for register values due to slightly
different floating point outputs.

The most dubious aspect of this patch is the change in
TypeSystemClang::GetFloatTypeSemantics to recognize `10` as a valid size
for x87 long double. This was necessary because because sizeof(long
double) on x86_64 is 16 even though it only holds 10 bytes of useful
data. This generalizes the hackaround present in the target-free branch
of the dumping function.

Differential Revision: https://reviews.llvm.org/D129750
2022-07-27 14:30:35 +02:00
Jakob Johnson dde3cf2e83 [trace] Add instruction control flow kind to JSON trace dumper's output
D128477 adds a '-k' flag which displays each instruction's control flow in the `thread trace dump instructions` command's non-json  output (ie no '-j' or '-J' flag)
This diff adds the instruction control flow kind to the `thread trace dump instructions` command's JSON output (ie '-j' or '-J' flag)

Test Plan:
Confirm "controlFlowKind" is present in JSON when '-k' is provided
```
(lldb) thread trace dump instructions -J -k
[
  {                                                                                                                                                                                                                                                                                 [141/1952]
    "id": 7755,
    "loadAddress": "0x400868",
    "module": "test.out",
    "symbol": "main",
    "mnemonic": "jmp",
    "controlFlowKind": "jump",
    "source": "/home/jakobjohnson/jakob-dev/test.cpp",
    "line": 41,
    "column": 29
  },
  {
    "id": 7753,
    "loadAddress": "0x7ffff7b54dab",
    "module": "libstdc++.so.6",
    "symbol": "std::ostream::flush()",
    "mnemonic": "retq",
    "controlFlowKind": "return"
  },
  {
    "id": 7752,
    "loadAddress": "0x7ffff7b54daa",
    "module": "libstdc++.so.6",
    "symbol": "std::ostream::flush()",
    "mnemonic": "popq",
    "controlFlowKind": "other"
  },
  ...
]
```
Confirm "controlFlowKind" is not present when '-k' isn't provided
```
(lldb) thread trace dump instructions -J
[
  {
    "id": 7755,
    "loadAddress": "0x400868",
    "module": "test.out",
    "symbol": "main",
    "mnemonic": "jmp",
    "source": "/home/jakobjohnson/jakob-dev/test.cpp",
    "line": 41,
    "column": 29
  },
  {
    "id": 7753,
    "loadAddress": "0x7ffff7b54dab",
    "module": "libstdc++.so.6",
    "symbol": "std::ostream::flush()",
    "mnemonic": "retq"
  },
  {
    "id": 7752,
    "loadAddress": "0x7ffff7b54daa",
    "module": "libstdc++.so.6",
    "symbol": "std::ostream::flush()",
    "mnemonic": "popq"
  },
```

Differential Revision: https://reviews.llvm.org/D130607
2022-07-27 05:23:59 -07:00
Matheus Izvekov 15f3cd6bfc
[clang] Implement ElaboratedType sugaring for types written bare
Without this patch, clang will not wrap in an ElaboratedType node types written
without a keyword and nested name qualifier, which goes against the intent that
we should produce an AST which retains enough details to recover how things are
written.

The lack of this sugar is incompatible with the intent of the type printer
default policy, which is to print types as written, but to fall back and print
them fully qualified when they are desugared.

An ElaboratedTypeLoc without keyword / NNS uses no storage by itself, but still
requires pointer alignment due to pre-existing bug in the TypeLoc buffer
handling.

---

Troubleshooting list to deal with any breakage seen with this patch:

1) The most likely effect one would see by this patch is a change in how
   a type is printed. The type printer will, by design and default,
   print types as written. There are customization options there, but
   not that many, and they mainly apply to how to print a type that we
   somehow failed to track how it was written. This patch fixes a
   problem where we failed to distinguish between a type
   that was written without any elaborated-type qualifiers,
   such as a 'struct'/'class' tags and name spacifiers such as 'std::',
   and one that has been stripped of any 'metadata' that identifies such,
   the so called canonical types.
   Example:
   ```
   namespace foo {
     struct A {};
     A a;
   };
   ```
   If one were to print the type of `foo::a`, prior to this patch, this
   would result in `foo::A`. This is how the type printer would have,
   by default, printed the canonical type of A as well.
   As soon as you add any name qualifiers to A, the type printer would
   suddenly start accurately printing the type as written. This patch
   will make it print it accurately even when written without
   qualifiers, so we will just print `A` for the initial example, as
   the user did not really write that `foo::` namespace qualifier.

2) This patch could expose a bug in some AST matcher. Matching types
   is harder to get right when there is sugar involved. For example,
   if you want to match a type against being a pointer to some type A,
   then you have to account for getting a type that is sugar for a
   pointer to A, or being a pointer to sugar to A, or both! Usually
   you would get the second part wrong, and this would work for a
   very simple test where you don't use any name qualifiers, but
   you would discover is broken when you do. The usual fix is to
   either use the matcher which strips sugar, which is annoying
   to use as for example if you match an N level pointer, you have
   to put N+1 such matchers in there, beginning to end and between
   all those levels. But in a lot of cases, if the property you want
   to match is present in the canonical type, it's easier and faster
   to just match on that... This goes with what is said in 1), if
   you want to match against the name of a type, and you want
   the name string to be something stable, perhaps matching on
   the name of the canonical type is the better choice.

3) This patch could expose a bug in how you get the source range of some
   TypeLoc. For some reason, a lot of code is using getLocalSourceRange(),
   which only looks at the given TypeLoc node. This patch introduces a new,
   and more common TypeLoc node which contains no source locations on itself.
   This is not an inovation here, and some other, more rare TypeLoc nodes could
   also have this property, but if you use getLocalSourceRange on them, it's not
   going to return any valid locations, because it doesn't have any. The right fix
   here is to always use getSourceRange() or getBeginLoc/getEndLoc which will dive
   into the inner TypeLoc to get the source range if it doesn't find it on the
   top level one. You can use getLocalSourceRange if you are really into
   micro-optimizations and you have some outside knowledge that the TypeLocs you are
   dealing with will always include some source location.

4) Exposed a bug somewhere in the use of the normal clang type class API, where you
   have some type, you want to see if that type is some particular kind, you try a
   `dyn_cast` such as `dyn_cast<TypedefType>` and that fails because now you have an
   ElaboratedType which has a TypeDefType inside of it, which is what you wanted to match.
   Again, like 2), this would usually have been tested poorly with some simple tests with
   no qualifications, and would have been broken had there been any other kind of type sugar,
   be it an ElaboratedType or a TemplateSpecializationType or a SubstTemplateParmType.
   The usual fix here is to use `getAs` instead of `dyn_cast`, which will look deeper
   into the type. Or use `getAsAdjusted` when dealing with TypeLocs.
   For some reason the API is inconsistent there and on TypeLocs getAs behaves like a dyn_cast.

5) It could be a bug in this patch perhaps.

Let me know if you need any help!

Signed-off-by: Matheus Izvekov <mizvekov@gmail.com>

Differential Revision: https://reviews.llvm.org/D112374
2022-07-27 11:10:54 +02:00
Jakob Johnson d36ae4952d Add string conversion for InstructionControlFlowKind enum
Refactor the string conversion of the `lldb::InstructionControlFlowKind` enum out
of `Instruction::Dump` to enable reuse of this logic by the
JSON TraceDumper (to be implemented in separate diff).

Will coordinate the landing of this change with D130320 since there will be a minor merge conflict between
these changes.

Test Plan:
Run unittests
```
> ninja check-lldb
[4/5] Running lldb unit test suite

Testing Time: 10.13s
  Passed: 1084
```

Verify '-k' flag's output
```
(lldb) thread trace dump instructions -k
thread #1: tid = 1375377
  libstdc++.so.6`std::ostream::flush() + 43
    7048: 0x00007ffff7b54dab    return      retq
    7047: 0x00007ffff7b54daa    other       popq   %rbx
    7046: 0x00007ffff7b54da7    other       movq   %rbx, %rax
    7045: 0x00007ffff7b54da5    cond jump   je     0x11adb0                  ; <+48>
    7044: 0x00007ffff7b54da2    other       cmpl   $-0x1, %eax
  libc.so.6`_IO_fflush + 249
    7043: 0x00007ffff7161729    return      retq
    7042: 0x00007ffff7161728    other       popq   %rbp
    7041: 0x00007ffff7161727    other       popq   %rbx
    7040: 0x00007ffff7161725    other       movl   %edx, %eax
    7039: 0x00007ffff7161721    other       addq   $0x8, %rsp
    7038: 0x00007ffff7161709    cond jump   je     0x87721                   ; <+241>
    7037: 0x00007ffff7161707    other       decl   (%rsi)
    7036: 0x00007ffff71616fe    cond jump   je     0x87707                   ; <+215>
    7035: 0x00007ffff71616f7    other       cmpl   $0x0, 0x33de92(%rip)      ; __libc_multiple_threads
    7034: 0x00007ffff71616ef    other       movq   $0x0, 0x8(%rsi)
    7033: 0x00007ffff71616ed    cond jump   jne    0x87721                   ; <+241>
    7032: 0x00007ffff71616e9    other       subl   $0x1, 0x4(%rsi)
    7031: 0x00007ffff71616e2    other       movq   0x88(%rbx), %rsi
    7030: 0x00007ffff71616e0    cond jump   jne    0x87721                   ; <+241>
    7029: 0x00007ffff71616da    other       testl  $0x8000, (%rbx)           ; imm = 0x8000
```

Differential Revision: https://reviews.llvm.org/D130580
2022-07-26 16:09:57 -07:00
Argyrios Kyrtzidis c5ddacb3b6 [lldb/ClangExpressionParser] Fix compiler error due to `clang::CreateLLVMCodeGen()` API change 2022-07-26 14:05:22 -07:00
Augusto Noronha 5ee910fef5 [lldb] Disable TestStackFromStdModule.py
TestStackFromStdModule.py started failing due to f4fb72e6d4
(https://reviews.llvm.org/D128146), with a clang assertion failure:
assert(isa<InjectedClassNameType>(Decl->TypeForDecl))
2022-07-26 13:02:51 -07:00
Walter Erquinigo 0538e5431a Move GetControlFlowKind's logic to DisassemblerLLVMC.cpp
This diff move the logic of `GetControlFlowKind()` from Disassembler.cpp to DisassemblerLLVMC.cpp.
Here's details:
- Actual logic of GetControlFlowKind() move to `DisassemblerLLVMC.cpp`, and we can check underlying architecture using `DisassemblerScope` there.
- With this change, passing 'triple' to `GetControlFlowKind()` is no more required.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D130320
2022-07-26 12:05:23 -07:00
Walter Erquinigo 4f676c2599 [trace][intel pt] Introduce wall clock time for each trace item
- Decouple TSCs from trace items
- Turn TSCs into events just like CPUs. The new name is HW clock tick, wich could be reused by other vendors.
- Add a GetWallTime that returns the wall time that the trace plug-in can infer for each trace item.
- For intel pt, we are doing the following interpolation: if an instruction takes less than 1 TSC, we use that duration, otherwise, we assume the instruction took 1 TSC. This helps us avoid having to handle context switches, changes to kernel, idle times, decoding errors, etc. We are just trying to show some approximation and not the real data. For the real data, TSCs are the way to go. Besides that, we are making sure that no two trace items will give the same interpolation value. Finally, we are using as time 0 the time at which tracing started.

Sample output:

```
(lldb) r
Process 750047 launched: '/home/wallace/a.out' (x86_64)
Process 750047 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 1.1
    frame #0: 0x0000000000402479 a.out`main at main.cpp:29:20
   26   };
   27
   28   int main() {
-> 29     std::vector<int> vvv;
   30     for (int i = 0; i < 100; i++)
   31       vvv.push_back(i);
   32
(lldb) process trace start -s 64kb -t --per-cpu
(lldb) b 60
Breakpoint 2: where = a.out`main + 1689 at main.cpp:60:23, address = 0x0000000000402afe
(lldb) c
Process 750047 resuming
Process 750047 stopped
* thread #1, name = 'a.out', stop reason = breakpoint 2.1
    frame #0: 0x0000000000402afe a.out`main at main.cpp:60:23
   57     map<int, int> m;
   58     m[3] = 4;
   59
-> 60     map<string, string> m2;
   61     m2["5"] = "6";
   62
   63     std::vector<std::string> vs = {"2", "3"};
(lldb) thread trace dump instructions -t -f -e thread #1: tid = 750047
    0: [379567.000 ns] (event) HW clock tick [48599428476224707]
    1: [379569.000 ns] (event) CPU core changed [new CPU=2]
    2: [390487.000 ns] (event) HW clock tick [48599428476246495]
    3: [1602508.000 ns] (event) HW clock tick [48599428478664855]
    4: [1662745.000 ns] (event) HW clock tick [48599428478785046]
  libc.so.6`malloc
    5: [1662746.995 ns] 0x00007ffff7176660    endbr64
    6: [1662748.991 ns] 0x00007ffff7176664    movq   0x32387d(%rip), %rax      ;  + 408
    7: [1662750.986 ns] 0x00007ffff717666b    pushq  %r12
    8: [1662752.981 ns] 0x00007ffff717666d    pushq  %rbp
    9: [1662754.977 ns] 0x00007ffff717666e    pushq  %rbx
    10: [1662756.972 ns] 0x00007ffff717666f    movq   (%rax), %rax
    11: [1662758.967 ns] 0x00007ffff7176672    testq  %rax, %rax
    12: [1662760.963 ns] 0x00007ffff7176675    jne    0x9c7e0                   ; <+384>
    13: [1662762.958 ns] 0x00007ffff717667b    leaq   0x17(%rdi), %rax
    14: [1662764.953 ns] 0x00007ffff717667f    cmpq   $0x1f, %rax
    15: [1662766.949 ns] 0x00007ffff7176683    ja     0x9c730                   ; <+208>
    16: [1662768.944 ns] 0x00007ffff7176730    andq   $-0x10, %rax
    17: [1662770.939 ns] 0x00007ffff7176734    cmpq   $-0x41, %rax
    18: [1662772.935 ns] 0x00007ffff7176738    seta   %dl
    19: [1662774.930 ns] 0x00007ffff717673b    jmp    0x9c690                   ; <+48>
    20: [1662776.925 ns] 0x00007ffff7176690    cmpq   %rdi, %rax
    21: [1662778.921 ns] 0x00007ffff7176693    jb     0x9c7b0                   ; <+336>
    22: [1662780.916 ns] 0x00007ffff7176699    testb  %dl, %dl
    23: [1662782.911 ns] 0x00007ffff717669b    jne    0x9c7b0                   ; <+336>
    24: [1662784.906 ns] 0x00007ffff71766a1    movq   0x3236c0(%rip), %r12      ;  + 24
(lldb) thread trace dump instructions -t -f -e -J -c 4
[
  {
    "id": 0,
    "timestamp_ns": "379567.000000",
    "event": "HW clock tick",
    "hwClock": 48599428476224707
  },
  {
    "id": 1,
    "timestamp_ns": "379569.000000",
    "event": "CPU core changed",
    "cpuId": 2
  },
  {
    "id": 2,
    "timestamp_ns": "390487.000000",
    "event": "HW clock tick",
    "hwClock": 48599428476246495
  },
  {
    "id": 3,
    "timestamp_ns": "1602508.000000",
    "event": "HW clock tick",
    "hwClock": 48599428478664855
  },
  {
    "id": 4,
    "timestamp_ns": "1662745.000000",
    "event": "HW clock tick",
    "hwClock": 48599428478785046
  },
  {
    "id": 5,
    "timestamp_ns": "1662746.995324",
    "loadAddress": "0x7ffff7176660",
    "module": "libc.so.6",
    "symbol": "malloc",
    "mnemonic": "endbr64"
  },
  {
    "id": 6,
    "timestamp_ns": "1662748.990648",
    "loadAddress": "0x7ffff7176664",
    "module": "libc.so.6",
    "symbol": "malloc",
    "mnemonic": "movq"
  },
  {
    "id": 7,
    "timestamp_ns": "1662750.985972",
    "loadAddress": "0x7ffff717666b",
    "module": "libc.so.6",
    "symbol": "malloc",
    "mnemonic": "pushq"
  },
  {
    "id": 8,
    "timestamp_ns": "1662752.981296",
    "loadAddress": "0x7ffff717666d",
    "module": "libc.so.6",
    "symbol": "malloc",
    "mnemonic": "pushq"
  }
]
```

Differential Revision: https://reviews.llvm.org/D130054
2022-07-26 12:05:23 -07:00
Jim Ingham 8b7775a472 StackFrame::GetValueObjectForFrameVariable holds the StackFrame lock too long.
This can cause a deadlock if other threads use the common pattern of
"lock the StackFrameList, get a frame, lock the StackFrame."

Differential Revision: https://reviews.llvm.org/D130524
2022-07-26 10:13:19 -07:00
Michael Buch 0a412b3505 [LLDB][ClangExpression] Prevent nullptr namespace map access during logging
Some codepaths lead to `namespace_map == nullptr` when we get to
`ClangASTSource::FindCompleteType`. This occurred while debugging
an lldb session that had `settings set target.import-std-module true`.

In that case, with `LLDBLog::Expressions` logging enabled, we would
dereference a `nullptr` and crash.

This commit moves the logging until after we check for `nullptr`.

**Testing**

* Fixed the specific crash I was seeing while debugging an `lldb`
  session with `import-std-module` enabled.

Differential Revision: https://reviews.llvm.org/D130561
2022-07-26 15:47:35 +01:00
David Spickett d0479cb290 [lldb][ARM] Use portable printf tokens for 64 bit types
Fixes some warnings in the 32 bit build.
2022-07-26 09:12:57 +00:00
David Spickett 10c2bab50e [lldb][ARM] Add tests for vpush/vpop D registers
Previously we just checked via S regs and were not checking
memory content after pushes.

The vpush test confirms that the fix in https://reviews.llvm.org/D130307
is working.

Memory will only be checked if an "after" state is provided.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D130468
2022-07-26 08:41:24 +00:00
David Spickett c4b6e5f950 [lldb][ARM] Misc improvements to TestEmulations
* Look for files that end width arm/thumb.dat,
  meaning we don't try to run, for example, vim swap files.
* Print the name of the test that failed.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D130467
2022-07-26 08:31:55 +00:00
David Spickett 3ebd541944 [lldb][ARM] Print mismatched registers in emulation tests
Also correct the test failed message. It implies that what
it's done is compare the 'before' and 'ater' states from the
test input.

Except that that's the whole point of the test, that the state changes.
It should tell you that it compared the result of the emulation to the
'after'.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D130464
2022-07-26 08:28:27 +00:00
David Spickett 290c4bc7be [LLDB][ARM] Generalise adding register state in emulation tests and add D registers
Since some s and d registers overlap we will error if we find both.
This prevents you overwriting one with the other in a test case.

Reviewed By: clayborg

Differential Revision: https://reviews.llvm.org/D130462
2022-07-26 08:22:26 +00:00
David Spickett 2f9fa9ef53 [lldb][AArch64] Add support for memory tags in core files
This teaches ProcessElfCore to recognise the MTE tag segments.

https://www.kernel.org/doc/html/latest/arm64/memory-tagging-extension.html#core-dump-support

These segments contain all the tags for a matching memory segment
which will have the same size in virtual address terms. In real terms
it's 2 tags per byte so the data in the segment is much smaller.

Since MTE is the only tag type supported I have hardcoded some
things to those values. We could and should support more formats
as they appear but doing so now would leave code untested until that
happens.

A few things to note:
* /proc/pid/smaps is not in the core file, only the details you have
  in "maps". Meaning we mark a region tagged only if it has a tag segment.
* A core file supports memory tagging if it has at least 1 memory
  tag segment, there is no other flag we can check to tell if memory
  tagging was enabled. (unlike a live process that can support memory
  tagging even if there are currently no tagged memory regions)

Tests have been added at the commands level for a core file with
mte and without.

There is a lot of overlap between the "memory tag read" tests here and the unit tests for
MemoryTagManagerAArch64MTE::UnpackTagsFromCoreFileSegment, but I think it's
worth keeping to check ProcessElfCore doesn't cause an assert.

Depends on D129487

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D129489
2022-07-26 08:46:36 +01:00
Slava Gurevich e80dbfddc5 [LLDB][Reliability] Fix register value unpacking
Fix incorrect direction for bit-shifting.

Coverity warning 1355603 (scan.coverity.com)

Differential Revision: https://reviews.llvm.org/D130307
2022-07-26 00:22:40 -07:00
Slava Gurevich 4871dfc64e [LLDB][NFC][Reliability] Fix uninitialized variables from Coverity scan. Part 2
Improve LLDB reliability by fixing the following "uninitialized variables" static code inspection warnings from
scan.coverity.com:

1476275, 1274012, 1455035, 1364789, 1454282
1467483, 1406152, 1406255, 1454837, 1454416
1467446, 1462022, 1461909, 1420566, 1327228
1367767, 1431254, 1467299, 1312678, 1431780
1454731, 1490403

Differential Revision: https://reviews.llvm.org/D130528
2022-07-25 20:52:45 -07:00
Slava Gurevich 9877159dd6 Revert "[LLDB][NFC][Reliability] Fix uninitialized variables from Coverity scan. Part 2"
This reverts commit b9aedd94e6.
2022-07-25 18:23:19 -07:00
Slava Gurevich b9aedd94e6 [LLDB][NFC][Reliability] Fix uninitialized variables from Coverity scan. Part 2
Improve LLDB reliability by fixing the following "uninitialized variables" static code inspection warnings from
scan.coverity.com:

1476275, 1274012, 1455035, 1364789, 1454282
1467483, 1406152, 1406255, 1454837, 1454416
1467446, 1462022, 1461909, 1420566, 1327228
1367767, 1431254, 1467299, 1312678, 1431780
1454731, 1490403

Differential Revision: https://reviews.llvm.org/D130528
2022-07-25 16:40:57 -07:00
Michał Górny 8068751189 [lldb] [gdb-remote] Refactor killing process and move it to client
Refactor the code responsible for sending the "k" packet and move it
into GDBRemoteCommunicationClient::KillProcess() method.  This is part
of refactoring to enable multiprocess support in the client,
and to support using the vKill packet instead.

As part of the refactoring, the following functional changes apply:

- Some redundant logging has been removed, as any failures are returned
  via exit_string anyway.

- SetLastStopPacket() is no longer called.  It is used only to populate
  the thread list, and since the process has just exited and we're
  terminating the process instance, there's really no reason to set it.

- On successful kill, exit_string is set to "killed", to clearly
  indicate that the process has terminated on our request rather than
  on its own.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D130340
2022-07-25 18:43:32 +02:00
Jonas Devlieghere 52465dc178
[lldb] Make compiler-rt an optional LLDB test dependency
Make compiler-rt an LLDB test dependency if the corresponding target
exists. Similarly we already have `asan` and `tsan` as optional test
dependencies, but we need the `compiler-rt` target when enabling
compiler-rt trough LLVM_ENABLE_RUNTIMES.
2022-07-25 09:28:56 -07:00
David Spickett 91098fec96 [lldb][AArch64] Use macro for unused var without asserts enabled
82d4f39f34 marked an unused
var of mine (thanks Dmitri Gribenko!). Which reminded me lldb has
a macro just for that purpose.
2022-07-25 15:14:49 +00:00
Dmitri Gribenko 82d4f39f34 [lldb][AArch64] Fix an unused variable warning in release builds. NFC 2022-07-25 16:58:03 +02:00
David Spickett 883b0d5b7f [lldb][AArch64] Add UnpackTagsFromCoreFileSegment to MemoryTagManager
This is the first part of support for reading MTE tags from Linux
core files. The format is documented here:
https://www.kernel.org/doc/html/latest/arm64/memory-tagging-extension.html#core-dump-support

This patch adds a method to unpack from the format the core
file uses, which is different to the one chosen for GDB packets.

MemoryTagManagerAArch64MTE is not tied one OS so another OS
might choose a different format in future. However, infrastructure
to handle that would go untested until then so I've chosen not to
attempt to handle that.

Reviewed By: omjavaid

Differential Revision: https://reviews.llvm.org/D129487
2022-07-25 15:51:36 +01:00
David Spickett ae8a6602fb [lldb][ARM/AArch64] Use sys/uio.h instead of socket.h in native register context
We only want iovec and uio.h is just that without a lot
of other stuff. Saves me wondering why this code might
want to open sockets.

https://pubs.opengroup.org/onlinepubs/007904975/basedefs/sys/uio.h.html
2022-07-25 12:35:57 +00:00
Kazu Hirata acf648b5e9 Use llvm::less_first and llvm::less_second (NFC) 2022-07-24 16:21:29 -07:00
Kazu Hirata 1d9231de70 [lldb] Remove redundant member initialization (NFC)
Identified with readability-redundant-member-init.
2022-07-24 12:27:09 -07:00
Kazu Hirata 4f8a2194c9 [lldb] Use nullptr instead of NULL (NFC)
Identified with modernize-use-nullptr.
2022-07-24 12:27:08 -07:00
Kazu Hirata 559463e94e [lldb] Use true instead of 0 (NFC)
Identified with modernize-use-bool-literals.
2022-07-24 12:27:06 -07:00
Augusto Noronha 2622c5e212 [lldb] Adapt lldb tests to changes in 71cdb8c6f1 2022-07-23 15:37:26 -07:00
Nico Weber 1b4b12a340 Revert "[NFC] Improve FileSpec internal APIs and usage in preparation for adding caching of resolved/absolute." and follow-ups
This reverts commit 9429b67b8e.

It broke the build on Windows, see comments on https://reviews.llvm.org/D130309

It also reverts these follow-ups:

Revert "Fix buildbot breakage after https://reviews.llvm.org/D130309."
This reverts commit f959d815f4.

Revert "Fix buildbot breakage after https://reviews.llvm.org/D130309."
This reverts commit 0bbce7a4c2.

Revert "Cache the value for absolute path in FileSpec."
This reverts commit dabe877248.
2022-07-23 12:35:48 -04:00
Dmitri Gribenko cd9a5cfd2e Use the range-based overload of llvm::sort where possible
Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D130403
2022-07-23 15:13:25 +02:00
Augusto Noronha c18304e600 [lldb] Remote accidental logs left in TestGuiExpandThreadsTree 2022-07-22 16:06:49 -07:00
Augusto Noronha 3b8a1cc38a [lldb] Disable TestGuiExpandThreadsTree 2022-07-22 16:00:51 -07:00
Med Ismail Bennani d959324e1e Revert "[lldb/Fuzzer] Add fuzzer for expression evaluator"
This reverts commit b797834748, since it
breaks building Clang: https://reviews.llvm.org/D129377
2022-07-22 15:24:40 -07:00
Chelsea Cassanova b797834748 [lldb/Fuzzer] Add fuzzer for expression evaluator
This commit adds a fuzzer for LLDB's expression evaluator.
The fuzzer takes a different approach than the current fuzzers
present, and uses an approach that is currently being used for
clang fuzzers.

Instead of fuzzing the evaluator with randomly mutated
characters, protobufs are used to generate a subset of C++. This
is then converted to valid C++ code and sent to the expression
evaluator. In addition, libprotobuf_mutator is used to mutate
the fuzzer's inputs from valid C++ code to valid C++ code, rather
than mutating from valid code to total nonsense.

Differential revision: https://reviews.llvm.org/D129377
2022-07-22 17:32:00 -04:00
Greg Clayton dabe877248 Cache the value for absolute path in FileSpec.
Checking if a path is absolute can be expensive and currently the result is not cached in the FileSpec object. This patch adds caching and also code to clear the cache if the file is modified.

Differential Revision: https://reviews.llvm.org/D130396
2022-07-22 14:04:52 -07:00
Greg Clayton 0bbce7a4c2 Fix buildbot breakage after https://reviews.llvm.org/D130309. 2022-07-22 13:59:06 -07:00
Greg Clayton f959d815f4 Fix buildbot breakage after https://reviews.llvm.org/D130309. 2022-07-22 13:24:26 -07:00
Greg Clayton 9429b67b8e [NFC] Improve FileSpec internal APIs and usage in preparation for adding caching of resolved/absolute.
The FileSpect APIs allow users to modify instance variables directly by getting a non const reference to the directory and filename instance variables. This makes it impossibly to control all of the times the FileSpec object is modified so we can clear the cache. This patch modifies the APIs of FileSpec so no one can modify the directory or filename directly by adding set accessors and by removing the get accessors that are non const.

Many clients were using FileSpec::GetCString(...) which returned a unique C string from a ConstString'ified version of the result of GetPath() which returned a std::string. This caused many locations to use this convenient function incorrectly and could cause many strings to be added to the constant string pool that didn't need to. Most clients were converted to using FileSpec::GetPath().c_str() when possible. Other clients were modified to use the newly renamed version of this function which returns an actualy ConstString:
    ConstString FileSpec::GetPathAsConstString(bool denormalize = true) const;

This avoids the issue where people were getting an already uniqued "const char *" that came from a ConstString only to put the "const char *" back into a "ConstString" object. By returning the ConstString instead of a "const char *" clients can be more efficient with the result.

The patch:
- Removes the non const GetDirectory() and GetFilename() get accessors
- Adds set accessors to replace the above functions: SetDirectory() and SetFilename().
- Adds ClearDirectory() and ClearFilename() to replace usage of the FileSpec::GetDirectory().Clear()/FileSpec::GetFilename().Clear() call sites
- Fixed all incorrect usage of FileSpec::GetCString() to use FileSpec::GetPath().c_str() where appropriate, and updated other call sites that wanted a ConstString to use the newly returned ConstString appropriately and efficiently.

Differential Revision: https://reviews.llvm.org/D130309
2022-07-22 10:12:31 -07:00
David Spickett 1ac12a5177 [lldb][ARM] Invert emulation test assert message
Previously you got:
AssertionError: False is not True : Emulation test succeeded.

Which is a bit of a head scratcher. The message is used when
the test fails, not when it succeeds.
2022-07-22 09:35:30 +00:00
Andy Yankovsky 5c39c31a99 [lldb] Handle jumping to the end in DW_OP_skip/DW_OP_bra
DW_OP_skip/DW_OP_bra can move offset to the end of the data, which means that this was the last instruction to execute and the interpreter should terminate.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D130285
2022-07-22 09:22:40 +00:00
Michael Buch 8184b252cd [LLDB][ClangExpression] Allow expression evaluation from within C++ Lambdas
This patch adds support for evaluating expressions which reference
a captured `this` from within the context of a C++ lambda expression.
Currently LLDB doesn't provide Clang with enough information to
determine that we're inside a lambda expression and are allowed to
access variables on a captured `this`; instead Clang simply fails
to parse the expression.

There are two problems to solve here:
1. Make sure `clang::Sema` doesn't reject the expression due to an
illegal member access.
2. Materialize all the captured variables/member variables required
to evaluate the expression.

To address (1), we currently import the outer structure's AST context
onto `$__lldb_class`, making the `contextClass` and the `NamingClass`
match, a requirement by `clang::Sema::BuildPossibleImplicitMemberExpr`.

To address (2), we inject all captured variables as locals into the
expression source code.

**Testing**

* Added API test
2022-07-22 08:02:09 +01:00
Michael Buch 317c8bf84d [LLDB][Expression] Allow instantiation of IR Entity from ValueObject
This is required in preparation for the follow-up patch which adds
support for evaluating expressions from within C++ lambdas. In such
cases we need to materialize variables which are not part of the
current frame but instead are ivars on a 'this' pointer of the current
frame.
2022-07-22 08:02:08 +01:00
Michael Buch fcf4e252f4 [LLDB][NFC] Create variable for hardcoded alignment/size constants in materializer 2022-07-22 08:02:07 +01:00
Slava Gurevich 98186def3f [LLDB][Reliability] Fix accessing invalid iterator
Using invalidated vector iterator is at best a UB and could crash depending on STL implementation.
Fixing via minimal changes to preserve the existing code style.

Coverity warning 1454828  (scan.coverity.com)

Differential Revision: https://reviews.llvm.org/D130312
2022-07-21 17:39:11 -07:00
Jorge Gorbe Moya fa3a2e611d [lldb][NFCI] Refactor regex filtering logic in CommandObjectTypeFormatterList
Extract a bit of copy/pasted regex filtering logic into a separate
function and simplify it a little bit.

Differential Revision: https://reviews.llvm.org/D130219
2022-07-21 09:22:40 -07:00