Commit Graph

27269 Commits

Author SHA1 Message Date
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
Michał Górny b61b8efcf3 [lldb] [gdb-remote] Fix process ID after following forked child
Update the process ID after handling fork/vfork to ensure that
the process plugin reports the correct PID immediately.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D130037
2022-07-21 17:11:38 +02:00
Pavel Labath cd18e2ea3f [lldb/test] Fix flakyness in TestNonStop.test_stdio
The test was assuming that the output will come in two messages. The
truth is that it will come in **at least** two messages.
2022-07-21 16:53:13 +02:00
Michael Buch 140bcd369b [LLDB][ClangExpression] Fix initialization of static enum alias members
`IntegerLiteral::Create` operates on integer types. For that reason
when we parse DWARF into an AST, when we encounter a constant
initialized enum member variable, we try to determine the underlying
integer type before creating the `IntegerLiteral`. However, we
currently don't desugar the type and for enum typedefs
`dyn_cast<EnumType>` fails. In debug builds this triggers following
assert:

```
Assertion failed: (type->isIntegerType() && "Illegal type in IntegerLiteral"), function IntegerLiteral, file Expr.cpp, line 892
```

This patch turns the `dyn_cast<EnumType>` into a `getAs<EnumType>`
which `dyn_cast`s the canonical type, allowing us to get to the
underlying integer type.

**Testing**

* API test
* Manual repro is fixed

Differential Revision: https://reviews.llvm.org/D130213
2022-07-21 14:23:41 +01:00
Michael Buch 6703812688 [LLDB][DataFormatter] Add support for std::__map_const_iterator
This patch adds support for formatting `std::map::const_iterator`.
It's just a matter of adding `const_` to the existing regex.

**Testing**

* Added test case to existing API tests

Differential Revision: https://reviews.llvm.org/D129962
2022-07-21 14:21:12 +01:00
Slava Gurevich 459cfa5e94 [LLDB][NFC][Reliability] Fix uninitialized variables from Coverity scan
Improve LLDB reliability by fixing the following "uninitialized variables" static code inspection warnings from
scan.coverity.com:

1094796 1095721 1095728 1095737 1095741
1095756 1095779 1095789 1095805 1214552
1229457 1232475 1274006 1274010 1293427
1364800 1364802 1364804 1364812 1364816
1374902 1374909 1384975 1399312 1420451
1431704 1454230 1454554 1454615 1454579
1454594 1454832 1457759 1458696 1461909
1467658 1487814 1487830 1487845

Differential Revision: https://reviews.llvm.org/D130098
2022-07-20 14:50:48 -07:00
Kazu Hirata 360c1111e3 Use llvm::is_contained (NFC) 2022-07-20 09:09:19 -07:00
Zequan Wu b8cf916b89 [LLDB][NativePDB] Add MSInheritanceAttr when creating pointer type that is a pointer to member.
Differential Revision: https://reviews.llvm.org/D129807
2022-07-19 15:36:35 -07:00
Jason Molenda 2149455cdc Update docs to note lzfse open source implementation 2022-07-19 01:40:40 -07:00
Jim Ingham 83fab8cee9 Revert "Make hit point counts reliable for architectures that stop before evaluation."
This reverts commit 5778ada8e5.

The watchpoint tests all stall on aarch64-ubuntu bots.  Reverting till I can
get my hands on an system to test this out.
2022-07-18 17:38:43 -07:00
Jim Ingham 4f5707e743 Revert "This is a followup to https://reviews.llvm.org/D129814"
This reverts commit 555ae5b8f5.

Apparently, there's something different about how Linux ARM handles watchpoints,
as all the watchpoint tests seem to stall on the Ubuntu aarch64 bots.

Reverting till I can get my hands on a linux system and see what is
wrong.
2022-07-18 17:37:13 -07:00
Jim Ingham 555ae5b8f5 This is a followup to https://reviews.llvm.org/D129814
That was causing hit counts to be double-counted on x86_64 Linux.
It looks like StopInfoWatchpoint::ShouldStopSynchronous gets called
twice for a give stop on Linux (not on Darwin).  I had taken out the
"have I been called already" check when I reworked this part of the
code because it didn't seem necessary.  Putting that back in because
it looks like it is on some systems.
2022-07-18 16:24:31 -07:00
Jim Ingham e83d47f6b7 When the module path for `command script import` is invalid, echo the path.
We were just emitting "invalid module" w/o saying which module.  That's
not particularly helpful.

Differential Revision: https://reviews.llvm.org/D129338
2022-07-18 14:49:07 -07:00
Jim Ingham 5778ada8e5 Make hit point counts reliable for architectures that stop before evaluation.
Since we want to present the "new & old" values for watchpoint hits, on architectures,
including the ARM family, that stop before the triggering instruction is run, we need
to single step over the instruction before stopping for realz.  This was incorrectly
done directly in the StopInfoWatchpoint::ShouldStop.  That causes problems if more than
one thread stops "for a reason" at the same time as the watchpoint, since the other actions
didn't expect the process to make progress in this part of the execution control machinery.

The correct way to do this is to schedule the step over using ThreadPlans, and then to restore
the stop info after that plan stops, so that the rest of the stop info actions can happen when
all the other threads have handled their immediate actions as well.

Differential Revision: https://reviews.llvm.org/D129814
2022-07-18 14:36:32 -07:00
Kazu Hirata 8b3ed1fa98 Remove redundant return statements (NFC)
Identified with readability-redundant-control-flow.
2022-07-17 15:37:46 -07:00
Kazu Hirata 5cff5142a8 Use value instead of getValue (NFC) 2022-07-15 20:03:13 -07:00
Michał Górny 09531ede6d [lldb] [llgs] Improve stdio forwarding in multiprocess+nonstop
Enable stdio forwarding when nonstop mode is enabled, and disable it
once it is disabled.  This makes it possible to cleanly handle stdio
forwarding while running multiple processes in non-stop mode.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128932
2022-07-15 21:50:39 +02:00
Michał Górny fc92f11441 [lldb] [test] Skip test_leave_nonstop on Windows 2022-07-15 21:48:03 +02:00
Michał Górny c732afa2c2 [lldb] [llgs] Fix disabling non-stop mode
Stop all processes and clear notification queues when disabling non-stop
mode.  Ensure that no stop notifications are sent for processes stopped
due to the mode switch.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128893
2022-07-15 20:16:49 +02:00
Michał Górny 5d6659739c [lldb] [test] Skip test_stop_reason_while_running on Windows 2022-07-15 20:14:55 +02:00
Michał Górny ab9f1e88fd [lldb] [llgs] Fix `?` packet response for running threads
Fix the response to `?` packet for threads that are running at the time
(in non-stop mode).  The previous code would wrongly send or queue
an empty response for them.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128879
2022-07-15 18:33:58 +02:00
Michał Górny 81e993f08d [lldb] [test] Skip TestNonStop → test_stdio on Windows 2022-07-15 18:33:19 +02:00
Michał Górny 1903f358bc [lldb] [llgs] Send process output asynchronously in non-stop mode
Introduce a new %Stdio notification category and use it to send process
output asynchronously when running in non-stop mode.  This is an LLDB
extension since GDB does not use the 'O' packet for process output,
just for replies to 'qRcmd' packets.

Using the async notification mechanism implies that only the first
output packet is sent immediately to the client.  The client needs
to request subsequent notifications (if any) using the new vStdio packet
(that works pretty much like vStopped for the Stop notification queue).

The packet handler in lldb-server tests is updated to handle the async
stdio packets in addition to the regular O packets.  However, due
to the implications noted above, it can only handle the first output
packet sent by the server.  Subsequent packets need to be explicitly
requested via vStdio.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128849
2022-07-15 17:20:39 +02:00
Michał Górny 5a6f1f3271 [lldb] [test] Skip new NonStop tests on Windows 2022-07-15 16:02:47 +02:00
David Spickett cd2e36eadd [lldb][AArch64] Enable int128 test
Other 128 bit tests run on AArch64 fine, it's
Arm (as in 32 bit Arm) that needs to be skipped.
2022-07-15 13:35:48 +00:00
Michał Górny eb43e43bb5 Reland "[lldb] [llgs] Fix multi-resume bugs with nonstop mode"
Improve handling of multiple successive continue packets in non-stop
mode.  More specifically:

1. Explicitly send error response (instead of crashing on assertion)
   if the user attempts to resume the same process twice.  Since we
   do not support thread-level non-stop mode, one needs to always stop
   the process explicitly before resuming another thread set.

2. Actually stop the process if "vCont;t" is delivered to a running
   process.  Similarly, we only support stopping all the running threads
   simultaneously (via -1) and return an error in any other case.

With this patch, running multiple processes simultaneously is still
unsupported.  The patch also employs a hack to avoid enabling stdio
forwarding on "vCont;t" packet.  Both of these issues are addressed
by followup patches.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128710
2022-07-15 15:24:00 +02:00
Michał Górny 7a2b09b479 Revert "[lldb] [llgs] Fix multi-resume bugs with nonstop mode"
This reverts commit f8605da875.
This is causing buildbot failures and now I see that I have not updated
the tests to use "stop" instead of "trap".
2022-07-15 13:43:34 +02:00
Michał Górny f8605da875 [lldb] [llgs] Fix multi-resume bugs with nonstop mode
Improve handling of multiple successive continue packets in non-stop
mode.  More specifically:

1. Explicitly send error response (instead of crashing on assertion)
   if the user attempts to resume the same process twice.  Since we
   do not support thread-level non-stop mode, one needs to always stop
   the process explicitly before resuming another thread set.

2. Actually stop the process if "vCont;t" is delivered to a running
   process.  Similarly, we only support stopping all the running threads
   simultaneously (via -1) and return an error in any other case.

With this patch, running multiple processes simultaneously is still
unsupported.  The patch also employs a hack to avoid enabling stdio
forwarding on "vCont;t" packet.  Both of these issues are addressed
by followup patches.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128710
2022-07-15 13:01:39 +02:00
Andy Yankovsky 7d297de951 Reland "[lldb] Add support for using integral const static data members in the expression evaluator"
Reland 486787210d which broke tests on Arm and Windows.

* Windows -- on Windows const static data members with no out-of-class
  definition do have valid addresses, in constract to other platforms
  (Linux, macos) where they don't. Adjusted the test to expect success
  on Windows and failure on other platforms.

* Arm -- `int128` is not available on 32-bit ARM, so disable the test
  for this architecture.
2022-07-15 10:52:35 +00:00
Fangrui Song 3c849d0aef Modernize Optional::{getValueOr,hasValue} 2022-07-15 01:20:39 -07:00
Jonas Devlieghere bcae3cdbd0
[lldb] Print the enum values and their description in the help output
Print the enum values and their description in the help output for
argument values. Until now, there was no way to get these values and
their description.

Example output:

(lldb) help <description-verbosity>
  <description-verbosity> -- How verbose the output of 'po' should be.

     compact : Only show the description string
     full    : Show the full output, including persistent variable's
               name and type

Differential revision: https://reviews.llvm.org/D129707
2022-07-14 21:18:08 -07:00
Jonas Devlieghere 7ced9fff95
[lldb] Refactor command option enum values (NFC)
Refactor the command option enum values and the command argument table
to connect the two. This has two benefits:

 - We guarantee that two options that use the same argument type have
   the same accepted values.
 - We can print the enum values and their description in the help
   output. (D129707)

