374 Commits

Author SHA1 Message Date
Piyush Jaiswal
e8566f83d2
[lldb][python] Add polymorphic __getitem__ to SBModuleSpecList for Pythonic indexing (#189125)
### Summary

`SBModuleSpecList` already supports `len()` and iteration via `__len__`
and `__iter__`, but is not subscriptable — `specs[0]` raises
`TypeError`.

This adds a `__getitem__` method that supports integer indexing (with
negative index support) and string lookup using `endswith()` matching,
which works for both Unix and Windows paths.

### Supported key types

| Key type | Example | Behavior |
|---|---|---|
| `int` | `specs[0]`, `specs[-1]` | Direct index with negative index
support |
| `str` | `specs['a.out']`, `specs['/usr/lib/liba.dylib']` | Lookup by
basename or partial/full path via `endswith()`. Returns first match or
`None` |

### Error handling

- **`IndexError`** for out-of-bounds integer indices
- **`TypeError`** for unsupported key types (e.g., `float`)
- **`None`** for string lookups with no match

### Before

```python
>>> specs = lldb.SBModuleSpecList.GetModuleSpecifications('/bin/ls')
>>> specs[0]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'SBModuleSpecList' object is not subscriptable
```

### After

```python
>>> import lldb, re
>>> specs = lldb.SBModuleSpecList.GetModuleSpecifications('/bin/ls')

>>> specs[0]
file = '/bin/ls', arch = x86_64-*-linux, uuid = 3CCC0D8A-..., object size = 140928
>>> specs[-1]
file = '/bin/ls', arch = x86_64-*-linux, uuid = 3CCC0D8A-..., object size = 140928

>>> specs['ls']
file = '/bin/ls', arch = x86_64-*-linux, uuid = 3CCC0D8A-..., object size = 140928

>>> specs[999]
IndexError: list index out of range
>>> specs[1.5]
TypeError: unsupported index type: <class 'float'>
```

### Test plan

Added test_module_spec_list_indexing to TestSBModule.py covering:

- Positive and negative integer indexing
- Out-of-bounds raises IndexError
- Unsupported key type raises TypeError
- String lookup by basename and full path (endswith() matching)
- Missing key returns None

```
bin/llvm-lit -sv lldb/test/API/python_api/sbmodule/TestSBModule.py
```

```
PASS: LLDB :: test_GetObjectName_dwarf (TestSBModule.SBModuleAPICase)
PASS: LLDB :: test_GetObjectName_dwo (TestSBModule.SBModuleAPICase)
PASS: LLDB :: test_module_spec_list_indexing_dwarf (TestSBModule.SBModuleAPICase)
PASS: LLDB :: test_module_spec_list_indexing_dwo (TestSBModule.SBModuleAPICase)
----------------------------------------------------------------------
Ran 12 tests in 1.854s

OK (skipped=6)
```

Co-authored-by: Piyush Jaiswal <piyushjais@meta.com>
2026-04-06 14:48:18 -07:00
Dave Lee
f72a150db0
[lldb] Disallow SHARED_BUILD_TESTCASE for non-default self.build() (#188523)
Change `self.build(...)` to assert if called with arguments of any kind,
for tests which have `SHARED_BUILD_TESTCASE` enabled (the default).

This also changes all tests that began asserting with this change, tests
which call `self.build(...)` with arguments.

---------

Co-authored-by: Adrian Prantl <adrian.prantl@gmail.com>
2026-03-25 14:37:20 -07:00
Jonas Devlieghere
85bdc271e5
[lldb] Use SBProcess.FixAddress in address_ranges_helper.py (#185802)
Use `SBProcess.FixAddress` in `address_ranges_helper.py` to support
arm64e and ARM's Memory Tagging Extension (MTE) which rely on TBI to
encode data in the top byte, which in this mode is ignored by the HW.

This fixes TestFindInMemory.py and TestFindRangesInMemory.py when
running the LLDB test suite with MTE.
2026-03-11 16:32:15 -07:00
Jim Ingham
ecd6f8c22b Revert "Add the ability to "allow another thread to see the private state" mode. (#184272)"
This reverts commit 97572c1860efeeb97b5940927cee72081b61810a.

This patch seems to cause TestWatchpointCommandPython.py to time out
on the ubuntu buildbots (but nowhere else that I can find so far.)  The
timeout is weird too, the TEST FILE is timing out but the individual
tests aren't being shown and there's no other output.  Grrr...
Anyway I'll revert this and then see if I can do some guessing about
how this change might cause the test to fail.
2026-03-05 12:09:07 -08:00
Jim Ingham
c969b5fe76 Revert "Skip some tests on Windows. They were already expected fail and"
This reverts commit 894408ded44151e4e34a3402210f671355d66310.

These tests were added by 97572c1860efeeb97b5940927cee72081b61810a
and I am reverting that as well.
2026-03-05 12:09:07 -08:00
Jim Ingham
894408ded4 Skip some tests on Windows. They were already expected fail and
I needed to use "sleep" so now the test file won't compile.  So
switching to skip...
2026-03-05 10:11:50 -08:00
jimingham
97572c1860
Add the ability to "allow another thread to see the private state" mode. (#184272)
When lldb stops to run a breakpoint condition or other callback that has
to happen between the private stop and returning control to the user, it
will run in the state where the public state is still "running". But if
the callback needs to run lldb commands or python code, it needs to see
the correct "stop" state.

We used to handle that by switching the public state to stopped before
running the callbacks. However, that opened a window where we are still
handling the stop event and another thread would be allowed to continue
the target or do other actions that can interfere with that orderly
process.

This patch adds the ability to designate a particular thread as "seeing
the private state" while all other threads see the "public state". Then
when we run a breakpoint callback, no threads but the one that is
actually running the callback will see the state change until the event
has been delivered to the primary state listener.

It also adds a test that while a long-running breakpoint callback runs,
another thread continues to see the state as running.
2026-03-05 08:17:16 -08:00
John Harrison
6b3f57de0a
[lldb] Skip SBBlock test on Windows. (#184818)
Skipping this test to unblock CI.
2026-03-05 08:12:19 -08:00
John Harrison
cee0703cea
[lldb] Fixing the python_api/block tests. (#184647)
Renaming the file to be unique and updating the symbols for Windows.
2026-03-04 16:03:42 -08:00
John Harrison
5e5f7efd77
[lldb] Expose block equality with SBBlock. (#184222)
Adding the `operator==` and `operator!=` for SBBlock. This should allow
us to compare blocks within a frame, like:

```python
block = frame.GetBlock()
while True:
  if block == frame.GetFrameBlock():
    # we're at the top function scope.
  else:
    # we're at an inner block scope.
```
2026-03-03 16:19:58 -08:00
Felipe de Azevedo Piovezan
09217ba904
[lldb] Disable shared build for TestTemplateArgs,TestEvents,TestTypeList (#184304)
See https://github.com/llvm/llvm-project/pull/181720
2026-03-03 09:34:39 +00:00
Sergei Barannikov
b881949ee4
[lldb] Drop incomplete non-8-bit bytes support (#182025)
This was originally introduced to support kalimba DSPs featuring 24-bit
bytes by f03e6d84 and also c928de3e, but the kalimba support was mostly
removed by f8819bd5. This change removes the rest of the support, which
was far from complete.
2026-02-19 13:01:02 +03:00
Dave Lee
b9225e8607
[lldb] Allow tests to share a single build (#181720)
This changes Python API tests to use a single build shared across all
test functions, instead of the previous default behavior of a separate
build dir for each test function.

This build behavior opt-out, tests can use the previous behavior of one
individual (unshared) build directory per test function, by setting
`SHARED_BUILD_TESTCASE` to False (in the test class).

The motivation is to make the test suite more efficient, by not
repeatedly building the same test source. When running tests on my macOS
machine, this reduces the time of `ninja check-lldb-api` by almost 60%
(sample numbers: from ~492s down to ~207s = 58%). Almost 5min time
saved.

Each test function still calls `self.build()`, but only the first call
will do a build, in the subsequent tests `make` will be a no-op because
the sources won't have changed.
2026-02-18 10:38:45 -08:00
Med Ismail Bennani
cfc311ed78
[lldb/API] Add __getitem__ subscript support to python SBAPI list class (#181457)
This patch adds __getitem__ method to the SBAPI list classes that were
missing subscript support, enabling Pythonic index access (e.g.,
list[0], list[-1]) in Python bindings.

The implementation adds __getitem__ to the following classes:
- SBStringList
- SBFileSpecList
- SBProcessInfoList
- SBMemoryRegionInfoList
- SBThreadCollection
- SBBreakpointList
- SBModuleSpecList
- SBTypeList

Each implementation follows the same pattern:
- Type validation (raises TypeError for non-integer indices)
- Range validation with negative index support (raises IndexError for
out-of-range)
- Delegates to the appropriate Get*AtIndex() method

The changes are in SWIG interface extension files (.i), implementing the
__getitem__ method in Python bindings while maintaining compatibility
with existing Get*AtIndex() API.

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2026-02-14 04:43:11 +00:00
jimingham
41cc71e9b1
Disable TestCancelAttach.py for linux -> linux remote (#180092)
This test was already disabled going from windows -> linux because it
was timing out there.

The PR: https://github.com/llvm/llvm-project/pull/179799 seems to have
exacerbated whatever this stall was, and now we're seeing it when
debugging from a linux host to a remote linux as well.

The native local host tests works correctly on all the bots that we
have, however. So I'm disabling the remote test till we can figure out
why this is problematic.
2026-02-05 17:27:42 -08:00
Ebuka Ezike
78f9d78b13
[lldb] Fix Python stderr redirection in test (#177970)
Python's internal stderr may differ from sys.stderr. 
When Python writes errors, it uses its internal stderr rather than the
overwritten sys.stderr.
This may not be the same file/handle

Fix the test to explicitly write to the specified stderr.
2026-01-26 22:20:55 +00:00
Matej Košík
8aa9c717f6
[lldb] Make sure that the "TypeSystemClang::GetBuiltinTypeByName" method returns the correct value also for "_BitInt(...)" types. (#165857)
When trying to get the `SBType` object corresponding to the
`_BitInt(...)` type name, we have noticed that the
`SBTarget::FindFirstType` metod returns `nil`. This branch proposes:
- some test that demonstrate that the problem exists
- a possible fix

---------

Co-authored-by: Matej Košík <matej.kosik@codasip.com>
Co-authored-by: Michael Buch <michaelbuch12@gmail.com>
2026-01-13 09:03:49 +00:00
Jonas Devlieghere
ae29bfd9db
Revert "[LLDB] Swig python extensions tests for SBTargetExtention" (#175251)
Reverts llvm/llvm-project#173473
2026-01-09 21:58:37 +00:00
Hamza Hassanain
1117d2a35f
[LLDB] Swig python extensions tests for SBTargetExtention (#173473)
Implements part of #168920
2026-01-09 15:00:59 -06:00
Matej Košík
42368f9194
[lldb] fix a problem in the ValueObject::GetExpressionPath method (#171521)
Consider the following program:
```
int main() {
  int foo[2][3][4];
  int (*bar)[3][4] = foo;
  return 0;
}
```
If we:
- compile this program
- launch an LLDB debugging session
- launch the process and let it stop at the `return 0;` statement
then the following LLDB command:
```
(lldb) script lldb.frame.FindVariable("bar").GetChildAtIndex(0).get_expr_path()
```
will produce the following output:
```
bar->[0]
```
What we were expecting:
- a valid expression in the C programming language
- that would allow us (in the scope of the `main` function) access the
appropriate object.

What we've got is a string that does not represent a valid expression in
the C programming language.

This pull-request proposes a fix to this problem.

---------

Co-authored-by: Matej Košík <matej.kosik@codasip.com>
2026-01-09 14:53:56 -06:00
Ebuka Ezike
21a1e6e6a7
[lldb] skip the python interactive I/O test on windows (#175055)
There is no indication this ever worked on windows as this is the first
test that checks python interactive console from a file.

Looking at the error from the CI, It closed the interpreter before
running any python commands.
Will reconfirm this when I have access to a windows machine. 


From https://github.com/llvm/llvm-project/pull/174216
2026-01-08 20:16:42 +00:00
Ebuka Ezike
43cb4631c1
[lldb] Fix typed commands not shown on the screen (#174216)
The cause is that in `python3.14`, `fcntl.ioctl` now throws a buffer
overflow error
when the buffer is too small or too large (see
https://github.com/python/cpython/pull/132919). This caused the Python
interpreter to fail terminal detection and not properly echo user
commands back to the screen.

Fix by dropping the custom terminal size check entirely and using the
built-in `sys.stdin.isatty()` instead.

Fixes #173302
2026-01-08 18:46:03 +00:00
David Spickett
38657c0ded
[lldb] Add zlib to version -v output (#174753)
I know this is required for at least one feature, because
TestSectionAPI.py has failures if zlib isn't enabled. So I think it's
useful for users to be able to check.

Now that it's in the config, I have also used it to make a test
annotation so we don't get the failure in TestSectionAPI.py when zlib is
disabled.

Which for future reference was:
Traceback (most recent call last):
File
"/home/davspi01/llvm-project/lldb/packages/Python/lldbsuite/test/decorators.py",
line 452, in wrapper
    return func(self, *args, **kwargs)
File
"/home/davspi01/llvm-project/lldb/test/API/python_api/section/TestSectionAPI.py",
line 67, in test_compressed_section_data
self.assertEqual(section_data, [0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
0x80, 0x90])
AssertionError: Lists differ: [] != [32, 48, 64, 80, 96, 112, 128, 144]

As it failed to decode the compressed section.
2026-01-07 15:26:55 +00:00
David Spickett
f5a198b8aa
[lldb][test] Xfail 3 backtrace related tests on Windows on Arm (#172300)
Since we updated our buildbot setup, these have been failing. Ignore
them until we have time to find the real problem, which is something to
do with failing to backtrace, or missing debug info when we do.
2025-12-15 14:04:02 +00:00
Med Ismail Bennani
41f643ab7e
[lldb] Add support for synthetic LineEntry objects without valid address ranges (#158811)
Scripted frames that materialize Python functions are PC-less by design,
meaning they don't have valid address ranges. Previously,
LineEntry::IsValid()
required both a valid address range and a line number, preventing
scripted
frames from creating valid line entries for these synthetic stack
frames.

Relaxing this requirement is necessary since
`SBSymbolContext::SetLineEntry`
will first check if the LineEntry is valid and discard it otherwise.

This change introduces an `synthetic` flag that gets set when LineEntry
objects are created or modified through the SBAPI (specifically via
SetLine).
When this flag is set, IsValid() no longer requires a valid address
range,
only a valid line number.

This is risk-free because the flag is only set for LineEntry objects
created
through the SBAPI, which are primarily used by scripted processes and
frames.
Regular debug information-derived line entries continue to require valid
address ranges.

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2025-12-04 20:48:49 +00:00
Vladislav Dzhidzhoev
b13b41a891
Revert "[LLDB] Add SBFrameExtensions Tests (#169236)" (#170555)
This reverts commit 5e5937c3d2e493a48837b2bdf179a53e8b80a66a, since the
added test fails on the `lldb-x86_64-win` buildbot.

https://lab.llvm.org/buildbot/#/builders/211/builds/4246
2025-12-03 22:01:34 +01:00
Ahmed Nour
5e5937c3d2
[LLDB] Add SBFrameExtensions Tests (#169236)
Fixes part of https://github.com/llvm/llvm-project/issues/168920
2025-12-02 10:02:11 -08:00
Ebuka Ezike
5c552c5cff
[lldb] Fix GetExpressionPath for vector registers (#169210)
Vector registers have synthetic values for display purposes. This causes
SBValue::GetExpressionPath to dispatch
to ValueObjectSynthetic instead of ValueObjectRegister, producing
incorrect results.

Fixes #147144
2025-12-02 17:10:08 +00:00
n2h9
a4d42775b9
[lldb] [scripting bridge] 167388 chore: add api to return arch name for target (#168273)
This pr fixes #167388 .

## Description

This pr adds new method `GetArchName` to `SBTarget` so that no need to
parse triple to get arch name in client code.

## Testing

### All from `TestTargetAPI.py`

run test with

```
./build/bin/lldb-dotest -v -p TestTargetAPI.py
```
<details>
<summary>existing tests (without newly added)</summary>
<img width="1425" height="804" alt="image"
src="https://github.com/user-attachments/assets/617e4c69-5c6b-44c4-9aeb-b751a47e253c"
/>
</details>

<details>
<summary>existing tests (with newly added)</summary>
<img width="1422" height="778" alt="image"
src="https://github.com/user-attachments/assets/746990a1-df88-4348-a090-224963d3c640"
/>

</details>

### Only `test_get_arch_name`

run test with 
```
./build/bin/lldb-dotest -v -p TestTargetAPI.py -f test_get_arch_name_dwarf -f test_get_arch_name_dwo -f test_get_arch_name_dsym lldb/test/API/python_api/target

```
<details>
<summary>only newly added</summary>
<img width="1422" height="778" alt="image"
src="https://github.com/user-attachments/assets/fcaafa5d-2622-4171-acee-e104ecee0652"
/>
</details>

---------

Signed-off-by: Nikita B <n2h9z4@gmail.com>
Co-authored-by: Jonas Devlieghere <jonas@devlieghere.com>
2025-11-26 11:36:19 -08:00
Jonas Devlieghere
6dad2c2cfb
[lldb] Add a test for capturing stdout/stderr from Python commands (#168138) 2025-11-14 22:43:01 +00:00
Jacob Lalonde
32ebf635c2
[LLDB] Fix debuginfo ELF files overwriting Unified Section List (#166635)
Recently I've been deep diving ELF cores in LLDB, aspiring to move LLDB
closer to GDB in capability. One issue I encountered was a system lib
losing it's unwind plan when loading the debuginfo. The reason for this
was the debuginfo has the eh_frame section stripped and the main
executable did not.

The root cause of this was this line in
[ObjectFileElf](163933e9e7/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (L1972))
```
  // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
  // unified section list.
  if (GetType() != eTypeDebugInfo)
    unified_section_list = *m_sections_up;
```

This would always be executed because CalculateType can never return an
eTypeDebugInfo
```
ObjectFile::Type ObjectFileELF::CalculateType() {
  switch (m_header.e_type) {
  case llvm::ELF::ET_NONE:
    // 0 - No file type
    return eTypeUnknown;

  case llvm::ELF::ET_REL:
    // 1 - Relocatable file
    return eTypeObjectFile;

  case llvm::ELF::ET_EXEC:
    // 2 - Executable file
    return eTypeExecutable;

  case llvm::ELF::ET_DYN:
    // 3 - Shared object file
    return eTypeSharedLibrary;

  case ET_CORE:
    // 4 - Core file
    return eTypeCoreFile;

  default:
    break;
  }
  return eTypeUnknown;
}
```

This makes sense as there isn't a explicit sh_type to denote that this
file is a debuginfo. After some discussion with @clayborg and
@GeorgeHuyubo we settled on joining the exciting unified section list
with whatever new sections were being added. Adding each new unique
section, or taking the section with the maximum file size. We picked
this strategy to pick the section with the most information. In most
scenarios, LHS should be SHT_NOBITS and RHS would be SHT_PROGBITS.

Here is a diagram documenting the existing vs proposed new way.
<img width="1666" height="1093" alt="image"
src="https://github.com/user-attachments/assets/73ba9620-c737-439e-9934-ac350d88a3b5"
/>
2025-11-06 15:56:11 -08:00
Med Ismail Bennani
d584d00ed2
[lldb] Introduce SBFrameList for lazy frame iteration (#166651)
This patch introduces `SBFrameList`, a new SBAPI class that allows
iterating over stack frames lazily without calling
`SBThread::GetFrameAtIndex` in a loop.

The new `SBThread::GetFrames()` method returns an `SBFrameList` that
supports Python iteration (`for frame in frame_list:`), indexing
(`frame_list[0]`, `frame_list[-1]`), and length queries (`len()`).

The implementation uses `StackFrameListSP` as the opaque pointer,
sharing the thread's underlying frame list to ensure frames are
materialized on-demand.

This is particularly useful for ScriptedFrameProviders, where user
scripts will be to iterate, filter, and replace frames lazily without
materializing the entire stack upfront.

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2025-11-05 16:02:02 -08:00
Ebuka Ezike
c46bfed1a4
[lldb] Add alternative SBThread::GetStopDescription (#165379)
the function signature for `GetStopDescription` is
`lldb::SBThread::GetStopDescription(char *dst_or_null, size_t len)`.
To get a description you need to call the function first time to get the
buffer size. a second time to get the description.

This is little worse from the python size as the signature is
`lldb.SBThread.GetStopDescription(int: len) -> list[str]` the user has
to pass the max size as possible with no way of checking if it is
enough.

This patch adds a new api
`lldb.SBThread.GetStopDescription(desc: lldb.SBStream()) -> bool` `bool
lldb::SBThread::GetStopDescription(lldb::SBStream &description)` which
handles this case.

Adds new Test case for lua.
2025-10-30 21:43:53 +00:00
Wanyi
068e1796ba
[lldb][swig] Support SBFileSpec::GetPath (#162964)
# Summary
`SBFileSpec::GetPath(char *dst_path, size_t dst_len)` contains `char*`
type argument. Need to handle this for python. Fortunately there're
already similar definitions we can reuse.

# Test Plan
Start the freshly built lldb and run the following code
```
$ lldb
(lldb) script
Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
>>> debugger = lldb.SBDebugger.Create()
>>> debugger.SetAsync (False)
>>> target = debugger.CreateTarget("~/tmp/hello")
>>> target.IsValid()
True
>>> breakpoint = target.BreakpointCreateByName('main', 'hello')
>>> breakpoint.GetNumLocations()
1
>>> process = target.LaunchSimple (None, None, os.getcwd())
>>> process.IsValid()
True
>>> thread = process.GetThreadAtIndex(0)
>>> frame = thread.GetFrameAtIndex(0)
>>> line = frame.GetLineEntry()

# Important line below
>>> file = line.GetFileSpec().GetPath(1024)
# Important line above

>>> print(file)
/home/wanyi/tmp/main.cpp
```

## Before this change
```
$ lldb
(lldb) script
Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
>>> debugger = lldb.SBDebugger.Create()
>>> debugger.SetAsync (False)
>>> target = debugger.CreateTarget("~/tmp/hello")
>>> target.IsValid()
True
>>> breakpoint = target.BreakpointCreateByName('main', 'hello')
>>> breakpoint.GetNumLocations()
1
>>> process = target.LaunchSimple (None, None, os.getcwd())
>>> process.IsValid()
True
>>> thread = process.GetThreadAtIndex(0)
>>> frame = thread.GetFrameAtIndex(0)
>>> line = frame.GetLineEntry()
>>> file = line.GetFileSpec().GetPath(1024)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: SBFileSpec.GetPath() missing 1 required positional argument: 'dst_len'
>>> print(file)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'file' is not defined
```
2025-10-13 12:24:12 -06:00
Matej Košík
14a1d3e0ae
[lldb] Fix TypeSystemClang::GetBasicTypeEnumeration for 128-bit int types (#162278)
When we take the following C program:
```
int main() {
  return 0;
}
```
and create a statically-linked executable from it:
```
clang -static -g -o main main.c
```
Then we can observe the following `lldb` behavior:
```
$ lldb
(lldb) target create main
Current executable set to '.../main' (x86_64).
(lldb) breakpoint set --name main
Breakpoint 1: where = main`main + 11 at main.c:2:3, address = 0x000000000022aa7b
(lldb) process launch
Process 3773637 launched: '/home/me/tmp/built-in/main' (x86_64)
Process 3773637 stopped
* thread #1, name = 'main', stop reason = breakpoint 1.1
    frame #0: 0x000000000022aa7b main`main at main.c:2:3
   1   	int main() {
-> 2   	  return 0;
   3   	}
(lldb) script lldb.debugger.GetSelectedTarget().FindFirstType("__int128").size
0
(lldb) script lldb.debugger.GetSelectedTarget().FindFirstType("unsigned __int128").size
0
(lldb) quit
```
The value return by the `SBTarget::FindFirstType` method is wrong for
the `__int128` and `unsigned __int128` basic types.

The proposed changes make the `TypeSystemClang::GetBasicTypeEnumeration`
method consistent with `gcc` and `clang` C [language
extension](https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html)
related to 128-bit integer types as well as with the
`BuiltinType::getName` method in the LLVM codebase itself.

When the above change is applied, the behavior of the `lldb` changes in
the following (desired) way:
```
$ lldb
(lldb) target create main
Current executable set to '.../main' (x86_64).
(lldb) breakpoint set --name main
Breakpoint 1: where = main`main + 11 at main.c:2:3, address = 0x000000000022aa7b
(lldb) process launch
Process 3773637 launched: '/home/me/tmp/built-in/main' (x86_64)
Process 3773637 stopped
* thread #1, name = 'main', stop reason = breakpoint 1.1
    frame #0: 0x000000000022aa7b main`main at main.c:2:3
   1   	int main() {
-> 2   	  return 0;
   3   	}
(lldb) script lldb.debugger.GetSelectedTarget().FindFirstType("__int128").size
16
(lldb) script lldb.debugger.GetSelectedTarget().FindFirstType("unsigned __int128").size
16
(lldb) quit
```

---------

Co-authored-by: Matej Košík <matej.kosik@codasip.com>
2025-10-13 14:52:30 +01:00
Michael Buch
e3620fe068
[lldb][Expression] Emit a 'Note' diagnostic that indicates the language used for expression evaluation (#161688)
Depends on:
* https://github.com/llvm/llvm-project/pull/162050

Since it's a 'Note' diagnostic it would only show up when expression
evaluation actually failed. This helps with expression evaluation
failure reports in mixed language environments where it's not quite
clear what language the expression ran as. It may also reduce confusion
around why the expression evaluator ran an expression in a language it
wasn't asked to run (a softer alternative to what I attempted in
https://github.com/llvm/llvm-project/pull/156648).

Here are some example outputs:
```
# Without target
(lldb) expr blah
note: Falling back to default language. Ran expression as 'Objective C++'.

# Stopped in target
(lldb) expr blah
note: Ran expression as 'C++14'.

(lldb) expr -l objc -- blah
note: Expression evaluation in pure Objective-C not supported. Ran expression as 'Objective C++'.

(lldb) expr -l c -- blah
note: Expression evaluation in pure C not supported. Ran expression as 'ISO C++'.

(lldb) expr -l c++14 -- blah
note: Ran expression as 'C++14'

(lldb) expr -l c++20 -- blah
note: Ran expression as 'C++20'

(lldb) expr -l objective-c++ -- blah
note: Ran expression as 'Objective C++'

(lldb) expr -l D -- blah
note: Expression evaluation in D not supported. Falling back to default language. Ran expression as 'Objective C++'.
```

I didn't put the diagnostic on the same line as the inline diagnostic
for now because of implementation convenience, but if reviewers deem
that a blocker I can take a stab at that again.

Also, other language plugins (namely Swift), won't immediately benefit
from this and will have to emit their own diagnistc. I played around
with having a virtual API on `UserExpression` or `ExpressionParser` that
will be called consistently, but by the time we're about to parse the
expression we are already several frames deep into the plugin. Before
(and at the beginning of) the generic `UserExpression::Parse` call we
don't have enough information to notify which language we're going to
parse in (at least for the C++ plugin).

rdar://160297649
rdar://159669244
2025-10-10 19:23:02 +01:00
Janet Yang
7546bd3804
[lldb] Add support for unique target ids (#160736)
### Summary
Add support for unique target ids per Target instance. This is needed
for upcoming changes to allow debugger instances to be shared across
separate DAP instances for child process debugging. We want the IDE to
be able to attach to existing targets in an already runny lldb-dap
session, and having a unique ID per target would make that easier.

Each Target instance will have its own unique id, and uses a
function-local counter in `TargetList::CreateTargetInternal` to assign
incremental unique ids.

### Tests
Added several unit tests to test basic functionality, uniqueness of
targets, and target deletion doesn't affect the uniqueness.
```
bin/lldb-dotest -p TestDebuggerAPI
```
2025-10-07 15:36:47 -04:00
Jonas Devlieghere
820f440274
[lldb] Correct style of error messages (#156774)
The LLVM Style Guide says the following about error and warning messages
[1]:

> [T]o match error message styles commonly produced by other tools,
> start the first sentence with a lowercase letter, and finish the last
> sentence without a period, if it would end in one otherwise.

I often provide this feedback during code review, but we still have a
bunch of places where we have inconsistent error message, which bothers
me as a user. This PR identifies a handful of those places and updates
the messages to be consistent.

[1] https://llvm.org/docs/CodingStandards.html#error-and-warning-messages
2025-09-04 16:37:41 -07:00
Dave Lee
d289ff761b
[lldb] Reland: Add Pythonic API to SBStructuredData extension (#156771)
* Adds `dynamic` property to automatically convert `SBStructuredData`
instances to the associated Python type (`str`, `int`, `float`, `bool`,
`NoneType`, etc)
* Implements `__getitem__` for Pythonic array and dictionary
subscripting
  * Subscripting return the result of the `dynamic` property
* Updates `__iter__` to support dictionary instances (supporting `for`
loops)
* Adds `__str__`, `__int__`, and `__float__`

With these changes, these two expressions are equal:

```py
data["name"] == data.GetValueForKey("name").GetStringValue(1024)
```

**Note**: Unlike the original commit (#155061), this re-commit removes
the `__bool__` implementation, which broke crashlog. Somewhere in the
crashlog execution, it depends on `__bool__` meaning only `IsValid()`.

Additionally did some cleanup in TestStructuredDataAPI.py.
2025-09-04 08:34:34 -07:00
Muhammad Omair Javaid
c0f84d31ed [lldb] Add issue no to xfail decorators in TestGetBaseName (#155939)
TestGetBaseName.py is currently marked as an expected failure on Windows
because SBFunction::GetBaseName() and SBSymbol::GetBaseName() don’t yet
handle MSVC-style mangling.

This patch updates the @expectedFailureAll decorator to include a
reference to https://github.com/llvm/llvm-project/issues/156861
2025-09-04 17:23:18 +05:00
Dave Lee
9d9a714f79
Revert "[lldb] Add Pythonic API to SBStructuredData extension (#155061)" (#156728)
Reverts #155061 (and #156721) which caused Crashlog shell tests to break.
2025-09-03 12:15:20 -07:00
Dave Lee
722339dc09
[lldb] Revert custom __str__ in SBStructuredDataExtensions.i (#156721)
`__str__` was implemented in #155061, however its behavior was limited
to only a some kinds of `SBStructuredData`. That was a breaking change,
and this change removes that implementation of `__str__`, relying on the
existing behavior which calls `GetDescription`.
2025-09-03 10:51:09 -07:00
Dave Lee
023a98c2ae
[lldb] Add Pythonic API to SBStructuredData extension (#155061)
* Adds `dynamic` property to automatically convert `SBStructuredData`
instances to the associated Python type (`str`, `int`, `float`, `bool`,
`NoneType`, etc)
* Implements `__getitem__` for Pythonic array and dictionary
subscripting
  * Subscripting return the result of the `dynamic` property
* Updates `__iter__` to support dictionary instances (supporting `for`
loops)
* Adds conversion to `str`, `int`, and `float`
* Adds Pythonic `bool` conversion

With these changes, these two expressions are equal:

```py
data["name"] == data.GetValueForKey("name").GetStringValue(1024)
```

Additionally did some cleanup in TestStructuredDataAPI.py.
2025-09-02 14:23:56 -07:00
Muhammad Omair Javaid
eef79c8b49 [lldb][test] Mark TestGetBaseName.py as expected failure on Windows
TestGetBaseName.py introduced in PR #155939 is failing on windows
LLDB bots. This patch adds @expectedFailureAll(oslist=["windows"])
decorator to mark it as an expected failure on Windows to make
buildbots green while the underlying issue is investigated.

(see: https://lab.llvm.org/buildbot/#/builders/141/builds/11176).
2025-09-01 01:41:05 +05:00
Jonas Devlieghere
2a062d6936
[lldb] Add SBFunction::GetBaseName() & SBSymbol::GetBaseName() (#155939)
When you are trying for instance to set a breakpoint on a function by
name, but the SBFunction or SBSymbol are returning demangled names with
argument lists, that match can be tedious to do. Internally, the base
name of a symbol is something we handle all the time, so it's reasonable
that there should be a way to get that info from the API as well.

rdar://159318791
2025-08-28 19:10:52 -07:00
Med Ismail Bennani
05b1ec3724
[lldb/API] Add setters to SBStructuredData (#154445)
This patch adds setters to the SBStruturedData class to be able to
initialize said object from the client side directly.

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
2025-08-21 16:40:01 -07:00
barsolo2000
402109e1c4
[LLDB] added getName method in SBModule (#150331)
added getName method in SBModule.h and .cpp in order to get the name of
the module from m_object_name.

---------

Co-authored-by: Bar Soloveychik <barsolo@fb.com>
2025-08-19 14:24:10 -07:00
LauraElanorJones
350f4a3e3b
Decent to Descent (#154040)
[lldb] Rename RecursiveDecentFormatter to RecursiveDescentFormatter (NFC)
2025-08-18 12:47:14 -05:00
Igor Kudrin
36c2a66968
[lldb][test] Make TestFindRangesInMemory.py more robust (#152817)
`GetHeapRanges()` could return two overlapping ranges because it did not
check whether `heap_pointer1` lies within the range returned for
`heap_pointer2`. This could result in a test failure in
`test_find_ranges_in_memory_two_matches` when
`process.FindRangesInMemory()` returned 3 instead of 2.

The patch ensures that `GetHeapRanges()` returns either two
non-overlapping ranges or one range covering both heap pointers.

The issue was probably introduced in #111951
2025-08-13 14:15:45 -07:00
Felipe de Azevedo Piovezan
f12e0380be
[lldb] Guard SBFrame/SBThread methods against running processes (#152020)
Prior to this patch, SBFrame/SBThread methods exhibit racy behavior if
called while the process is running, because they do not lock the
`Process::RetRunLock` mutex. If they did, they would fail, correctly
identifying that the process is not running.

Some methods _attempt_ to protect against this with the pattern:

```
ExecutionContext exe_ctx(m_opaque_sp.get(), lock); // this is a different lock
Process *process = exe_ctx.GetProcessPtr();
if (process) {
  Process::StopLocker stop_locker;
  if (stop_locker.TryLock(&process->GetRunLock()))
        .... do work ...
```

However, this is also racy: the constructor of `ExecutionContext` will
access the frame list, which is something that can only be done once the
process is stopped.

With this patch:

1. The constructor of `ExecutionContext` now expects a `ProcessRunLock`
as an argument. It attempts to lock the run lock, and only fills in
information about frames and threads if the lock can be acquired.
Callers of the constructor are expected to check the lock.
2. All uses of ExecutionContext are adjusted to conform to the above.
3. The SBThread.cpp-defined helper function ResumeNewPlan now expects a
locked ProcessRunLock as _proof_ that the execution is stopped. It will
unlock the mutex prior to resuming the process.

This commit exposes many opportunities for early-returns, but these
would increase the diff of this patch and distract from the important
changes, so we opt not to do it here.
2025-08-11 10:26:57 -07:00