Differential revision: https://reviews.llvm.org/D129703
2022-07-14 21:18:07 -07:00
Stella Stamenova c3a28e8a99 Revert "[lldb] Add support for using integral const static data members in the expression evaluator"
This reverts commit 486787210d.

This broke the windows lldb bot: https://lab.llvm.org/buildbot/#/builders/83/builds/21186
2022-07-14 10:47:01 -07:00
Michał Górny 06b3f27fed [lldb] [llgs] Remove not-really-used m_inferior_prev_state
Remove m_inferior_prev_state that's not suitable for multiprocess
debugging and that does not seem to be really used at all.

The only use of the variable right now is to "prevent" sending the stop
reason after attach/launch.  However, this code is never actually run
since none of the process plugins actually use eStateLaunching or
eStateAttaching.  Through adding an assert, I've confirmed that it's
never hit in any of the LLDB tests or while attaching/launching debugged
process via lldb-server and via lldb CLI.

Differential Revision: https://reviews.llvm.org/D128878
Sponsored by: The FreeBSD Foundation
2022-07-14 19:25:54 +02:00
Fangrui Song ecfaf4801c [lldb] Remove ELF .zdebug support
clang 14 removed -gz=zlib-gnu support and ld.lld/llvm-objcopy removed zlib-gnu
support recently. Remove lldb support by migrating away from
llvm::object::Decompressor::isCompressedELFSection.
The API has another user llvm-dwp, so it is not removed in this patch.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D129724
2022-07-14 10:12:48 -07:00
Andy Yankovsky 486787210d [lldb] Add support for using integral const static data members in the expression evaluator
This adds support for using const static integral data members as described by C++11 [class.static.data]p3
to LLDB's expression evaluator.

So far LLDB treated these data members are normal static variables. They already work as intended when they are declared in the class definition and then defined in a namespace scope. However, if they are declared and initialised in the class definition but never defined in a namespace scope, all LLDB expressions that use them will fail to link when LLDB can't find the respective symbol for the variable.

The reason for this is that the data members which are only declared in the class are not emitted into any object file so LLDB can never resolve them. Expressions that use these variables are expected to directly use their constant value if possible. Clang can do this for us during codegen, but it requires that we add the constant value to the VarDecl we generate for these data members.

This patch implements this by:
* parsing the constant values from the debug info and adding it to variable declarations we encounter.
* ensuring that LLDB doesn't implicitly try to take the address of expressions that might be an lvalue that points to such a special data member.

The second change is caused by LLDB's way of storing lvalues in the expression parser. When LLDB parses an expression, it tries to keep the result around via two mechanisms:

1. For lvalues, LLDB generates a static pointer variable and stores the address of the last expression in it: `T *$__lldb_expr_result_ptr = &LastExpression`
2. For everything else, LLDB generates a static variable of the same type as the last expression and then direct initialises that variable: `T $__lldb_expr_result(LastExpression)`

If we try to print a special const static data member via something like `expr Class::Member`, then LLDB will try to take the address of this expression as it's an lvalue. This means LLDB will try to take the address of the variable which causes that Clang can't replace the use with the constant value. There isn't any good way to detect this case (as there a lot of different expressions that could yield an lvalue that points to such a data member), so this patch also changes that we only use the first way of capturing the result if the last expression does not have a type that could potentially indicate it's coming from such a special data member.

This change shouldn't break most workflows for users. The only observable side effect I could find is that the implicit persistent result variables for const int's now have their own memory address:

Before this change:
```
(lldb) p i
(const int) $0 = 123
(lldb) p &$0
(const int *) $1 = 0x00007ffeefbff8e8
(lldb) p &i
(const int *) $2 = 0x00007ffeefbff8e8
```

After this change we capture `i` by value so it has its own value.
```
(lldb) p i
(const int) $0 = 123
(lldb) p &$0
(const int *) $1 = 0x0000000100155320
(lldb) p &i
(const int *) $2 = 0x00007ffeefbff8e8
```

Reviewed By: Michael137

Differential Revision: https://reviews.llvm.org/D81471
2022-07-14 15:15:11 +00:00
Michał Górny 355c791633 [lldb] [llgs] Convert m_debugged_processes into a map of structs
Convert the m_debugged_processes map from NativeProcessProtocol pointers
to structs, and combine the additional set(s) holding the additional
process properties into a flag field inside this struct.  This is
desirable since there are more properties to come and having a single
structure with all information should be cleaner and more efficient than
using multiple sets for that.

Suggested by Pavel Labath in D128893.

Differential Revision: https://reviews.llvm.org/D129652
2022-07-14 15:32:19 +02:00
Michał Górny c164efb006 [lldb] [gdb-remote] Remove stray GetSupportsThreadSuffix() method (NFC)
Remove stray GDBRemoteCommunicationClient::GetSupportsThreadSuffix()
method that is not implemented nor used anywhere.
2022-07-14 12:18:17 +02:00
Jason Molenda ac49e90219 jGetLoadedDynamicLibrariesInfos can inspect machos not yet loaded
jGetLoadedDynamicLibrariesInfos normally checks with dyld to find
the list of binaries loaded in the inferior, and getting the filepath,
before trying to parse the Mach-O binary in inferior memory.
This allows for debugserver to parse a Mach-O binary present in memory,
but not yet registered with dyld.  This patch also adds some simple
sanity checks that we're reading a Mach-O header before we begin
stepping through load commands, because we won't have the sanity check
of consulting dyld for the list of loaded binaries before parsing.
Also adds a testcase.

[This patch was reverted after causing a testsuite failure on a CI bot;
I haven't been able to repro the failure outside the CI, but I have a
theory that my sanity check on cputype which only matched arm64 and
x86_64 - and the CI machine may have a watch simulator that is still
using i386.]

Differential Revision: https://reviews.llvm.org/D128956
rdar://95737734
2022-07-14 00:56:14 -07:00
Dave Lee b5ccfeb6bf [lldb] Add image dump pcm-info command
Add `pcm-info` to the `target module dump` subcommands.

This dump command shows information about clang .pcm files. This command
effectively runs `clang -module-file-info` and produces identical output.

The .pcm file format is tightly coupled to the clang version. The clang
embedded in lldb is not guaranteed to match the version of the clang executable
available on the local system.

There have been times when I've needed to view the details about a .pcm file
produced by lldb's embedded clang, but because the clang executable was a
slightly different version, the `-module-file-info` invocation failed. With
this command, users can inspect .pcm files generated by lldb too.

Differential Revision: https://reviews.llvm.org/D129456
2022-07-13 16:56:53 -07:00
Fangrui Song e690137dde [Support] Change compression::zlib::{compress,uncompress} to use uint8_t *
It's more natural to use uint8_t * (std::byte needs C++17 and llvm has
too much uint8_t *) and most callers use uint8_t * instead of char *.
The functions are recently moved into `llvm::compression::zlib::`, so
downstream projects need to make adaption anyway.
2022-07-13 16:26:54 -07:00
Martin Storsjö a1568fa278 [lldb] Silence a GCC warning about missing returns after a fully covered switch. NFC. 2022-07-13 23:57:01 +03:00
ymeng 0466d1df23 [trace][intel pt] Support dumping the trace info in json
Thanks to ymeng@fb.com for coming up with this change.

`thread trace dump info` can dump some metrics that can be useful for
analyzing the performance and quality of a trace. This diff adds a --json
option for dumping this information in json format that can be easily
understood my machines.

Differential Revision: https://reviews.llvm.org/D129332
2022-07-13 12:26:11 -07:00
Gaurav Gaur d30fd5c3a1 [trace][intel pt] Add a cgroup filter
It turns out that cgroup filtering is relatively trivial and works
really nicely. Thid diffs adds automatic cgroup filtering when in
per-cpu mode, unless a new --disable-cgroup-filtering flag is passed in
the start command. At least on Meta machines, all processes are spawned
inside a cgroup by default, which comes super handy, because per cpu
tracing is now much more precise.

A manual test gave me this result

- Without filtering:
    Total number of trace items: 36083
    Total number of continuous executions found: 229
    Number of continuous executions for this thread: 2
    Total number of PSB blocks found: 98
    Number of PSB blocks for this thread 2
    Total number of unattributed PSB blocks found: 38

- With filtering:
    Total number of trace items: 87756
    Total number of continuous executions found: 123
    Number of continuous executions for this thread: 2
    Total number of PSB blocks found: 10
    Number of PSB blocks for this thread 3
    Total number of unattributed PSB blocks found: 2

Filtering gives us great results. The number of instructions collected
more than double (probalby because we have less noise in the trace), and
we have much less unattributed PSBs blocks and unrelated PSBs in
general. The ones that are unrelated probably belong to other processes
in the same cgroup.

Differential Revision: https://reviews.llvm.org/D129257
2022-07-13 12:26:11 -07:00
Walter Erquinigo 4a843d9282 [trace][intel pt] Create a CPU change event and expose it in the dumper
Thanks to fredzhou@fb.com for coming up with this feature.

When tracing in per-cpu mode, we have information of in which cpu we are execution each instruction, which comes from the context switch trace. This diff makes this information available as a `cpu changed event`, which an additional accessor in the cursor `GetCPU()`. As cpu changes are very infrequent, any consumer should listen to cpu change events instead of querying the actual cpu of a trace item. Once a cpu change event is seen, the consumer can invoke GetCPU() to get that information. Also, it's possible to invoke GetCPU() on an arbitrary instruction item, which will return the last cpu seen. However, this call is O(logn) and should be used sparingly.

Manually tested with a sample program that starts on cpu 52, then goes to 18, and then goes back to 52.

Differential Revision: https://reviews.llvm.org/D129340
2022-07-13 12:26:11 -07:00
Walter Erquinigo b532dd545f [trace] Add an option to save a compact trace bundle
A trace bundle contains many trace files, and, in the case of intel pt, the
largest files are often the context switch traces because they are not
compressed by default. As a way to improve this, I'm adding a --compact option
to the `trace save` command that filters out unwanted processes from the
context switch traces. Eventually we can do the same for intel pt traces as
well.

Differential Revision: https://reviews.llvm.org/D129239
2022-07-13 11:43:28 -07:00
Peicong Wu 9f9464e02a [trace][intel pt] Measure the time it takes to decode a thread in per-cpu mode
This metric was missing. We were only measuring in per-thread mode, and
this completes the work.

For a sample trace I have, the `dump info` command shows

```
Timing for this thread:
    Decoding instructions: 0.12s

```

I also improved a bit the TaskTime function so that callers don't need to
specify the template argument

Differential Revision: https://reviews.llvm.org/D129249
2022-07-13 11:08:14 -07:00
rnofenko db73a52d7b [trace][intel pt] Add a nice parser for the trace size
Thanks to rnofenko@fb.com for coming up with these changes.

This diff adds support for passing units in the trace size inputs. For example,
it's now possible to specify 64KB as the trace size, instead of the
problematic 65536. This makes the user experience a bit friendlier.

Differential Revision: https://reviews.llvm.org/D129613
2022-07-13 10:53:14 -07:00
Muhammad Omair Javaid f827b4b657 [LLDB] Fix TestConvenienceVariables.test AArch64/Windows
This patch fixes TestConvenienceVariables.test for AArch64 Windows.
Clang/LLD was unable to find printf apparently available as a macro
definition in stdio.h.
2022-07-13 16:46:55 +05:00
Muhammad Omair Javaid 7610524af3 [LLDB] Fix TestThreadAPI.py for AArch64/Windows
This patch fixes TestThreadAPI for AArch64 windows by switching over to
PDB debug info instead of DWARF. This is needed to step over library
functions like printf as there is debug info mismatch between DWARF and
PDB. PDB DWARF interworking is not fully supported by LLDB at the
moment.
2022-07-13 16:30:09 +05:00
Muhammad Omair Javaid b82b018712 [LLDB] XFail TestLoadUnload.test_static_init_during_load AArch64/Windows
This patch fixes marks TestLoadUnload.test_static_init_during_load as
xfail for AArch64 windows. It is failing similar to Linux and already
marked xfail for linux.
2022-07-13 16:18:18 +05:00
Muhammad Omair Javaid 891319f654 [LLDB] Fix pointers.test for AArch64/Windows
pointers.test started failing again for AArch64 windows after D125509
This patch fixes the test to make it pass on AArch64 windows again.

LLDB AArch64 Windows buildbot running at:
https://lab.llvm.org/staging/#/builders/207
2022-07-13 15:55:31 +05:00
Martin Storsjö 306fc2cd87 [lldb] Fix build with GCC 9 after "[ADT] Use Empty Base Optimization for Allocators"
This fixes this compilation error, after
a565509308f9372c4de1c4c32afde461a42e81c8:

In file included from ../tools/lldb/include/lldb/Host/Host.h:14,
                 from ../tools/lldb/source/Host/common/File.cpp:28:
../tools/lldb/include/lldb/Utility/Environment.h: In copy constructor ‘lldb_private::Environment::Environment(const lldb_private::Environment&)’:
../tools/lldb/include/lldb/Utility/Environment.h:60:49: error: call of overloaded ‘StringMap(const lldb_private::Environment&)’ is ambiguous
   60 |   Environment(const Environment &RHS) : Base(RHS) {}
      |                                                 ^
In file included from ../include/llvm/Support/YAMLTraits.h:16,
                 from ../tools/lldb/include/lldb/Utility/ConstString.h:15,
                 from ../tools/lldb/include/lldb/Utility/FileSpec.h:15,
                 from ../tools/lldb/include/lldb/Host/FileSystem.h:14,
                 from ../tools/lldb/source/Host/common/File.cpp:27:
../include/llvm/ADT/StringMap.h:137:3: note: candidate: ‘llvm::StringMap<ValueTy, AllocatorTy>::StringMap(const llvm::StringMap<ValueTy, AllocatorTy>&) [with ValueTy = std::__cxx11::basic_string<char>; AllocatorTy = llvm::MallocAllocator]’
  137 |   StringMap(const StringMap &RHS)
      |   ^~~~~~~~~
../include/llvm/ADT/StringMap.h:122:12: note: candidate: ‘llvm::StringMap<ValueTy, AllocatorTy>::StringMap(AllocatorTy) [with ValueTy = std::__cxx11::basic_string<char>; AllocatorTy = llvm::MallocAllocator]’
  122 |   explicit StringMap(AllocatorTy A)
      |            ^~~~~~~~~
2022-07-13 12:57:04 +03:00
Kazu Hirata e5f568a49f Use has_value instead of hasValue (NFC) 2022-07-13 01:58:03 -07:00
Walter Erquinigo dbc0cb0198 [trace] Avoid a crash in the dumper when disassembling fails
In rare situations, disassemblying would fail that produce an invalid
InstructionSP object. We need to check that it's valid before using.

With this change, now the dumper doesn't crash with dumping instructions of
ioctl. In fact, it now dumps this output

 {
    "id": 6135,
    "loadAddress": "0x7f4bfe5c7515",
    "module": "libc.so.6",
    "symbol": "ioctl",
    "source": "glibc/2.34/src/glibc-2.34/sysdeps/unix/syscall-template.S",
    "line": 120,
    "column": 0
 }

Anyway, we need to investigate why the diassembler failed disassembling that
instruction. From over 2B instructions I was disassembling today, just this
one failed, so this could be a bug in LLVM's core disassembler.

Differential Revision: https://reviews.llvm.org/D129588
2022-07-12 16:23:03 -07:00
Walter Erquinigo ad7bcda940 [trace] Add a flag to the decoder to output the instruction type
To build complex binding upon instruction trace, additional metadata 'instruction type' is needed.

This diff has followings:
 - Add a flag -k  / --kind for instruction dump
 - Remove SetGranularity and SetIgnoreErros from Trace cursor

Sample output:

```
(lldb) thread trace dump instruction -k
thread #1: tid = 3198805
  libc.so.6`_IO_puts + 356
    2107: 0x00007ffff7163594 (    return)     retq
    2106: 0x00007ffff7163592 (     other)     popq   %r13
    2105: 0x00007ffff7163590 (     other)     popq   %r12
    2104: 0x00007ffff716358f (     other)     popq   %rbp
    2103: 0x00007ffff716358e (     other)     popq   %rbx
    2102: 0x00007ffff716358c (     other)     movl   %ebx, %eax
    2101: 0x00007ffff7163588 (     other)     addq   $0x8, %rsp
    2100: 0x00007ffff7163570 ( cond jump)     je     0x89588                   ; <+344>
    2099: 0x00007ffff716356e (     other)     decl   (%rdx)
    2098: 0x00007ffff7163565 ( cond jump)     je     0x8956e                   ; <+318>
    2097: 0x00007ffff716355e (     other)     cmpl   $0x0, 0x33c02b(%rip)      ; __libc_multiple_threads
    2096: 0x00007ffff7163556 (     other)     movq   $0x0, 0x8(%rdx)
    2095: 0x00007ffff7163554 ( cond jump)     jne    0x89588                   ; <+344>
    2094: 0x00007ffff7163550 (     other)     subl   $0x1, 0x4(%rdx)
    2093: 0x00007ffff7163549 (     other)     movq   0x88(%rbp), %rdx
    2092: 0x00007ffff7163547 ( cond jump)     jne    0x89588                   ; <+344>
    2091: 0x00007ffff7163540 (     other)     testl  $0x8000, (%rbp)           ; imm = 0x8000
    2090: 0x00007ffff716353c (     other)     cmovaq %rax, %rbx
    2089: 0x00007ffff7163535 (     other)     cmpq   $0x7fffffff, %rbx         ; imm = 0x7FFFFFFF
    2088: 0x00007ffff7163530 (     other)     movl   $0x7fffffff, %eax         ; imm = 0x7FFFFFFF
```

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D128477
2022-07-12 16:23:03 -07:00
Jonas Devlieghere 5edfc0b928
[lldb] Fix macOS Ventura version number checks
Unlike Python 2 which reports 10.16 on any recent macOS, Python 3
correctly reports Ventura as macOS 13.
2022-07-12 13:29:46 -07:00
Jonas Devlieghere b620852d23
[lldb] Make the g_arguments_data constexpr and fix the static assert
This fixes the static assert that's meant to keep the g_arguments_data
table in sync with the CommandArgumentType enumeration. Indeed, the
assert didn't fire even though the current code is missing an entry.
This patches fixes that as well.

Differential revision: https://reviews.llvm.org/D129529
2022-07-12 13:12:36 -07:00
Pavel Labath a72306e202 [lldb] Fix TestDataFormatterLibcxxString broken by D129490
We need to check for the error inside the value object to avoid reading
garbage through invalid (target) pointers.
2022-07-12 20:12:22 +02:00
Zequan Wu b74a01a80b Reland "[LLDB][NFC] Decouple dwarf location table from DWARFExpression."
This reland 227dffd0b6 and
562c3467a6 with failed api tests fixed by keeping
function base file addres in DWARFExpressionList.
2022-07-12 10:54:24 -07:00
Nico Weber 7f83dae7f5 try to fix lldb build after d489268392 2022-07-12 11:08:44 -04:00
Muhammad Omair Javaid 7b69843f0b [LLDB] Catagory decorator for watchpoint test in TestCompletion.py
This patch adds watchpoint catagory decorator to watchpoint dependent
tests in TestCompletion.py.
2022-07-12 17:15:33 +05:00
Muhammad Omair Javaid 68cc1eeb1d [LLDB] Fix NativePDB/local-variables.cpp for AArch64/Windows
This patch fixes NativePDB/local-variables.cpp test for AArch64 Windows.
There are two changes:
1) Replace function breakpoint with line breakpoint required due to pr56288
2) Adjust "target modules dump ast" test as the output was slightly different
on AArch64/Windows.
2022-07-12 16:26:47 +05:00
David M. Lary 1e3ee766bb [lldb] add SBSection.alignment to python bindings
This commit adds SBSection.GetAlignment(), and SBSection.alignment as a python property to lldb.

Reviewed By: clayborg, JDevlieghere, labath

Differential Revision: https://reviews.llvm.org/D128069
2022-07-12 12:18:38 +02:00
Pavel Labath 918b1e7bbd Revert "[lldb] add SBSection.alignment to python bindings"
The patch didn't get proper attribution. Will recommit.

This reverts commit 4135abca89.
2022-07-12 12:17:29 +02:00
Pavel Labath 4135abca89 [lldb] add SBSection.alignment to python bindings
This commit adds SBSection.GetAlignment(), and SBSection.alignment as a python property to lldb.

Reviewed By: clayborg, JDevlieghere, labath

Differential Revision: https://reviews.llvm.org/D128069
2022-07-12 12:14:54 +02:00
Michael Buch 4d26faa526 [LLDB][ClangExpression] Remove unused StructVars::m_object_pointer_type
This member variable was removed a while ago in
443427357f. It was previously used in
materialization code paths that have since been removed. Nowadays,
`m_object_pointer_type` gets set but not used anywhere.

This patch simply removes all remaining instances of it and any
supporting code.

**Testing**

* API tests pass

Differential Revision: https://reviews.llvm.org/D129367
2022-07-12 10:33:41 +01:00
Michael Buch d1e9d0b27f [LLDB][DataFormatter] Add data formatter for libcxx std::unordered_map iterator
This patch adds a formatter for libcxx's `std::unordered_map` iterators.
The implementation follows a similar appraoch to the `std::map` iterator
formatter. I was hesistant about coupling the two into a common
implementation since the libcxx layouts might change for one of the
the containers but not the other.

All `std::unordered_map` iterators are covered with this patch:
1. const/non-const key/value iterators
2. const/non-const bucket iterators

Note that, we currently don't have a formatter for `std::unordered_map`.
This patch doesn't change that, we merely add support for its iterators,
because that's what Xcode users requested. One can still see contents
of `std::unordered_map`, whereas with iterators it's less ergonomic.

**Testing**

* Added API test

Differential Revision: https://reviews.llvm.org/D129364
2022-07-12 10:13:55 +01:00
Pavel Labath d4381153ea [lldb/libc++] Simplify the libc++ string formatter
Precise string layout has changed a lot recently, but a long of these
changes did not have any effect on the usages of its fields -- e.g.
introduction/removal of an anonymous struct or union does not change the
way one can access the field in C++. Our name-based variable lookup
rules (deliberately) copy the C++ semantics, which means these changes
would have been invisible to the them, if only we were using name-based
lookup.

This patch replaces the opaque child index accesses with name-based
lookups, which allows us to greatly simplify the data formatter code.
The formatter continues to support all the string layouts that it
previously supported.

It is unclear why the formatter was not using this approach from the
beginning. I would speculate that the original version was working
around some (now fixed) issue with anonymous members or base classes,
and the subsequent revisions stuck with that approach out of inertia.

Differential Revision: https://reviews.llvm.org/D129490
2022-07-12 09:57:13 +02:00
Raphael Isemann 9bc34636a5
[lldb] Add support for escaping fish arguments
LLDB supports having globbing regexes in the process launch arguments
that will be resolved using the user's shell. This requires that we pass
the launch args to the shell and then read back the expanded arguments
using LLDB's argdumper utility.

As the shell will not just expand the globbing regexes but all special
characters, we need to escape all non-globbing charcters such as $, &,
<, >, etc. as those otherwise are interpreted and removed in the step
where we expand the globbing characters. Also because the special
characters are shell-specific, LLDB needs to maintain a list of all the
characters that need to be escaped for each specific shell.

This patch adds the list of special characters that need to be escaped
for fish. Without this patch on systems where fish is the user's shell
having any of these special characters in your arguments or path to
the binary will cause the process launch to fail. E.g., `lldb -- ./calc
1<2` is failing without this patch. The same happens if the absolute
path to calc is in a directory that contains for example parentheses
or other special characters.

Differential revision: https://reviews.llvm.org/D104635
2022-07-11 16:44:46 -07:00
Jonas Devlieghere 9097920eba
[lldb] Add a test to prefer exact triple matches in platform selection
Add a test that ensures we always prioritize exact triple matches when
creating platforms. This is a regression test for a (now resolved) bug
that that resulted in the remote tvOS platform being selected for a tvOS
simulator binary because the ArchSpecs are compatible.
2022-07-11 16:35:51 -07:00
Jonas Devlieghere ce233e7146
[lldb] Use the just-built libc++ for testing the LLDB data formatters
Make sure we use the libc++ from the build dir. Currently, by passing
-stdlib=libc++, we might pick up the system libc++. This change ensures
that if LLVM_LIBS_DIR is set, we try to use the libc++ from there.

Differential revision: https://reviews.llvm.org/D129166
2022-07-11 14:49:24 -07:00
Martin Storsjö 66cdd6548a [lldb] Reduce the stack alignment requirements for the Windows x86_64 ABI
This fixes https://github.com/llvm/llvm-project/issues/56095.

Differential Revision: https://reviews.llvm.org/D129455
2022-07-11 23:41:35 +03:00
spupyrev b444358126 Revert "Rebase: [Facebook] Add clang driver options to test debug info and BOLT"
This reverts commit f921985a29.
2022-07-11 09:50:46 -07:00
Amir Ayupov f921985a29 Rebase: [Facebook] Add clang driver options to test debug info and BOLT
Summary:
This is an essential piece of infrastructure for us to be
continuously testing debug info with BOLT. We can't only make changes
to a test repo because we need to change debuginfo tests to call BOLT,
hence, this diff needs to sit in our opensource repo. But when upstreaming
to LLVM, this should be kept BOLT-only outside of LLVM. When upstreaming,
we need to git diff and check all folders that are being modified by our
commits and discard this one (and leave as an internal diff).

To test BOLT in debuginfo tests, configure it with -DLLVM_TEST_BOLT=ON.
Then run check-lldb and check-debuginfo.

Manual rebase conflict history:
https://phabricator.intern.facebook.com/D29205224
https://phabricator.intern.facebook.com/D29564078
https://phabricator.intern.facebook.com/D33289118
https://phabricator.intern.facebook.com/D34957174

Test Plan:
tested locally
Configured with:
-DLLVM_ENABLE_PROJECTS="clang;lld;lldb;compiler-rt;bolt;debuginfo-tests"
-DLLVM_TEST_BOLT=ON
Ran test suite with:
ninja check-debuginfo
ninja check-lldb

Reviewers: #llvm-bolt

Subscribers: ayermolo, phabricatorlinter

Differential Revision: https://phabricator.intern.facebook.com/D35317341

Tasks: T92898286
2022-07-11 09:31:51 -07:00
Jonas Devlieghere 9302ff0951
Revert "jGetLoadedDynamicLibrariesInfos can inspect machos not yet loaded"
This reverts commit 77a38f6839 because (I
suspect) it breaks TestAppleSimulatorOSType.py on GreenDragon [1].

[1] https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/45191/
2022-07-11 09:25:14 -07:00
Michał Górny 9790406a92 Reland "[lldb] [test] Improve stability of llgs vCont-threads tests"
Perform a major refactoring of vCont-threads tests in order to attempt
to improve their stability and performance.

Split test_vCont_run_subset_of_threads() into smaller test cases,
and split the whole suite into two files: one for signal-related tests,
the running-subset-of tests.

Eliminate output_match checks entirely, as they are fragile to
fragmentation of output.  Instead, for the initial thread list capture
raise an explicit SIGINT from inside the test program, and for
the remaining output let the test program run until exit, and check all
the captured output afterwards.

For resume tests, capture the LLDB's thread view before and after
starting new threads in order to determine the IDs corresponding
to subthreads rather than relying on program output for that.

Add a mutex for output to guarantee serialization.  A barrier is used
to guarantee that all threads start before SIGINT, and an atomic bool
is used to delay prints from happening until after SIGINT.

Call std::this_thread::yield() to reduce the risk of one of the threads
not being run.

This fixes the test hangs on FreeBSD.  Hopefully, it will also fix all
the flakiness on buildbots.

Thanks to Pavel Labath for figuring out why the original version did not
work on Debian.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D129012
2022-07-11 18:05:14 +02:00
Venkata Ramanaiah Nalamothu 419cc0a0b2 [lldb] Fix thread step until to not set breakpoint(s) on incorrect line numbers
The requirements for "thread until <line number>" are:

a) If any code contributed by <line number> or the nearest subsequent of <line number> is executed before leaving the function, stop
b) If you end up leaving the function w/o triggering (a), then stop

In case of (a), since the <line number> may have multiple entries in the line table and the compiler might have scheduled/moved the relevant code across, and the lldb does not know the control flow, set breakpoints on all the line table entries of best match of <line number> i.e. exact or the nearest subsequent line.

Along with the above, currently, CommandObjectThreadUntil is also setting the breakpoints on all the subsequent line numbers after the best match and this latter part is wrong.

This issue is discussed at http://lists.llvm.org/pipermail/lldb-dev/2018-August/013979.html.

In fact, currently `TestStepUntil.py` is not actually testing step until scenarios and `test_missing_one` test fails without this patch if tests are made to run. Fixed the test as well.

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D50304
2022-07-11 18:45:37 +05:30
Pavel Labath fea52ac541 [lldb/test] Use SIGINT as the "stopping" signal
Using SIGSTOP means that if anything goes wrong in the test, the process
can end up in the stopped state, where it is not running, but still
taking up resources. Eventually, these "zombies" can make the machine
completely unusable. Instead, use a signal whose default action is to
kill the processes.
2022-07-11 08:42:17 +02:00
Dave Lee 4655400b21 [lldb] Delete more mydir references (NFC) 2022-07-10 18:56:06 -07:00
Jason Molenda 77a38f6839 jGetLoadedDynamicLibrariesInfos can inspect machos not yet loaded
jGetLoadedDynamicLibrariesInfos normally checks with dyld to find
the list of binaries loaded in the inferior, and getting the filepath,
before trying to parse the Mach-O binary in inferior memory.
This allows for debugserver to parse a Mach-O binary present in memory,
but not yet registered with dyld.  This patch also adds some simple
sanity checks that we're reading a Mach-O header before we begin
stepping through load commands, because we won't have the sanity check
of consulting dyld for the list of loaded binaries before parsing.
Also adds a testcase.

Differential Revision: https://reviews.llvm.org/D128956
rdar://95737734
2022-07-08 15:13:49 -07:00
Leonard Chan 474c873148 Revert "[llvm] cmake config groundwork to have ZSTD in LLVM"
This reverts commit f07caf20b9 which seems to break upstream https://lab.llvm.org/buildbot/#/builders/109/builds/42253.
2022-07-08 13:48:05 -07:00
Cole Kissane f07caf20b9 [llvm] cmake config groundwork to have ZSTD in LLVM
- added `FindZSTD.cmake`
- added a CMake option `LLVM_ENABLE_ZSTD` with behavior mirroring that of `LLVM_ENABLE_ZLIB`
- likewise added have_zstd to compiler-rt/test/lit.common.cfg.py, clang-tools-extra/clangd/test/lit.cfg.py, and several lit.site.cfg.py.in files mirroring have_zlib behavior

Reviewed By: leonardchan, MaskRay

Differential Revision: https://reviews.llvm.org/D128465
2022-07-08 11:46:52 -07:00
Louis Dionne d2e86866be [libc++] Re-apply the use of ABI tags to provide per-TU insulation
This commit re-applies 9ee97ce3b8, which was reverted by 61d417ce
because it broke the LLDB data formatter tests. It also re-applies
6148c79a (the manual GN change associated to it).

Differential Revision: https://reviews.llvm.org/D127444
2022-07-08 08:38:36 -04:00
serge-sans-paille 132d711554 [lldb/test] Disable TestStringLiteralExpr.test on Windows
This test, introduced by b042d15d2e, fails on
https://lab.llvm.org/buildbot/#/builders/83/builds/20933/steps/7/logs/stdio

but succeeds on other targets, see for instance
https://lab.llvm.org/buildbot/#/builders/68/builds/35462/steps/6/logs/stdio

This test is not be arch specific, just disabling it on Windows.
2022-07-08 12:17:31 +02:00
Jesus Checa Hidalgo b042d15d2e [lldb/test] Add Shell/Expr/TestStringLiteralExpr.test
This test should exercise the usage of expressions containing
string literals and ensure that lldb doesn't crash.

Differential Revision: https://reviews.llvm.org/D129261
2022-07-08 10:01:07 +02:00
David Blaikie 72d9390778 Add a little extra test coverage for simple template names
This would fail with an overly naive approach to simple template
name (clang's -gsimple-template-names) since the names wouldn't be
unique per specialization, creating ambiguity/chance that a query for
one specialization would find another.
2022-07-08 00:12:29 +00:00
Jonas Devlieghere e4c5bca597
Revert "[LLDB][NFC] Decouple dwarf location table from DWARFExpression."
This reverts commit 227dffd0b6 and its
follow up 562c3467a6 because it breaks a
bunch of tests on GreenDragon:

https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/45155/
2022-07-07 16:36:10 -07:00
Zequan Wu 562c3467a6 [LLDB] Fix aggregate-indirect-arg.cpp failure introduced by 227dffd0b6 2022-07-07 15:01:07 -07:00
David Blaikie b92c33495a Remove dead code: TypeMap::RemoveMismatchedTypes(TypeClass type_class) 2022-07-07 20:46:14 +00:00
David Blaikie 6edbde1001 Simplify some AsCString usage that was also explicitly handling default 2022-07-07 20:27:05 +00:00
David Blaikie 856ebe9e82 Retrieve as StringRef since that's how it'll be used 2022-07-07 20:13:36 +00:00
Augusto Noronha 5ade38c285 [lldb] Add comments to describe m_memory_addr and IsInMemory
Differential Revision: https://reviews.llvm.org/D129319
2022-07-07 13:11:50 -07:00
David Blaikie 65cac0ed92 Use StringRef to avoid unnecessary copies into std::strings 2022-07-07 19:50:12 +00:00
Zequan Wu 227dffd0b6 [LLDB][NFC] Decouple dwarf location table from DWARFExpression.
Differential Revision: https://reviews.llvm.org/D125509
2022-07-07 10:26:58 -07:00
Jonas Devlieghere ec48a0df91
[lldb] Improve the error message in run_to_breakpoint_do_run
Improve the error message when we fail to hit the initial breakpoint in
run_to_breakpoint_do_run. In addition to the process state, we now also
report the exit code and reason (if the process exited) as well as the
inferior's output.

Differential revision: https://reviews.llvm.org/D111978
2022-07-07 10:22:45 -07:00
David Spickett f3d43eca34 [lldb][Windows] Fixup overlapping memory regions tests
As suggested in post-commit review on https://reviews.llvm.org/D129272.

* Rename the test case.
* Simplify the overlap check.
* Correct assertion.
2022-07-07 15:36:14 +00:00
Pavel Labath d955185b94 [lldb/test] Use the shim executable for TestGdbRemoteAttach*Or*Wait as well
Without it, the test may nondeterminstically fail due to YAMA
restrictions.

Also, merge the two tests into one to reduce duplication.
2022-07-07 17:35:15 +02:00
Michał Górny fad93cd682 Revert "[lldb] [test] Improve stability of llgs vCont-threads tests"
This reverts commit 86e472317c.
It breaks Debian buildbot, for some reason.
2022-07-07 17:01:43 +02:00
Michał Górny 86e472317c [lldb] [test] Improve stability of llgs vCont-threads tests
Perform a major refactoring of vCont-threads tests in order to attempt
to improve their stability and performance.

Split test_vCont_run_subset_of_threads() into smaller test cases,
and split the whole suite into two files: one for signal-related tests,
the running-subset-of tests.

Eliminate output_match checks entirely, as they are fragile to
fragmentation of output.  Instead, for the initial thread list capture
raise an explicit SIGSTOP from inside the test program, and for
the remaining output let the test program run until exit, and check all
the captured output afterwards.

For resume tests, capture the LLDB's thread view before and after
starting new threads in order to determine the IDs corresponding
to subthreads rather than relying on program output for that.

Add a mutex for output to guarantee serialization.  A barrier is used
to guarantee that all threads start before SIGSTOP, and an atomic bool
is used to delay prints from happening until after SIGSTOP.

Call std::this_thread::yield() to reduce the risk of one of the threads
not being run.

This fixes the test hangs on FreeBSD.  Hopefully, it will also fix all
the flakiness on buildbots.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D129012
2022-07-07 16:33:55 +02:00
Pavel Labath 8262ff44c5 [lldb/test] Add a couple of libc++ std::string layouts
.. to the "string simulator" test. These layouts were used at some point in
the past few months, and are already supported by the code.
2022-07-07 16:20:20 +02:00
David Spickett 1ca8a97802 [lldb][Windows] Fix memory region base addresses when a range is split
Previously we recorded AllocationBase as the base address of the region
we get from VirtualQueryEx. However, this is the base of the allocation,
which can later be split into more regions.

So you got stuff like:
[0x00007fff377c0000-0x00007fff377c1000) r-- PECOFF header
[0x00007fff377c0000-0x00007fff37840000) r-x .text
[0x00007fff377c0000-0x00007fff37870000) r-- .rdata

Where all the base addresses were the same.

Instead, use BaseAddress as the base of the region. So we get:
[0x00007fff377c0000-0x00007fff377c1000) r-- PECOFF header
[0x00007fff377c1000-0x00007fff37840000) r-x .text
[0x00007fff37840000-0x00007fff37870000) r-- .rdata

https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information

The added test checks for any overlapping regions which means
if we get the base or size wrong it'll fail. This logic
applies to any OS so the test isn't restricted to Windows.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D129272
2022-07-07 13:55:48 +00:00
Pavel Labath 11a09692ad [lldb] Fixup TestLoadAfterAttach for 82ba3f4
After 82ba3f4, we (again) need to call lldb_enable_attach to be able to
attach to processes on linux. This was a new test, so it does not have
the necessary boilerplate.
2022-07-07 15:06:40 +02:00
Pavel Labath 82ba3f4465 Recommit "[lldb/test] Don't use preexec_fn for launching inferiors"
This recommits b15b1421, which reverted in was reverted in f51c47d98 due to
failures on apple systems. The problem was that the patch introduced a race
where the debug server could start the attach process before the first process
(which isn't supposed to be attached to) was set up. This caused us to attach
to the wrong process.

The new version introduces additional synchronization to ensure that does not
happen.

Original commit message was:
As the documentation states, using this is not safe in multithreaded
programs, and I have traced it to a rare deadlock in some of the tests.

The reason this was introduced was to be able to attach to a program
from the very first instruction, where our usual mechanism of
synchronization -- waiting for a file to appear -- does not work.

However, this is only needed for a single test
(TestGdbRemoteAttachWait) so instead of doing this everywhere, I create
a bespoke solution for that single test. The solution basically
consists of outsourcing the preexec_fn code to a separate (and
single-threaded) shim process, which enables attaching and then executes
the real program.

This pattern could be generalized in case we needed to use it for other
tests, but I suspect that we will not be having many tests like this.

This effectively reverts commit
a997a1d7fb.
2022-07-07 14:38:33 +02:00
David Spickett e5fdcfac1b [lldb][AArch64] Use "+all" feature for the disassembler
The "+all" feature name was added in https://reviews.llvm.org/D128029.

This feature means we don't have to generate a list of features
or use a base architecture feature.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D129177
2022-07-06 12:15:01 +00:00
Martin Storsjö 4270c9cd44 [lldb] Stop passing both i386 and i686 in parallel as architectures on Windows
When an object file returns multiple architectures, it is treated
as a fat binary - which really isn't the case of i386 vs i686 where
the object file actually has one architecture.

This allows getting rid of hardcoded architecture triples in
PlatformWindows.

The parallel i386 and i686 architecture strings stem from
5e6f45201f / D7120 and
ad587ae4ca / D4658.

Differential Revision: https://reviews.llvm.org/D128617
2022-07-06 12:13:36 +03:00
Med Ismail Bennani ea8b811bf8 [lldb/Core] Fix finite progress event reporting
This patch should fix event handling for finite progress reports.

Previously, the event handler would get stuck when receiving a finite
progress report, and stop displaying upcoming reports.
This was due to the fact that we were checking if the progress event was
completed by calling `GetCompleted` but returns the completion amount
instead of saying whether it's completed.

That caused the current event id to remain the same, preventing all the
following progress reports to be shown to the user.

This patch also adds some logging to facilitate debugging progress events.

rdar://91788326

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-07-05 16:25:40 -07:00
Muhammad Omair Javaid bb9b30ffbe [LLDB] Remove TestLoadUnload.py Arm/Linux Xfail decorator
This is a follow up on my last commit where one of the decorator was
left unremoved.

This patch removes Xfail decorator from TestLoadUnload.py as it is now
passing on Arm/Linux buildbot.
2022-07-06 01:39:52 +04:00
Muhammad Omair Javaid 5cca2ef3c3 [LLDB] Remove TestLoadUnload.py Arm/Linux Xfail decorator
This patch removes Xfail decorator from TestLoadUnload.py as it is now
passing on Arm/Linux buildbot.
2022-07-06 01:14:40 +04:00
Jonas Devlieghere f51c47d987
Revert "[lldb/test] Don't use preexec_fn for launching inferiors"
This reverts commit b15b1421bc because it
breaks GreenDragon [1]. The bot has been red for several days, so
reverting to green while I take a look.

[1] https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/45012/
2022-07-05 10:12:57 -07:00
Muhammad Omair Javaid b7b11091ef [LLDB] Fix decorator import in TestTwoHitsOneActual.py 2022-07-05 15:26:26 +04:00
Muhammad Omair Javaid 3b2496e8fa [LLDB] Skip TestTwoHitsOneActual.py on Arm/AArch64 Linux
This test has some race condition which is making it hang on LLDB
Arm/AArch64 Linux buildbot. I am marking it as skipped until we
investigate whats going wrong.
2022-07-05 15:01:51 +04:00
Muhammad Omair Javaid ba14e4d65c [LLDB] Disable TestGdbRemoteFork* for Arm/AArch64 Linux
This test is causing some trouble with LLDB Arm/AArch64 Linux buildbot.
I am disabling is temporarily to make buildbot green.
2022-07-05 13:45:26 +04:00
Kaining Zhong dc46ae6df5 [lldb] Add support to load object files from thin archives
This fixes https://github.com/llvm/llvm-project/issues/50114 where lldb/mac
can't load object files from thin archives.  This patch allows lldb to identify
thin archives, and load object files contained in them.

Differential Revision: https://reviews.llvm.org/D126464
2022-07-05 10:52:26 +02:00
Pavel Labath b15b1421bc [lldb/test] Don't use preexec_fn for launching inferiors
As the documentation states, using this is not safe in multithreaded
programs, and I have traced it to a rare deadlock in some of the tests.

The reason this was introduced was to be able to attach to a program
from the very first instruction, where our usual mechanism of
synchronization -- waiting for a file to appear -- does not work.

However, this is only needed for a single test
(TestGdbRemoteAttachWait) so instead of doing this everywhere, I create
a bespoke solution for that single test. The solution basically
consists of outsourcing the preexec_fn code to a separate (and
single-threaded) shim process, which enables attaching and then executes
the real program.

This pattern could be generalized in case we needed to use it for other
tests, but I suspect that we will not be having many tests like this.

This effectively reverts commit
a997a1d7fb.
2022-07-01 14:36:01 +02:00
Muhammad Omair Javaid 3d477bbeee [LLDB] Xfail TestStepNoDebug.py AArch64/Windows
LLDB fails to step in/out/over code with missing debug information.
This is only reproducible on AArch64/Windows. I have reported a issue
upstream at llvm.org/pr56292

This patch Xfail TestStepNoDebug.py for AArch64/Windows.
2022-07-01 12:25:43 +04:00
Pavel Labath b6b65403b3 [lldb] Add tests which simulate the various std::string layouts
Checking whether a formatter change does not break some of the supported
string layouts is difficult because it requires tracking down and/or
building different versions and build configurations of the library.

The purpose of this patch is to avoid that by providing an in-tree
simulation of the string class. It is a reduced version of the real
string class, obtained by elimitating all non-trivial code, leaving
just the internal data structures used by the data formatter. Different
versions of the class can be simulated through preprocessor defines.

The test (ab)uses the fact that our formatters kick in for any
double-underscore sub-namespace of `std`, so it avoids colliding with
the real string class by declaring the test class in the std::__lldb
namespace.

I do not consider this to be a replacement for the existing data
formatter tests, as producing this kind of a test is not trivial, and it
is easy to make a mistake in the process. However, it's also not
realistic to expect that every person changing the data formatter will
test it against all versions of the real class, so I think it can be
useful as a first line of defence.

Adding support for new layouts can become particularly unwieldy, but
this complexity will also be reflected in the actual code, so if we find
ourselves needing to support too many variants, we may need to start
dropping support for old ones, or come up with a completely different
strategy.

Differential Revision: https://reviews.llvm.org/D124155
2022-07-01 08:08:22 +02:00
Pavel Labath 553558292e [lldb/dyld-posix] Avoid reading the module list in inconsistent states
New glibc versions (since 2.34 or including this
<ed3ce71f5c>
patch) trigger the rendezvous breakpoint after they have already added
some modules to the list. This did not play well with our dynamic
loader plugin which was doing a diff of the the reported modules in the
before (RT_ADD) and after (RT_CONSISTENT) states. Specifically, it
caused us to miss some of the modules.

While I think the old behavior makes more sense, I don't think that lldb
is doing the right thing either, as the documentation states that we
should not be expecting a consistent view in the RT_ADD (and RT_DELETE)
states.

Therefore, this patch changes the lldb algorithm to compare the module
list against the previous consistent snapshot. This fixes the previous
issue, and I believe it is more correct in general. It also reduces the
number of times we are fetching the module info, which should speed up
the debugging of processes with many shared libraries.

The change in RefreshModules ensures we don't broadcast the loaded
notification for the dynamic loader (ld.so) module more than once.

Differential Revision: https://reviews.llvm.org/D128264
2022-07-01 08:08:22 +02:00
Emre Kultursay c0702ac07b [PATCH] [lldb-server] Skip shared regions for memory allocation
Differential Revision: https://reviews.llvm.org/D128832
2022-07-01 13:45:42 +08:00
Zequan Wu 8a790e65f4 [LLDB][NativePDB] Return LLDB_INVALID_ADDRESS in PdbIndex::MakeVirtualAddress when input is invalid due to missing address info in symbol/public records. 2022-06-30 14:34:20 -07:00
Jim Ingham 38ca754eb0 Apparently you need a special makefile flag to use threads on Linux.
This is a follow-up to https://reviews.llvm.org/D128776.
2022-06-30 12:10:17 -07:00
Jim Ingham b8e0b5a071 Threads which hit a breakpoint but fail the condition are considered
not to be hit.  But another thread might be hit at the same time and
actually stop.  So we have to be sure to switch the first thread's
stop info to eStopReasonNone or we'll report a hit when the condition
failed, which is confusing.

Differential Revision: https://reviews.llvm.org/D128776
2022-06-30 11:43:59 -07:00
Jonas Devlieghere 3a56858cee
[lldb] XFAIL TestObjCXXBridgedPO on macOS Ventura
TestObjCXXBridgedPO is broken on macOS Ventura (but not on macOS
Monterey). I took a look but it doesn't seem trivial. I'm XFAILing the
test until Adrian, who wrote the test, can take a look.

rdar://96224141
2022-06-30 09:20:56 -07:00
Pavel Labath cff509f33b [lldb] Fix libc++ string formatter for the "unstable" layout
D128285 only changed the stable (v1) layout, so the matching change in
D128694 broke the formatting of the unstable strings. This fixes that,
and ensures compatibility with all older layouts as well.
2022-06-30 16:44:54 +02:00
Muhammad Omair Javaid 8e9360db1b Fix PDB/func-symbols.test for Arm/Windows
PDB/func-symbols.test was orignally written for 32bit x86, keeping in
mind cdecl and stdcall calling conventions which does name mangling for
example like adding "_" underscore before function name.
This is only x86 specific but purpose of pointers.test is NOT to test
calling convention.
I have made a minor change to make this test pass on Windows/Arm.
2022-06-30 17:58:19 +04:00
Muhammad Omair Javaid dd01d9aadb Fix TestCommandScript.py for Arm/Windows
TestCommandScript.py fails on Arm/Windows due following issues:
https://llvm.org/pr56288
https://llvm.org/pr56292

LLDB fails to skip prologue and also step over library function or
nodebug functions fails due to PDB/DWARF mismatch.

This patch replace function breakpoint with line breakpoint so that we
can expect LLDB to stop on desired line. Also replace dwarf with PDB
debug info for this test only.
2022-06-30 17:48:28 +04:00
Muhammad Omair Javaid 8b7f5ee5f0 [LLDB] Fix TestSTL.py Makefile to remove -gdwarf O0
This is a follow up to my previous commit where TestSTL.py got broken
due to 9c6e043592.
Now that we force dwarf symbols by default on windows we dont need to
specifically put -gdwarf O0 in debug flags for this test.
2022-06-30 14:06:21 +04:00
Muhammad Omair Javaid 5fe0da6d7b [LLDB] Fix TestSTL.py on Windows
TestSTL.py was broken by 9c6e043592.
This patch fixes it with changes to its Makefile.
2022-06-30 13:27:14 +04:00
Fangrui Song 67854f9ed0 Use value_or instead of getValueOr. NFC 2022-06-29 21:55:02 -07:00
Kevin Cadieux a3ec54c660 [lldb] Fix unused variable warning in TraceHTR (NFC)
A warning was recently introduced in [D128576](https://reviews.llvm.org/D128576) due to now unused lambda `function_name_from_load_address`. This warning causes build failures when treating warnings as errors. This change expands the comment to also include the definition of this lambda, fixing the warning.

Error:
```
[3809/6000] Building CXX object tools/lldb/source/Plugins/TraceExporter/common/CMakeFiles/lldbPluginTraceExporterCommon.dir/TraceHTR.cpp.o
FAILED: tools/lldb/source/Plugins/TraceExporter/common/CMakeFiles/lldbPluginTraceExporterCommon.dir/TraceHTR.cpp.o
/usr/bin/clang++ -DHAVE_ROUND -DLLDB_CONFIGURATION_DEBUG -D_DEBUG -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/__w/1/b/llvm/Debug/tools/lldb/source/Plugins/TraceExporter/common -I/__w/1/llvm-project/lldb/source/Plugins/TraceExporter/common -I/__w/1/llvm-project/lldb/include -I/__w/1/b/llvm/Debug/tools/lldb/include -I/__w/1/b/llvm/Debug/include -I/__w/1/llvm-project/llvm/include -I/__w/1/llvm-project/llvm/../clang/include -I/__w/1/b/llvm/Debug/tools/lldb/../clang/include -I/__w/1/llvm-project/lldb/source -I/__w/1/b/llvm/Debug/tools/lldb/source -isystem /usr/include/libxml2 -fPIC -fvisibility-inlines-hidden -Werror -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion -Wmisleading-indentation -fdiagnostics-color -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -g  -fno-exceptions -gsplit-dwarf -std=c++14 -MD -MT tools/lldb/source/Plugins/TraceExporter/common/CMakeFiles/lldbPluginTraceExporterCommon.dir/TraceHTR.cpp.o -MF tools/lldb/source/Plugins/TraceExporter/common/CMakeFiles/lldbPluginTraceExporterCommon.dir/TraceHTR.cpp.o.d -o tools/lldb/source/Plugins/TraceExporter/common/CMakeFiles/lldbPluginTraceExporterCommon.dir/TraceHTR.cpp.o -c /__w/1/llvm-project/lldb/source/Plugins/TraceExporter/common/TraceHTR.cpp
/__w/1/llvm-project/lldb/source/Plugins/TraceExporter/common/TraceHTR.cpp:136:8: error: unused variable 'function_name_from_load_address' [-Werror,-Wunused-variable]
  auto function_name_from_load_address =
```

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D128874
2022-06-29 21:29:50 -07:00
Zequan Wu bd2044c108 [CodeView] Call llvm::codeview::visitMemberRecordStream with the deserialized CVType whose kind is FieldListRecord.
llvm::codeview::visitMemberRecordStream expects to receive an array ref that's FieldListRecord's Data not a CVType's data which has 4 more bytes preceeding. The first 2 bytes indicate the size of the FieldListRecord, and following 2 bytes is always 0x1203. Inside llvm::codeview::visitMemberRecordStream, it iterates to the data to check if first two bytes matching some type record kinds. If the size coincidentally matches one type kind, it will start parsing from there and causing crash.
2022-06-29 17:18:56 -07:00
Jonas Devlieghere 1b8c73522e
[lldb] Use assertState in even more tests (NFC)
Followup to D127355 and D127378, converting more instances of
assertEqual to assertState.
2022-06-29 17:05:58 -07:00
Jonas Devlieghere dee672ee85
[lldb] Skip instead of XFAIL TestGdbRemote_vContThreads on Darwin
The two XFAILed tests started timing out after D126983. Given that they
were XFAILed anyway I didn't investigate and just skipped them.
2022-06-29 16:34:34 -07:00
Jonas Devlieghere 3944780dd8
[lldb] Skip TestAppleSimulatorOSType is simulator isn't available
Skip TestAppleSimulatorOSType is simulator isn't available for the given
platform.
2022-06-29 15:10:16 -07:00
Jonas Devlieghere 65a7ebff33
[lldb] XFAIL TestVSCode_breakpointEvents.py on Ventura
TestVSCode_breakpointEvents.py is failing on macOS Ventura because we
receive 3 breakpoint events instead of one. This is likely the result of
dyld moving into the shared cache.
2022-06-29 15:00:57 -07:00
Muhammad Omair Javaid 9c6e043592 [LLDB] Allow API tests to override -gdwarf on Windows
This patch fixes LLDB API tests MakeFile.rules to allow overriding of
debug symbol flags when compiling tests for Windows.
Previously windows tests were forced to emit only dwarf debug symbols
as majority of the tests rely on dwarf debug info. After this patch
any test can override debug symbol flag by setting DEBUG_INFO_FLAG
variable in its make file.
2022-06-29 23:24:18 +04:00
Muhammad Omair Javaid f5ba0a3d05 Fix inline-record.test for Arm/Windows
This patch fixes inline-record.test to run on multiple platforms
including Arm/Windows. Test is fixed to expect any value for id
fields of functions and blocks returned by 'image lookup' command.
This field can be any value as it is internally generated id.
2022-06-29 23:21:02 +04:00
Pavel Labath 079c8ccb33 [lldb] Attempt to fix TestStepThroughTrampoline on windows 2022-06-29 19:59:24 +02:00
Walter Erquinigo a7d6c3effe [trace] Make events first class items in the trace cursor and rework errors
We want to include events with metadata, like context switches, and this
requires the API to handle events with payloads (e.g. information about
such context switches). Besides this, we want to support multiple
similar events between two consecutive instructions, like multiple
context switches. However, the current implementation is not good for this because
we are defining events as bitmask enums associated with specific
instructions. Thus, we need to decouple instructions from events and
make events actual items in the trace, just like instructions and
errors.

- Add accessors in the TraceCursor to know if an item is an event or not
- Modify from the TraceDumper all the way to DecodedThread to support
- Renamed the paused event to disabled.
- Improved the tsc handling logic. I was using an API for getting the tsc from libipt, but that was an overkill that should be used when not processing events manually, but as we are already processing events, we can more easily get the tscs.
event items. Fortunately this simplified many things
- As part of this refactor, I also fixed and long stating issue, which is that some non decoding errors were being inserted in the decoded thread. I changed this so that TraceIntelPT::Decode returns an error if the decoder couldn't be set up proplerly. Then, errors within a trace are actual anomalies found in between instrutions.

All test pass

Differential Revision: https://reviews.llvm.org/D128576
2022-06-29 09:19:51 -07:00
Michał Górny 4a95861d73 [lldb] [test] Avoid relying on signos in other fork tests
Sponsored by: The FreeBSD Foundation
2022-06-29 17:48:36 +02:00
Michał Górny e60ed2401b [lldb] [test] Un-XFAIL fork tests on arm as well
Sponsored by: The FreeBSD Foundation
2022-06-29 16:05:12 +02:00
Michał Górny 251165b2e4 [lldb] [test] Use raise(SIGSTOP) instead of trap in fork tests
Replace the use of "trap" with a new "stop" command in fork tests,
that maps to `raise(SIGSTOP)`.  Since traps do not increment PC on some
architectures (notably ARM), using traps would require special logic
to increment it while testing.  Using SIGSTOP avoids the problem
and is probably more logical, given that the purpose of the "trap"s
was to simply stop the inferior at a synchronization point.  This fixes
tests on AArch64 (and possibly ARM, I'll update XFAILs when it is
confirmed by the buildbot).

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128780
2022-06-29 15:37:26 +02:00
Pavel Labath 5e39198570 [lldb] Replace linux/uio.h with sys/uio.h in NativeRegisterContextLinux_s390x
Fixes PR56280.
2022-06-29 14:50:06 +02:00
Michał Górny 3c16fb3ab3 [lldb] [test] Fix variable overwrite in non-stop fork tests
Thanks to Pavel Labath for noticing the mistake in:
https://reviews.llvm.org/D128638#3618039

Sponsored by: The FreeBSD Foundation
2022-06-29 13:34:50 +02:00
Michael Daniels d8ad018869 [lldb] fix stepping through POSIX trampolines
The DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan() function was
doing the symbol lookup using the demangled name. This stopped working
with https://reviews.llvm.org/D118814. To get things working again, just
use the mangled name for the lookup instead.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D127999
2022-06-29 11:06:29 +02:00
Muhammad Omair Javaid 01bc838e45 [LLDB] Add PDB/calling-conventions.test for Arm/Windows
This patch renames PDB/calling-conventions.test to calling-conventions-x86.test.
Also restrict it to run only for target-x86*.
This patch also adds a arm specific test PDB/calling-conventions-arm.test which
tests that x86 specifc calling convention decorators are ignored by Arm compiler.

Reviewed By: labath

Differential Revision: https://reviews.llvm.org/D128678
2022-06-29 12:58:16 +04:00
Muhammad Omair Javaid a18baf16c6 [LLDB] Add Arm64 CodeView to LLDB regnum mapping
This patch writes a mapping structure for converting  CodeView Arm64 register numbers to LLDB Arm64 regnums.

This fixes various symbols and variable location test failures on AArch64/Windows.

Reviewed By: DavidSpickett

Differential Revision: https://reviews.llvm.org/D128221
2022-06-29 12:50:57 +04:00
Muhammad Omair Javaid 695c22c84a [LLDB] Fix PDB/pointers.test for 32bit Arm/Windows
PDB/pointers.test was orignally written for 32bit x86 keeping in mind
__cdecl and __stdcall calling conventions which does name mangling for
example like adding "_" underscore before function name.
This is only x86 specific but purpose of pointers.test is NOT to test
calling convention.
I am have made a few minor changes to this test which will make it pass
when run on Windows/Arm platform.

Reviewed By: mstorsjo

Differential Revision: https://reviews.llvm.org/D128668
2022-06-29 12:47:02 +04:00
Michał Górny 7fc12da898 [lldb] [test] Split TestGdbRemoteFork in two
Split the test that's gotten very long in two, in hope that it will
resolve the arm/aarch64 buildbot failures.  Even if it does not, it
could help pinpointing where the problem lies.

Sponsored by: The FreeBSD Foundation
2022-06-29 06:57:38 +02:00
Walter Erquinigo 6564ca188a [trace] Fix errors when handling command arguments
https://reviews.llvm.org/D128453 recently added some safety checks for
command arguments. Unfortunately, some few commands started failing due
to that, and this diff fixes it. But fortunately, the fix is trivial, which is
simply declaring the argument that these commands will receive.

Differential Revision: https://reviews.llvm.org/D128775
2022-06-28 17:54:30 -07:00
Walter Erquinigo f91d82816f [trace] Improve the TraceCursor iteration API
The current way ot traversing the cursor is a bit uncommon and it can't handle empty traces, in fact, its invariant is that it shold always point to a valid item. This diff simplifies the cursor API and allows it to point to invalid items, thus being able to handle empty traces or to know it ran out of data.

- Removed all the granularity functionalities, because we are not actually making use of that. We can bring them back when they are actually needed.
- change the looping logic to the following:

```
  for (; cursor->HasValue(); cursor->Next()) {
     if (cursor->IsError()) {
       .. do something for error
       continue;
     }
     .. do something for instruction
  }

```

- added a HasValue method that can be used to identify if the cursor ran out of data, the trace is empty, or the user tried to move to an invalid position via SetId() or Seek()
- made several simplifications to severals parts of the code.

Differential Revision: https://reviews.llvm.org/D128543
2022-06-28 16:50:12 -07:00
Med Ismail Bennani 44a114fec7 [lldb/Dataformatters] Adapt C++ std::string dataformatter for D128285
This patch changes the C++ `std::string` dataformatter to reflect
internal layout changes following D128285.

Now, in short-mode strings, in order to access the `__size_` and
`__is_long_` attributes, we need to access a packed anonymous struct,
which introduces another indirection.

We need to do the same in order to access the `__cap_` field for
long-mode strings.

This should fix the various test failures that are happening on
GreenDragon:

https://green.lab.llvm.org/green/job/lldb-cmake/44918/

rdar://96010248

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

Signed-off-by: Med Ismail Bennani <medismail.bennani@gmail.com>
2022-06-28 15:34:17 -07:00
Michał Górny 261d003350 [lldb] [llgs] Fix premature server exit if multiprocess+nonstop
Fix lldb-server in the non-stop + multiprocess mode to exit on vStopped
only if all processes have exited, rather than when the first one exits.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128639
2022-06-28 21:49:17 +02:00
Michał Górny b415f8e3df [lldb] [llgs] Add base nonstop fork/vfork tests
Extend the most of baseline fork tests to run in nonstop mode as well.
For more cases, we're just testing one example scenario to save time.
This patch does not cover tests that rely on correct exit handling,
as fixing that is addressed in a followup patch.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128638
2022-06-28 21:49:16 +02:00
Michał Górny e095cddb76 [lldb] Add a NativeProcessProtocol::Threads() iterable
Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128698
2022-06-28 21:49:16 +02:00
Jim Ingham f7bf9d13d5 TestIgnoredExceptions.py needs support from debugserver, so it
needs to be marked skip if out of tree debugserver.
2022-06-28 11:49:55 -07:00
Michał Górny 25f46084d8 [lldb] [test] XFAIL llgs tests failing on arm
Sponsored by: The FreeBSD Foundation
2022-06-28 17:02:59 +02:00
Michał Górny a1df636a8b [lldb] [test] Skip llgs tests broken due to #56268 on aarch64
Sponsored by: The FreeBSD Foundation
2022-06-28 16:24:38 +02:00
Yi Kong b83b82f9f4 [lldb] Fix build on older Linux kernel versions
PERF_COUNT_SW_DUMMY is introduced in Linux 3.12.

Differential Revision: https://reviews.llvm.org/D128707
2022-06-28 20:23:33 +08:00
Michał Górny f1dcc6af30 [lldb] [test] Mark test_vCont_supports_t llgs-only
Sponsored by: The FreeBSD Foundation
2022-06-28 06:06:54 +02:00
Jonas Devlieghere e06a88cbe9
[lldb] Use assertState in TestIgnoredExceptions 2022-06-27 16:30:47 -07:00
Jim Ingham c1b07d6177 Have CommandObjectParsed check for "commands that take no arguments".
This is currently being done in an ad hoc way, and so for some
commands it isn't being checked.  We have the info to make this check,
since commands are supposed to add their arguments to the m_arguments
field of the CommandObject.  This change uses that info to check whether
the command received arguments in error.

A handful of commands weren't defining their argument types, I also had
to fix them.  And a bunch of commands were checking for arguments by
hand, so I removed those checks in favor of the CommandObject one.  That
also meant I had to change some tests that were checking for the ad hoc
error outputs.

Differential Revision: https://reviews.llvm.org/D128453
2022-06-27 15:14:41 -07:00
Alex Langford ef5510d81b [NFC][lldb] Correct Module::FindFunctions documentation
Looks like a copy/paste from ModuleList::FindCompileUnits.
2022-06-27 12:33:05 -07:00
Jonas Devlieghere 9bdb7e5734
[lldb] Add a log dump command
Add a log dump command to dump logs to a file. This only works for
channels that have a log handler associated that supports dumping. For
now that's limited to the circular log handler, but more could be added
in the future.

Differential revision: https://reviews.llvm.org/D128557
2022-06-27 10:02:34 -07:00
Michał Górny fe80829289 [lldb] [llgs] Skip new vCont test on Windows
Sponsored by: The FreeBSD Foundation
2022-06-27 18:22:38 +02:00
Michał Górny b4f2d7cde5 [lldb] [llgs] Support "t" vCont action
Implement support for the "t" action that is used to stop a thread.
Normally this action is used only in non-stop mode.  However, there's
no technical reason why it couldn't be also used in all-stop mode,
e.g. to express "resume all threads except ..." (`t:...;c`).

While at it, add a more complete test for vCont correctly resuming
a subset of program's threads.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D126983
2022-06-27 17:33:59 +02:00
Mikhail Goncharov fe6db8d03f Revert "[lldb] Fix thread step until to not set breakpoint(s) on incorrect line numbers"
This reverts commit a57b62deef.

lldb-aarch64-ubuntu buildbot test fails since https://lab.llvm.org/buildbot/#/builders/96/builds/25128
2022-06-27 10:18:39 +02:00
Kazu Hirata 96d1b4ddb2 [lld] Don't use Optional::hasValue (NFC)
This patch replaces x.hasValue() with x where x is contextually
convertible to bool.
2022-06-26 19:29:40 -07:00
Kazu Hirata 3b7c3a654c Revert "Don't use Optional::hasValue (NFC)"
This reverts commit aa8feeefd3.
2022-06-25 11:56:50 -07:00
Kazu Hirata aa8feeefd3 Don't use Optional::hasValue (NFC) 2022-06-25 11:55:57 -07:00
Michał Górny 1452e2e5cb Reland "[lldb] [llgs] Support multiprocess in qfThreadInfo"
Now preserving the non-standard behavior of returning "OK" response
when there is no debugged process.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128152
2022-06-25 15:15:37 +02:00
Michał Górny f609b54e24 Revert "[lldb] [llgs] Support multiprocess in qfThreadInfo"
This reverts part of commit 75757c86c6.
It broke the following test:

  commands/target/auto-install-main-executable/TestAutoInstallMainExecutable.py

I need more time to figure it out, so I'm reverting the code changes
and marking the tests depending on them xfail.
2022-06-25 09:46:28 +02:00
Jonas Devlieghere be265d25ca
[lldb] Add support for specifying a log handler
This patch adds a new flag to `log enable`, allowing the user to specify
a custom log handler. In addition to the default (stream) handler, this
allows using the circular log handler (which logs to a fixed size,
in-memory circular buffer) as well as the system log handler (which logs
to the operating system log).

Differential revision: https://reviews.llvm.org/D128323
2022-06-24 18:24:00 -07:00
Venkata Ramanaiah Nalamothu a57b62deef [lldb] Fix thread step until to not set breakpoint(s) on incorrect line numbers
The requirements for "thread until <line number>" are:

a) If any code contributed by <line number> or the nearest subsequent of <line number> is executed before leaving the function, stop
b) If you end up leaving the function w/o triggering (a), then stop

In case of (a), since the <line number> may have multiple entries in the line table and the compiler might have scheduled/moved the relevant code across, and the lldb does not know the control flow, set breakpoints on all the line table entries of best match of <line number> i.e. exact or the nearest subsequent line.

Along with the above, currently, CommandObjectThreadUntil is also setting the breakpoints on all the subsequent line numbers after the best match and this latter part is wrong.

This issue is discussed at http://lists.llvm.org/pipermail/lldb-dev/2018-August/013979.html.

In fact, currently `TestStepUntil.py` is not actually testing step until scenarios and `test_missing_one` test fails without this patch if tests are made to run. Fixed the test as well.

Reviewed By: jingham

Differential Revision: https://reviews.llvm.org/D50304
2022-06-25 00:01:04 +05:30
Jonas Devlieghere 87a3293961
[lldb] Move Host::SystemLog out of !defined(_WIN32)
The definition of Host::SystemLog was (unintentionally) guarded by
!defined(_WIN32).
2022-06-24 11:18:31 -07:00
Jonas Devlieghere 5a08280659
[lldb] Fix flakiness in shell tests that mixed stderr and stdout
Because the diagnostic events are processed by the default event handler
in its own thread, tests cannot rely on output ordering. Split stdout
and stderr to make the test reliable again.
2022-06-24 10:53:15 -07:00
Jonas Devlieghere 1e5d5261e2
[lldb] Add SystemLogHandler for emitting log messages to the system log
Add a system log handler that emits log messages to the operating system
log. In addition to the log handler itself, this patch also introduces a
new Host::SystemLog helper function to abstract over writing to the
system log.

Differential revision: https://reviews.llvm.org/D128321
2022-06-24 10:53:15 -07:00
Jonas Devlieghere 6879391908
[lldb] Replace Host::SystemLog with Debugger::Report{Error,Warning}
As it exists today, Host::SystemLog is used exclusively for error
reporting. With the introduction of diagnostic events, we have a better
way of reporting those. Instead of printing directly to stderr, these
messages now get printed to the debugger's error stream (when using the
default event handler). Alternatively, if someone is listening for these
events, they can decide how to display them, for example in the context
of an IDE such as Xcode.

This change also means we no longer write these messages to the system
log on Darwin. As far as I know, nobody is relying on this, but I think
this is something we could add to the diagnostic event mechanism.

Differential revision: https://reviews.llvm.org/D128480
2022-06-24 09:46:26 -07:00
Walter Erquinigo b8dcd0ba26 [NFC][lldb][trace] Rename trace session to trace bundle
As previously discussed with @jj10306, we didn't really have a name for
the post-mortem (or offline) trace session representation, which is in
fact a folder with a bunch of files. We decided to call this folder
"trace bundle", and the main JSON file in it "trace bundle description
file". This naming is pretty decent, so I'm refactoring all the existing
code to account for that.

Differential Revision: https://reviews.llvm.org/D128484
2022-06-24 08:41:33 -07:00
Michał Górny c1829e0ec5 [lldb] [test] Move part of fork tests to common helper
Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128361
2022-06-24 17:20:25 +02:00
Michał Górny 4b485fc0ea [lldb] [llgs] Introduce an AppendThreadIDToResponse() helper
Introduce a helper function to append GDB Remote Serial Protocol "thread
IDs", with optional PID in multiprocess mode.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128324
2022-06-24 17:20:24 +02:00
Michał Górny e827e5186f [lldb] [llgs] Implement the 'T' packet
Implement the 'T' packet that is used to verify whether the specified
thread belongs to the debugged processes.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128170
2022-06-24 17:20:24 +02:00
Michał Górny 630da0e309 [lldb] [llgs] Include PID in QC response in multiprocess mode
Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128156
2022-06-24 17:20:24 +02:00
Michał Górny 14d6707335 [lldb] [llgs] Add a test for multiprocess register read/write
Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128153
2022-06-24 17:20:24 +02:00
Michał Górny 75757c86c6 [lldb] [llgs] Support multiprocess in qfThreadInfo
Update the `qfThreadInfo` handler to report threads of all debugged
processes and include PIDs when in multiprocess mode.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128152
2022-06-24 17:20:24 +02:00
Michał Górny 0481d8efa9 [lldb] [llgs] Add a test for multiprocess memory read/write
Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D128150
2022-06-24 17:20:24 +02:00
Michał Górny a3422793e0 [lldb] [llgs] Support resuming one process with PID!=current via vCont
Extend vCont function to support resuming a process with an arbitrary
PID, that could be different than the one selected via Hc (or no process
at all may be selected).  Resuming more than one process simultaneously
is not supported yet.

Remove the ReadTid() method that was only used by Handle_vCont(),
and furthermore it was wrongly using m_current_process rather than
m_continue_process.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D127862
2022-06-24 17:20:23 +02:00
Michał Górny 3266b11714 [lldb] [llgs] Add test for resuming via c in multiprocess scenarios
Add a test verifying that it is possible to resume a single process
via the `c` packet when multiple processes are being debugged.  This
includes a tiny change to the test program — when `fork()` is called,
the child process is no longer terminated immediately but continues
performing the same tasks as queued for the parent.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D127755
2022-06-24 17:20:23 +02:00
Michał Górny c18784ba33 [lldb] [llgs] Implement the vKill packet
Implement the support for the vKill packet.  This is the modern packet
used by the GDB Remote Serial Protocol to kill one of the debugged
processes.  Unlike the `k` packet, it has well-defined semantics.

The `vKill` packet takes the PID of the process to kill, and always
replies with an `OK` reply (rather than the exit status, as LLGS does
for `k` packets at the moment).  Additionally, unlike the `k` packet
it does not cause the connection to be terminated once the last process
is killed — the client needs to close it explicitly.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D127667
2022-06-24 17:20:23 +02:00
Michał Górny e8fe7e930a [lldb] [llgs] Make `k` kill all processes, and fix multiple exits
Modify the behavior of the `k` packet to kill all inferiors rather than
just the current one.  The specification leaves the exact behavior
of this packet up to the implementation but since vKill is specifically
meant to be used to kill a single process, it seems logical to use `k`
to provide the alternate function of killing all of them.

Move starting stdio forwarding from the "running" response
to the packet handlers that trigger the process to start.  This avoids
attempting to start it multiple times when multiple processes are killed
on Linux which implicitly causes LLGS to receive "started" events
for all of them.  This is probably also more correct as the ability
to send "O" packets is implied by the continue-like command being issued
(and therefore the client waiting for responses) rather than the start
notification.

Sponsored by: The FreeBSD Foundation
Differential Revision: https://reviews.llvm.org/D127500
2022-06-24 17:20:23 +02:00
Muhammad Omair Javaid 91d61c1431 [LLDB] Mark TestExprsChar Xfail for Windows/AArch64
test_unsigned_char test in TestExprsChar.py fails on AArch64/Windows
platform. There is known bug already present for the failure for various
arch/os combinations. This patch marks the test as xfail for
windows/AArch64.
2022-06-24 13:59:22 +04:00
Jonas Devlieghere 6fa9120080
[lldb] Fix up Objective-C ISA pointers
Support stripping the PAC bits from Objective-C ISA pointers in the
Objective-C runtime plugin.
2022-06-23 14:16:29 -07:00
Chelsea Cassanova 40aace59cc [lldb/Fuzzer] Have fuzzers write artifacts to specific directory
This makes the LLDB fuzzers write their fuzzer artifacts to
their own directory in the build directory. It also adds an artifact
prefix to the target fuzzer to make it easier to tell which fuzzer
wrote the artifact.

Differential revision: https://reviews.llvm.org/D128450
2022-06-23 16:55:23 -04:00
Jim Ingham a1f20da315 The help string for stop-on-shared-library-load was copied to stop-on-exec.
Fix it so it says it does what it does.
2022-06-23 13:54:50 -07:00
Jonas Devlieghere 70841b97eb
[lldb] Make thread safety the responsibility of the log handlers
Drop the thread-safe flag and make the locking strategy the
responsibility of the individual log handler.

Previously we got away with a non-thread safe mode because we were using
unbuffered streams that rely on the underlying syscalls/OS for
synchronization. With the introduction of log handlers, we can have
arbitrary logic involved in writing out the logs. With this patch the
log handlers can pick the most appropriate locking strategy for their
particular implementation.

Differential revision: https://reviews.llvm.org/D127922
2022-06-23 09:12:05 -07:00
Jonas Devlieghere 09dea54669
[lldb] Support a buffered logging mode
This patch adds a buffered logging mode to lldb. A buffer size can be
passed to `log enable` with the -b flag. If no buffer size is specified,
logging is unbuffered.

Differential revision: https://reviews.llvm.org/D127986
2022-06-23 09:12:01 -07:00
David Spickett 5e7ddb0ddf Revert "[LLDB] Handle DIE with DW_AT_low_pc and empty ranges"
This reverts commit 1beededc0e7d86d09cee972f0b9f0030a139cab4.

Due to failures on the Arm/AArch64 build bots:
https://lab.llvm.org/buildbot/#/builders/96/builds/25032
2022-06-23 10:33:05 +00:00
Chelsea Cassanova 46be5faaf0 [lldb/Fuzzer] Add command interpreter fuzzer for LLDB
This adds a command interpreter fuzzer to LLDB's fuzzing library.
The input data from the fuzzer is used as input for the command
interpreter.
Input data for the fuzzer is guided by a dictionary of keywords used in
LLDB, such as "breakpoint", "target" and others.

Differential revision: https://reviews.llvm.org/D128292
2022-06-22 17:42:55 -04:00
Jonas Devlieghere d95c406c20
[lldb] Fix off-by-one error in the AppleObjCRuntimeV2 utility function
Fix an off-by-one error in the utility function used to extract the
dynamic class info. This resulted in a buffer overflow in the inferior
which interrupted our utility function.

Differential revision: https://reviews.llvm.org/D128377
2022-06-22 13:57:24 -07:00
Jonas Devlieghere f0d87dfe30
[lldb] Return the correct utility function in AppleObjCRuntimeV2
A copy/paste error in GetClassInfoUtilityFunction resulted in the wrong
utility function being returned: copyRealizedClassList instead of
getRealizedClassList_trylock.

Differential revision: https://reviews.llvm.org/D128378
2022-06-22 13:57:23 -07:00
Jim Ingham bae10a6bbb Fix a bug with "process continue -b" when no breakpoints are
passed.  I was passing the empty list of breakponts to the
VerifyBreakpointList routine, but that treats empty as "choose
the default breakpoint" which we don't want here.
2022-06-22 12:18:07 -07:00