├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── setup.cfg ├── dev-requirements.txt ├── after.png ├── before.png ├── .gitignore ├── rust_test_crate ├── Cargo.lock ├── Cargo.toml └── main.rs ├── .vscode ├── settings.json └── launch.json ├── tests ├── test_crossbeam.py ├── test_collections.py ├── test_harness.py ├── test_basic_types.py └── test_enums.py ├── README.md ├── LICENSE └── rust_prettifier_for_lldb.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: cmrschwarz 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | lldb-python==19.0.0.dev1 2 | pytest==8.3.3 3 | -------------------------------------------------------------------------------- /after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmrschwarz/rust-prettifier-for-lldb/HEAD/after.png -------------------------------------------------------------------------------- /before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmrschwarz/rust-prettifier-for-lldb/HEAD/before.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | !/.github 2 | 3 | /.pytest_cache 4 | /.venv 5 | __pycache__ 6 | 7 | /target 8 | /rust_test_crate/target 9 | -------------------------------------------------------------------------------- /rust_test_crate/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "rust_test_crate" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /rust_test_crate/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_test_crate" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | 8 | [[bin]] 9 | name = "rust_test_crate" 10 | path = "main.rs" 11 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.testing.pytestArgs": [ 3 | "tests" 4 | ], 5 | "python.testing.unittestEnabled": true, 6 | "python.testing.pytestEnabled": true, 7 | "rust-analyzer.linkedProjects": [ 8 | "${workspaceFolder}/rust_test_crate/Cargo.toml" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /tests/test_crossbeam.py: -------------------------------------------------------------------------------- 1 | from test_harness import expect_summaries 2 | 3 | def test_crossbeam_atomic_cell(tmpdir): 4 | src = """ 5 | use crossbeam::atomic::AtomicCell; 6 | 7 | let atomic_cell = AtomicCell::new(42); 8 | """ 9 | expect_summaries(tmpdir, src, { 10 | "atomic_cell": "42", 11 | }) -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: ["main", "staging"] 6 | pull_request: 7 | branches: ["main"] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | test: 14 | name: Test 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: dtolnay/rust-toolchain@stable 19 | - uses: actions/setup-python@v5 20 | with: 21 | python-version: "3.12" 22 | - run: pip install -r dev-requirements.txt 23 | - run: pytest 24 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "All Tests", 6 | "type": "debugpy", 7 | "request": "launch", 8 | "module": "pytest", 9 | "subProcess": true, 10 | "args": [], 11 | }, 12 | { 13 | "name": "Specific Test", 14 | "type": "debugpy", 15 | "request": "launch", 16 | "module": "pytest", 17 | "subProcess": true, 18 | "args": [ 19 | "-k", 20 | "${input:pattern}" 21 | ], 22 | }, 23 | { 24 | "name": "Test Crate code-lldb", 25 | "type": "lldb", 26 | "request": "launch", 27 | "cargo": { 28 | "cwd": "${workspaceFolder}/rust_test_crate", 29 | "args": [ 30 | "build", 31 | "--bin=rust_test_crate" 32 | ], 33 | "filter": { 34 | "kind": "bin" 35 | } 36 | }, 37 | "expressions": "simple", 38 | "preRunCommands": [ 39 | "command script import ${workspaceFolder}/rust_prettifier_for_lldb.py" 40 | ] 41 | }, 42 | { 43 | "name": "Test Crate code-lldb no prettifier", 44 | "type": "lldb", 45 | "request": "launch", 46 | "cargo": { 47 | "cwd": "${workspaceFolder}/rust_test_crate", 48 | "args": [ 49 | "build", 50 | "--bin=rust_test_crate" 51 | ], 52 | "filter": { 53 | "kind": "bin" 54 | } 55 | }, 56 | "expressions": "simple", 57 | }, 58 | ], 59 | "inputs": [ 60 | { 61 | "id": "pattern", 62 | "description": "pytest test name pattern for test filtering", 63 | "type": "promptString" 64 | } 65 | ] 66 | } 67 | -------------------------------------------------------------------------------- /tests/test_collections.py: -------------------------------------------------------------------------------- 1 | from test_harness import expect_summaries, expect_command_output 2 | 3 | 4 | def test_basic_vec_summary(tmpdir): 5 | src = """ 6 | let x = vec![1,2,3]; 7 | """ 8 | expect_summaries(tmpdir, src, { 9 | "x": "(3) vec![1, 2, 3]" 10 | }) 11 | 12 | 13 | def test_basic_vec_child_access(tmpdir): 14 | src = """ 15 | let x = vec![1,2,3]; 16 | """ 17 | expect_command_output(tmpdir, src, [ 18 | ("v x[1]", "(int) x[1] = 2\n") 19 | ]) 20 | 21 | def test_basic_vec_sequence_limits(tmpdir): 22 | src = """ 23 | let x = vec![1,2,3,4,5,6,7,8,9,10,11]; 24 | """ 25 | expect_summaries(tmpdir, src, { 26 | "x": "(11) vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]" 27 | }) 28 | 29 | # regression test for #2 30 | def test_vec_i8(tmpdir): 31 | src = """ 32 | let x = vec![1i8, -1i8, 'A' as i8]; 33 | """ 34 | expect_summaries(tmpdir, src, { 35 | "x": "(3) vec![1, -1, 65]" 36 | }) 37 | # TODO: see test_basic_types.test_i8 for explanation 38 | expect_command_output(tmpdir, src, [ 39 | ("v x[1]", "(char) x[1] = '\\xff' -1\n") 40 | ]) 41 | 42 | 43 | def test_basic_vec_deque(tmpdir): 44 | src = """ 45 | use std::collections::VecDeque; 46 | let x = VecDeque::from([1,2,3]); 47 | """ 48 | expect_summaries(tmpdir, src, { 49 | "x": "(3) VecDeque[1, 2, 3]" 50 | }) 51 | 52 | 53 | def test_hashmap_access(tmpdir): 54 | src = """ 55 | use std::collections::HashMap; 56 | use std::hash::{Hasher, BuildHasherDefault}; 57 | use std::iter::FromIterator; 58 | #[derive(Default)] 59 | struct IdentityHash(u64); 60 | impl Hasher for IdentityHash { 61 | fn write(&mut self, _: &[u8]) {unimplemented!()} 62 | fn write_u8(&mut self, n: u8) { self.0 = u64::from(n) } 63 | fn write_u16(&mut self, n: u16) { self.0 = u64::from(n) } 64 | fn write_u32(&mut self, n: u32) { self.0 = u64::from(n) } 65 | fn write_u64(&mut self, n: u64) { self.0 = n } 66 | fn write_usize(&mut self, n: usize) { self.0 = n as u64 } 67 | fn write_i8(&mut self, n: i8) { self.0 = n as u64 } 68 | fn write_i16(&mut self, n: i16) { self.0 = n as u64 } 69 | fn write_i32(&mut self, n: i32) { self.0 = n as u64 } 70 | fn write_i64(&mut self, n: i64) { self.0 = n as u64 } 71 | fn write_isize(&mut self, n: isize) { self.0 = n as u64 } 72 | fn finish(&self) -> u64 { self.0 } 73 | } 74 | let mut hm = HashMap::>::from_iter([ 75 | (3, "foo"), 76 | (12, "bar"), 77 | ]); 78 | """ 79 | # TODO: seems a bit sketchy. Can we improve this? 80 | expect_command_output(tmpdir, src, [ 81 | ("v hm[0].0", "(int) 0 = 12\n") 82 | ]) 83 | -------------------------------------------------------------------------------- /tests/test_harness.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import lldb # type: ignore 4 | import textwrap 5 | from typing import Any, Callable 6 | 7 | PACKAGE_ROOT_PATH = os.path.abspath( 8 | os.path.join( 9 | os.path.dirname(os.path.abspath(__file__)), 10 | ".." 11 | ) 12 | ) 13 | PRETTIFIER_PATH = os.path.join( 14 | PACKAGE_ROOT_PATH, 15 | "rust_prettifier_for_lldb.py" 16 | ) 17 | 18 | 19 | def run_rust_test( 20 | temp_dir: Any, 21 | rust_src: str, 22 | test_code: Callable[[lldb.SBDebugger, lldb.SBFrame], None] 23 | ): 24 | project_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 25 | target_dir = os.path.join(project_dir, "target") 26 | src_path = os.path.join(str(temp_dir), "src/main.rs") 27 | os.makedirs(os.path.dirname(src_path), exist_ok=True) 28 | cargo_toml_path = os.path.join(str(temp_dir), "Cargo.toml") 29 | with open(cargo_toml_path, "w") as f: 30 | f.write(""" 31 | [package] 32 | name = "main" 33 | version = "0.1.0" 34 | edition = "2021" 35 | 36 | [dependencies] 37 | crossbeam = "0.8.4" 38 | """ 39 | ) 40 | rust_src = textwrap.indent(textwrap.dedent(rust_src), " ") 41 | 42 | rust_src += " let _ = 0 + 0;" # dummy line to place the breakpoint on 43 | 44 | rust_src = "fn main() {\n" + rust_src + "\n}\n" 45 | 46 | binary_path = os.path.join(target_dir, "debug/main") 47 | with open(src_path, "w") as f: 48 | f.write(rust_src) 49 | 50 | result = subprocess.run( 51 | ["cargo", "build", "--target-dir", target_dir], 52 | stderr=subprocess.PIPE, 53 | stdout=subprocess.PIPE, 54 | cwd=str(temp_dir) 55 | ) 56 | 57 | if result.returncode != 0: 58 | stderr = result.stderr.decode("utf-8") 59 | assert stderr == "" 60 | assert result.returncode == 0 61 | 62 | debugger: lldb.SBDebugger = lldb.SBDebugger.Create() 63 | debugger.SetAsync(False) 64 | 65 | target: lldb.SBTarget = debugger.CreateTargetWithFileAndArch( 66 | binary_path, lldb.LLDB_ARCH_DEFAULT) 67 | assert target 68 | 69 | breakpoint_line = len(rust_src.splitlines()) - 1 70 | breakpoint: lldb.SBBreakpoint = target.BreakpointCreateByLocation( 71 | "main.rs", breakpoint_line) 72 | assert breakpoint.num_locations == 1 73 | 74 | process = target.LaunchSimple(None, None, ".") 75 | thread = process.GetThreadAtIndex(0) 76 | frame = thread.GetFrameAtIndex(0) 77 | assert frame 78 | 79 | repl: lldb.SBCommandInterpreter = debugger.GetCommandInterpreter() 80 | res = lldb.SBCommandReturnObject() 81 | repl.HandleCommand(f"command script import {PRETTIFIER_PATH}", res) 82 | assert res.Succeeded() 83 | 84 | test_code(debugger, frame) 85 | 86 | lldb.SBDebugger.Destroy(debugger) 87 | 88 | 89 | def compare_summaries(frame: lldb.SBFrame, expected_var_summaries: dict[str, str]): 90 | for (name, expected_summary) in expected_var_summaries.items(): 91 | var = frame.FindVariable(name) 92 | s = var.GetSummary() 93 | if s is None: 94 | s = var.GetValue() 95 | assert s == expected_summary 96 | 97 | 98 | def expect_summaries( 99 | temp_dir: Any, 100 | rust_src: str, 101 | expected_var_summaries: dict[str, str] 102 | ): 103 | run_rust_test( 104 | temp_dir, 105 | rust_src, 106 | lambda debugger, frame: compare_summaries(frame, expected_var_summaries) 107 | ) 108 | 109 | 110 | def compare_command_outputs(debugger, frame: Any, commands: list[tuple[str, str]]): 111 | repl: lldb.SBCommandInterpreter = debugger.GetCommandInterpreter() 112 | res = lldb.SBCommandReturnObject() 113 | 114 | for (cmd, expected_output) in commands: 115 | repl.HandleCommand(cmd, res) 116 | output = res.GetOutput() 117 | error = res.GetError() 118 | assert error == "" 119 | assert res.Succeeded() 120 | assert output == expected_output 121 | 122 | 123 | def expect_command_output( 124 | temp_dir: Any, 125 | rust_src: str, 126 | commands: list[tuple[str, str]] 127 | ): 128 | run_rust_test( 129 | temp_dir, 130 | rust_src, 131 | lambda debugger, frame: compare_command_outputs(debugger, frame, commands) 132 | ) 133 | -------------------------------------------------------------------------------- /tests/test_basic_types.py: -------------------------------------------------------------------------------- 1 | from test_harness import expect_command_output, expect_summaries 2 | 3 | 4 | def test_u8(tmpdir): 5 | src = """ 6 | let x: u8 = 65; 7 | """ 8 | expect_summaries(tmpdir, src, { 9 | "x": "65", 10 | }) 11 | 12 | 13 | # regression test for #2 14 | def test_i8(tmpdir): 15 | src = """ 16 | let x: i8 = -128; 17 | """ 18 | 19 | # TODO: we would prefer to get rid of the 20 | # '\x80' here, but I have no idea how. 21 | # Disabling the cplusplus Category and other potentially conflicting 22 | # Sources did unfortunately not help. 23 | expect_command_output(tmpdir, src, [ 24 | ("v x", "(char) x = '\\x80' -128\n") 25 | ]) 26 | expect_summaries(tmpdir, src, { 27 | "x": "-128", 28 | }) 29 | 30 | 31 | def test_char(tmpdir): 32 | src = """ 33 | let x: char = 'A'; 34 | let y: char = '\\n'; 35 | """ 36 | expect_summaries(tmpdir, src, { 37 | "x": "'A'", 38 | "y": "U+0x0000000A" 39 | }) 40 | expect_command_output(tmpdir, src, { 41 | ("v x", "(char32_t) x = U+0x00000041 'A'\n") 42 | }) 43 | 44 | 45 | def test_str(tmpdir): 46 | src = """ 47 | let x: &str = "foo"; 48 | let y: String = "bar".into(); 49 | """ 50 | expect_summaries(tmpdir, src, { 51 | "x": "\"foo\"", 52 | "y": "\"bar\"" 53 | }) 54 | 55 | 56 | 57 | def test_rc(tmpdir): 58 | src = """ 59 | use std::rc::Rc; 60 | 61 | let rc_vec = Rc::new(Vec::from([1, 2, 3])); 62 | 63 | let rc_int = Rc::new(42); 64 | let rc_int_2 = rc_int.clone(); 65 | 66 | let rc_string: Rc = Rc::from("asdf".to_string()); 67 | 68 | let rc_u8: Rc = Rc::from(42); 69 | let rc_str: Rc = Rc::from("asdf"); 70 | 71 | let rc_slice = Rc::<[i32]>::from([1, 2, 3]); 72 | 73 | 74 | """ 75 | expect_summaries(tmpdir, src, { 76 | "rc_vec": "(strong:1) (3) vec![1, 2, 3]", 77 | "rc_slice": "(strong:1) [1, 2, 3]", 78 | "rc_str": "(strong:1) \"asdf\"", 79 | "rc_int": "(strong:2) 42", 80 | "rc_string": "(strong:1) \"asdf\"", 81 | "rc_u8": "(strong:1) 42", 82 | }) 83 | 84 | expect_command_output(tmpdir, src, { 85 | ("v rc_vec[0]", "(int) rc_vec[0] = 1\n") 86 | }) 87 | 88 | def test_arc(tmpdir): 89 | src = """ 90 | use std::sync::Arc; 91 | 92 | let arc_vec = Arc::new(Vec::from([1, 2, 3])); 93 | 94 | let arc_int = Arc::new(42); 95 | let arc_int_2 = arc_int.clone(); 96 | 97 | let arc_string: Arc = Arc::from("asdf".to_string()); 98 | 99 | let arc_u8: Arc = Arc::from(42); 100 | let arc_str: Arc = Arc::from("asdf"); 101 | 102 | let weak = Arc::downgrade(&arc_str); 103 | 104 | let arc_slice = Arc::<[i32]>::from([1, 2, 3]); 105 | """ 106 | expect_summaries(tmpdir, src, { 107 | "arc_vec": "(strong:1) (3) vec![1, 2, 3]", 108 | "arc_str": "(strong:1, weak:1) \"asdf\"", 109 | "arc_int": "(strong:2) 42", 110 | "arc_string": "(strong:1) \"asdf\"", 111 | "arc_u8": "(strong:1) 42", 112 | "arc_slice": "(strong:1) [1, 2, 3]", 113 | }) 114 | 115 | expect_command_output(tmpdir, src, { 116 | ("v arc_vec[0]", "(int) arc_vec[0] = 1\n") 117 | }) 118 | 119 | 120 | def test_box(tmpdir): 121 | src = """ 122 | let x = Box::new(42); 123 | """ 124 | # TODO: currently raw summary text is just the pointer hex value, 125 | # consider showing Box(T) ? 126 | expect_command_output(tmpdir, src, [ 127 | ("v *x", "(int) *x = 42\n"), 128 | ]) 129 | 130 | def test_tuple(tmpdir): 131 | src = """ 132 | let x = (42, "foo"); 133 | """ 134 | # TODO: currently raw summary text is just the pointer hex value, 135 | # consider showing Box(T) ? 136 | expect_summaries(tmpdir, src, { 137 | "x": "(42, \"foo\")", 138 | }) 139 | 140 | 141 | def test_tuple_access(tmpdir): 142 | src = """ 143 | let x = (42, "foo"); 144 | """ 145 | # '(int) 1'. meh. 146 | expect_command_output(tmpdir, src, [ 147 | ("v x[0]", "(int) 0 = 42\n"), 148 | ("v x.0", "(int) 0 = 42\n"), 149 | ]) 150 | 151 | def test_cell(tmpdir): 152 | src = """ 153 | use std::cell::{Cell, UnsafeCell}; 154 | let safe = Cell::::new(42); 155 | let not_safe = UnsafeCell::::new(42); 156 | """ 157 | 158 | expect_summaries(tmpdir, src, { 159 | "safe": "42", 160 | "not_safe": "42", 161 | }) 162 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust Prettifier for LLDB 2 | 3 | [![CI](https://github.com/cmrschwarz/rust-prettifier-for-lldb/actions/workflows/ci.yml/badge.svg)](https://github.com/cmrschwarz/rust-prettifier-for-lldb/actions/workflows/ci.yml) 4 | 5 | 6 | Script to add Rust specific pretty-printing to the LLDB debugger. 7 | 8 | With the recent [removal](https://github.com/vadimcn/codelldb/issues/1166) of Rust specific pretty printing from 9 | [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb), debugging Rust, especially 10 | enums, has become quite painful. 11 | 12 | This script is meant as a temporary fix until the situation of the 13 | ecosystem improves, see [Compatability](#compatability). 14 | 15 | 16 | ### With Prettifier 17 | ![After](after.png) 18 | 19 | 20 | ### Without Prettifier 21 | ![Before](before.png) 22 | 23 | 24 | ## Standalone LLDB 25 | 26 | To load the script into your lldb debugger instance, execute the following lldb command: 27 | 28 | ``` 29 | command script import /path/to/rust_prettifier_for_lldb.py 30 | ``` 31 | 32 | [`rust_prettifier_for_lldb.py`](https://raw.githubusercontent.com/cmrschwarz/rust-prettifier-for-lldb/refs/heads/main/rust_prettifier_for_lldb.py) 33 | is the only file from this Repository that you actually need. You can download it separately from the 34 | [Releases](https://github.com/cmrschwarz/rust-prettifier-for-lldb/releases) section. 35 | 36 | ## Usage with VSCode Debug Adapters 37 | To use this script with VSCode debug adapters you have to instruct them 38 | to execute the same lldb command as above before the actual debugging session. 39 | 40 | **Either place `rust_prettifier_for_lldb.py` into your `.vscode` folder, 41 | or replace `${workspaceFolder}/.vscode/rust_prettifier_for_lldb.py` 42 | with the actual path you chose in the examples below**. 43 | 44 | ### VSCode + CodeLLDB 45 | For the 46 | [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb) 47 | extension, add the `preRunCommands` json tag from the example below 48 | to your launch configuration(s) or alternatively to your user settings under 49 | `lldb.launch.preRunCommands`. 50 | 51 | It is also recommended to set `"expressions": "simple"` to fix an issue with 52 | the array subscript operator (`[..]`) in the Debug Watch Window. 53 | Here's an example configuration for your `.vscode/launch.json`: 54 | 55 | ``` 56 | { 57 | "version": "0.2.0", 58 | "configurations": [ 59 | { 60 | "type": "lldb", 61 | "request": "launch", 62 | "name": "Debug", 63 | "cargo": { 64 | "args": [ 65 | "build", 66 | ], 67 | "filter": { 68 | "name": "NAME_OF_YOUR_BINARY_HERE", 69 | "kind": "bin" 70 | } 71 | }, 72 | "expressions": "simple", 73 | "preRunCommands": [ 74 | // !! change this path if you placed the script somewhere else !! 75 | "command script import ${workspaceFolder}/.vscode/rust_prettifier_for_lldb.py" 76 | ], 77 | "args": [], 78 | 79 | 80 | }, 81 | ] 82 | } 83 | ``` 84 | 85 | ### VSCode + lldb-dap 86 | 87 | For the [lldb-dap](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.lldb-dap) extension, add the `initCommands` JSON tag to your `.vscode/launch.json` configuration(s), as shown in the example below: 88 | 89 | ``` 90 | { 91 | "version": "0.2.0", 92 | "configurations": [ 93 | { 94 | "type": "lldb-dap", 95 | "request": "launch", 96 | "name": "Debug", 97 | "program": "NAME_OF_YOUR_BINARY_HERE", 98 | "args": [], 99 | "cwd": "${workspaceFolder}", 100 | "initCommands": [ 101 | // !! change this path if you placed the script somewhere else !! 102 | "command script import ${workspaceFolder}/.vscode/rust_prettifier_for_lldb.py" 103 | ], 104 | } 105 | ] 106 | } 107 | ``` 108 | 109 | 110 | 111 | ## Compatability 112 | This script was developed for LLDB Version `19.0.0`, aswell as `19.1.0-codelldb` (version currently bundled by 113 | [CodeLLDB](https://github.com/vadimcn/codelldb)). 114 | 115 | At the time of writing, it is known to work well with the latest stable version Rust (`1.82.0`). 116 | 117 | Initially this did not support Windows, although @jesnor was able to get it partially working. 118 | Any improvements on that front would of course be welcomed. 119 | 120 | If you are using older versions of Rust or LLDB this script might not work for you. 121 | 122 | Due to the changing nature of the Rust Standard Library internals aswell 123 | as the LLDB representation of them, this will never be more than a temporary hack 124 | that's constantly in danger of becoming outdated. 125 | The hope is that 126 | [Rust's own Pretty Printers](https://github.com/rust-lang/rust/blob/717f5df2c308dfb4b7b8e6c002c11fe8269c4011/src/etc/lldb_providers.py) 127 | will eventually ship in a functional state, superseeding this temporary bandaid. 128 | 129 | 130 | The plan for this script is to live at head, and hopefully get retired sooner rather than later. 131 | 132 | 133 | I'm happy to accept pull requests to improve this script or even add support 134 | for commonly used collection types of third party crates, 135 | as long as you supply testcases to make sure your additions can be maintained. 136 | 137 | Note (2025-01-18): There are 138 | [known cases](https://github.com/cmrschwarz/rust-prettifier-for-lldb/blob/4e630a6576f033eba0565a554198dc2ef6fc0379/tests/test_enums.py#L95) 139 | where it does not seem feasible to report the correct answer without fixing the upstream issues in Rust or LLVM. 140 | You might in rare cases even get incorrect results. 141 | 142 | ## Thank You 143 | 144 | Thank you to Vadim Chugunov (@vadimcn) for the wonderful CodeLLDB and the 145 | [starting point](https://github.com/vadimcn/codelldb/blob/05502bf75e4e7878a99b0bf0a7a81bba2922cbe3/formatters/rust.py) 146 | for this script. 147 | 148 | ## Support 149 | 150 | If this script has helped you out a a Github Star :sparkles: would make me very happy, 151 | and maybe help demonstrate to the Rust Project Maintainers that a solid solution 152 | for debugging Rust is something that many people desire. 153 | -------------------------------------------------------------------------------- /tests/test_enums.py: -------------------------------------------------------------------------------- 1 | from test_harness import expect_command_output, expect_summaries, run_rust_test 2 | 3 | 4 | def test_basic_int(tmpdir): 5 | src = """ 6 | let x = 3; 7 | """ 8 | expect_summaries(tmpdir, src, { 9 | "x": "3" 10 | }) 11 | 12 | 13 | def test_c_style_enum(tmpdir): 14 | src = """ 15 | enum CStyleEnum { 16 | A, B 17 | } 18 | let x = CStyleEnum::A; 19 | """ 20 | expect_summaries(tmpdir, src, { 21 | "x": "A" # TODO: change this to be Foo::A? 22 | }) 23 | 24 | 25 | def test_basic_rust_enum(tmpdir): 26 | src = """ 27 | enum Foo { 28 | A(u8), 29 | B(u16) 30 | } 31 | let x = Foo::A(42); 32 | """ 33 | expect_summaries(tmpdir, src, { 34 | "x": "Foo::A(42)" 35 | }) 36 | 37 | 38 | def test_multi_enum_variant(tmpdir): 39 | src = """ 40 | enum RegularEnum { 41 | A, 42 | B(i32, i32), 43 | C { x: i64, y: f64 }, 44 | } 45 | let a = RegularEnum::A; 46 | let b = RegularEnum::B(1, 2); 47 | let c = RegularEnum::C{x: 1, y: 2.5}; 48 | """ 49 | expect_summaries(tmpdir, src, { 50 | "a": "RegularEnum::A", 51 | "b": "RegularEnum::B(1, 2)", 52 | "c": "RegularEnum::C{x: 1, y: 2.5}" 53 | }) 54 | 55 | def test_enum_with_niche_in_early_variant(tmpdir): 56 | src = """ 57 | pub enum E { 58 | Foo(Vec), 59 | Bar, 60 | Baz, 61 | Quux, 62 | } 63 | let foo = E::Foo(vec![1, 2]); 64 | let bar = E::Bar; 65 | let baz = E::Baz; 66 | let quux = E::Quux; 67 | """ 68 | expect_summaries(tmpdir, src, { 69 | # TODO: the discriminator for this case ends up just being the 70 | # the length of the vector. We have no way of doing the correct 71 | # thing here. 72 | # "foo": "E::Foo((2) vec![1, 2])", 73 | "bar": "E::Bar", 74 | "baz": "E::Baz", 75 | "quux": "E::Quux", 76 | }) 77 | 78 | 79 | 80 | def test_enum_with_niche_in_middle_variant(tmpdir): 81 | src = """ 82 | pub enum E { 83 | Foo, 84 | Bar, 85 | Baz(Vec), 86 | Quux, 87 | } 88 | let foo = E::Foo; 89 | let bar = E::Bar; 90 | let baz = E::Baz(vec![1]); 91 | let quux = E::Quux; 92 | """ 93 | expect_summaries(tmpdir, src, { 94 | "foo": "E::Foo", 95 | "bar": "E::Bar", 96 | # TODO: see `test_enum_with_niche_in_early_variant`. We are screwed here. 97 | #"baz": "E::Baz((3) vec![1, 2, 3])", 98 | "quux": "E::Quux", 99 | }) 100 | 101 | def test_enum_with_niche_in_late_variant(tmpdir): 102 | src = """ 103 | pub enum E { 104 | Foo, 105 | Bar, 106 | Baz, 107 | Quux(Vec), 108 | } 109 | let foo = E::Foo; 110 | let bar = E::Bar; 111 | let baz = E::Baz; 112 | let quux = E::Quux(vec![1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]); 113 | """ 114 | expect_summaries(tmpdir, src, { 115 | "foo": "E::Foo", 116 | "bar": "E::Bar", 117 | "baz": "E::Baz", 118 | "quux": "E::Quux((15) vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...])", 119 | }) 120 | 121 | 122 | 123 | def test_option(tmpdir): 124 | src = """ 125 | let opt_str1: Option<&str> = Some("foobar"); 126 | let opt_str2: Option<&str> = None; 127 | let opt_str3: Option<*const u8> = Some("other string".as_ptr()); 128 | """ 129 | expect_summaries(tmpdir, src, { 130 | "opt_str1": "Some(\"foobar\")" 131 | }) 132 | 133 | 134 | def test_result(tmpdir): 135 | src = """ 136 | let result_ok: Result<&str, String> = Ok("ok"); 137 | let result_err: Result<&str, String> = Err("err".into()); 138 | """ 139 | expect_summaries(tmpdir, src, { 140 | "result_ok": "Ok(\"ok\")", 141 | "result_err": "Err(\"err\")" 142 | }) 143 | 144 | 145 | def test_cow(tmpdir): 146 | src = """ 147 | use std::borrow::Cow; 148 | let cow1 = Cow::Borrowed("their cow"); 149 | let cow2 = Cow::::Owned("my cow".into()); 150 | """ 151 | expect_summaries(tmpdir, src, { 152 | "cow1": "Borrowed(\"their cow\")", 153 | "cow2": "Owned(\"my cow\")", 154 | }) 155 | 156 | 157 | def test_pointer_niche(tmpdir): 158 | src = """ 159 | enum MyEnum { 160 | A(&'static str), 161 | B(i32), 162 | C(Vec), 163 | } 164 | let myenum = MyEnum::B(42); 165 | """ 166 | expect_summaries(tmpdir, src, { 167 | "myenum": "MyEnum::B(42)", 168 | }) 169 | 170 | 171 | def test_struct_enum_synthetic(tmpdir): 172 | src = """ 173 | enum Foo{ 174 | Bar(Baz) 175 | } 176 | struct Baz{x: i32, y: i32} 177 | 178 | let foo = Foo::Bar(Baz{x: 1, y: 2}); 179 | """ 180 | 181 | def compare_synth(_dbg, frame): 182 | foo = frame.FindVariable("foo") 183 | foo_s = foo.GetSummary() 184 | assert foo_s == 'Foo::Bar(Bar{x: 1, y: 2})' 185 | x = foo.GetChildAtIndex(0) 186 | x_s = x.GetValue() 187 | assert x_s == "1" 188 | 189 | run_rust_test(tmpdir, src, compare_synth) 190 | 191 | 192 | def test_access_vec_in_enum(tmpdir): 193 | src = """ 194 | enum Foo{ 195 | A(Vec), 196 | B(Vec) 197 | } 198 | let x = Foo::A(vec![1, 2, 3]); 199 | """ 200 | expect_command_output(tmpdir, src, [ 201 | ("settings set target.enable-synthetic-value true", ""), 202 | ("v x[1]", "(int) x[1] = 2\n") 203 | ]) 204 | 205 | 206 | def _broken_test_lld_crash(tmpdir): # TODO: send a bugreport to LLDB 207 | src = """ 208 | use std::num::NonZeroI64; 209 | #[repr(C)] 210 | struct Foo { 211 | x: i64, 212 | y: NonZeroI64, 213 | } 214 | struct Bar { 215 | x: i64, 216 | } 217 | enum Baz { 218 | Foo(Foo), 219 | Bar(Bar), 220 | } 221 | let baz = Baz::Bar(Bar{x: 3}); 222 | """ 223 | expect_summaries(tmpdir, src, { 224 | "baz": "Baz::Bar(Bar{x: 3})" 225 | }) 226 | -------------------------------------------------------------------------------- /rust_test_crate/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::all, unused)] 2 | 3 | // Set a breakpoint where you want ot inspect and open your debug log. 4 | // Use commands like `script lldb.frame.FindVariable("foo").GetNonSyntheticValue()` 5 | // for interactive testing. 6 | 7 | use std::{ 8 | borrow::Cow, 9 | collections::{HashMap, VecDeque}, 10 | rc::Rc, 11 | sync::Arc, 12 | }; 13 | 14 | use core::iter::FromIterator; 15 | 16 | fn basic_datatypes() { 17 | let x: char = 'A'; 18 | let y: i8 = 65; 19 | let z: i8 = -128; 20 | let w: u8 = 65; 21 | 22 | let xx: i16 = 1000; 23 | let xy: u16 = 1000; 24 | 25 | println!("") 26 | } 27 | 28 | #[derive(Default)] 29 | struct StructWithManyMembers { 30 | x: i32, 31 | y: f64, 32 | z: i32, 33 | w: i32, 34 | q: i32, 35 | f: i32, 36 | g: i32, 37 | } 38 | 39 | enum A { 40 | X, 41 | Y, 42 | Z, 43 | V(Vec), 44 | D(StructWithManyMembers), 45 | } 46 | 47 | #[derive(Clone, PartialEq, Debug)] 48 | pub enum B { 49 | Foo(Box), 50 | Bar(Box<[B; 2]>), 51 | Baz(i32), 52 | } 53 | 54 | pub enum LargeEarly { 55 | Foo(Vec), 56 | 57 | Bar, 58 | Baz, 59 | Quux, 60 | } 61 | 62 | pub enum LargeMiddle { 63 | Foo, 64 | Bar, 65 | Baz(Vec), 66 | Quux, 67 | } 68 | 69 | pub enum LargeLate { 70 | Foo, 71 | Bar, 72 | Baz, 73 | Quux(Vec), 74 | } 75 | 76 | #[derive(Clone, PartialEq, Debug)] 77 | pub enum TokenKind<'a> { 78 | Literal(Vec), 79 | Identifier(&'a str), 80 | 81 | Let, 82 | If, 83 | Else, 84 | True, 85 | False, 86 | } 87 | 88 | fn enums() { 89 | let vd = VecDeque::from([1, 2, 3]); 90 | let foo = StructWithManyMembers { 91 | x: 1, 92 | y: 3.2, 93 | ..Default::default() 94 | }; 95 | let a = A::D(foo); 96 | 97 | let vec_in_enum = A::V(vec![1, 2, 3]); 98 | 99 | let long_vec_in_enum = A::V(Vec::from_iter(0..100)); 100 | 101 | let b = B::Foo(Box::new(B::Baz(42))); 102 | 103 | let le1 = LargeEarly::Foo(vec![1]); 104 | let le2 = LargeEarly::Bar; 105 | let le3 = LargeEarly::Baz; 106 | let le4 = LargeEarly::Quux; 107 | 108 | let lm1 = LargeMiddle::Foo; 109 | let lm2 = LargeMiddle::Bar; 110 | let lm3 = LargeMiddle::Baz(vec![42]); 111 | let lm4 = LargeMiddle::Quux; 112 | 113 | let ll2 = LargeLate::Foo; 114 | let ll3 = LargeLate::Bar; 115 | let ll4 = LargeLate::Baz; 116 | let ll1 = LargeLate::Quux(vec![42]); 117 | 118 | let x = TokenKind::False; 119 | 120 | println!(""); 121 | } 122 | 123 | // TODO: implement dependencies for our test harness 124 | // and replace the hasmap access tests aswell as this. 125 | // We need some way to get deterministic ordering though. 126 | fn hashmap() { 127 | use std::collections::HashMap; 128 | use std::hash::{BuildHasherDefault, Hasher}; 129 | use std::iter::FromIterator; 130 | #[derive(Default)] 131 | struct IdentityHash(u64); 132 | impl Hasher for IdentityHash { 133 | fn write(&mut self, _: &[u8]) { 134 | unimplemented!() 135 | } 136 | fn write_u8(&mut self, n: u8) { 137 | self.0 = u64::from(n) 138 | } 139 | fn write_u16(&mut self, n: u16) { 140 | self.0 = u64::from(n) 141 | } 142 | fn write_u32(&mut self, n: u32) { 143 | self.0 = u64::from(n) 144 | } 145 | fn write_u64(&mut self, n: u64) { 146 | self.0 = n 147 | } 148 | fn write_usize(&mut self, n: usize) { 149 | self.0 = n as u64 150 | } 151 | fn write_i8(&mut self, n: i8) { 152 | self.0 = n as u64 153 | } 154 | fn write_i16(&mut self, n: i16) { 155 | self.0 = n as u64 156 | } 157 | fn write_i32(&mut self, n: i32) { 158 | self.0 = n as u64 159 | } 160 | fn write_i64(&mut self, n: i64) { 161 | self.0 = n as u64 162 | } 163 | fn write_isize(&mut self, n: isize) { 164 | self.0 = n as u64 165 | } 166 | fn finish(&self) -> u64 { 167 | self.0 168 | } 169 | } 170 | let mut hm = HashMap::>::from_iter([ 171 | (3, "foo"), 172 | (12, "bar"), 173 | ]); 174 | println!(""); 175 | } 176 | 177 | fn collections() { 178 | let array = [1, 2, 3]; 179 | let array_2 = [[1, 2, 3], [4, 5, 6]]; 180 | let v = vec![1, 2, 3]; 181 | let vd = VecDeque::from_iter([1, 2, 3]); 182 | 183 | let vec_i8 = vec![3i8, -1i8, 'A' as i8]; 184 | 185 | let vec_char = vec!['A', 'B', 'C']; 186 | 187 | println!(""); 188 | } 189 | 190 | fn std_lib_types() { 191 | let x = Box::new(42); 192 | 193 | let y = Box::new(Rc::new(42)); 194 | 195 | let cow_str = Cow::::Borrowed("asdf"); 196 | 197 | let rc_string: Rc = Rc::from("asdf".to_string()); 198 | 199 | let rc_str: Rc = Rc::from("asdf"); 200 | 201 | let rc_slice = Rc::<[i32]>::from([1, 2, 3]); 202 | 203 | println!(""); 204 | } 205 | 206 | // see https://github.com/cmrschwarz/rust-prettifier-for-lldb/issues/5 207 | fn rc_of_vec() { 208 | const ARRAY: [i32; 3] = [1, 2, 3]; 209 | 210 | let vec = Vec::from(ARRAY); 211 | 212 | let vec_deque = VecDeque::from(ARRAY); 213 | 214 | let rc_vec = Rc::new(Vec::from(ARRAY)); 215 | 216 | let rc_vec_deque = Rc::new(VecDeque::from(ARRAY)); 217 | 218 | let rc_slice: Rc<[i32]> = Rc::new(ARRAY); 219 | 220 | let rc_ref_slice: Rc<&[i32]> = Rc::new(&ARRAY); 221 | 222 | let arc_vec = Arc::new(Vec::from(ARRAY)); 223 | 224 | let arc_vec_deque = Arc::new(VecDeque::from(ARRAY)); 225 | 226 | let arc_slice: Arc<[i32]> = Arc::new(ARRAY); 227 | 228 | let arc_ref_slice: Arc<&[i32]> = Arc::new(&ARRAY[..]); 229 | 230 | println!(""); 231 | } 232 | 233 | enum MyEnum { 234 | A(&'static str), 235 | B(i32), 236 | C(Vec), 237 | } 238 | 239 | fn demo() { 240 | enum MyEnum { 241 | A, 242 | C { x: i32, y: f32 }, 243 | D(Vec), 244 | } 245 | let a = MyEnum::A; 246 | let c = MyEnum::C { x: 1, y: 2.5 }; 247 | let d = MyEnum::D(vec![1, 2, 3]); 248 | 249 | let cd = VecDeque::from_iter([1, 2, 3, 5, 423]); 250 | 251 | println!(""); 252 | } 253 | 254 | fn main() { 255 | basic_datatypes(); 256 | enums(); 257 | hashmap(); 258 | collections(); 259 | std_lib_types(); 260 | rc_of_vec(); 261 | demo(); 262 | } 263 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /rust_prettifier_for_lldb.py: -------------------------------------------------------------------------------- 1 | # rust-prettifier-for-lldb, Christian Schwarz, 2024 2 | 3 | # This file is based on by vadimcn/codelldb by Vadim Chugunov 4 | # https://github.com/vadimcn/codelldb/blob/05502bf75e4e7878a99b0bf0a7a81bba2922cbe3/formatters/rust.py 5 | # The original version was used and adapted under the terms of the MIT License: 6 | # 7 | # The MIT License (MIT) 8 | # 9 | # Copyright (c) 2016 Vadim Chugunov 10 | # 11 | # Permission is hereby granted, free of charge, to any person obtaining a copy 12 | # of this software and associated documentation files (the "Software"), to deal 13 | # in the Software without restriction, including without limitation the rights 14 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 | # copies of the Software, and to permit persons to whom the Software is 16 | # furnished to do so, subject to the following conditions: 17 | # 18 | # The above copyright notice and this permission notice shall be included in all 19 | # copies or substantial portions of the Software. 20 | # 21 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 27 | # SOFTWARE. 28 | 29 | 30 | from __future__ import print_function, division 31 | import sys 32 | import lldb # type: ignore 33 | import weakref 34 | import re 35 | 36 | module = sys.modules[__name__] 37 | rust_category = None 38 | lldb_major_version = None 39 | 40 | MAX_STRING_SUMMARY_LENGTH = 1024 41 | MAX_SEQUENCE_SUMMARY_LENGTH = 10 42 | 43 | TARGET_ADDR_SIZE = 8 44 | 45 | 46 | def initialize_category(debugger, internal_dict): 47 | global rust_category, MAX_STRING_SUMMARY_LENGTH, TARGET_ADDR_SIZE, lldb_major_version 48 | 49 | version_string_match = re.match( 50 | r"lldb version (\d+)\.\d+", 51 | lldb.SBDebugger.GetVersionString(), 52 | re.IGNORECASE 53 | ) 54 | if version_string_match is not None: 55 | lldb_major_version = version_string_match.groups(1) 56 | 57 | # remove previous conflicting prettifiers potentially added e.g. by CodeLLDB 58 | rust_category = debugger.DeleteCategory('Rust') 59 | rust_category = debugger.CreateCategory('Rust') 60 | # rust_category.AddLanguage(lldb.eLanguageTypeRust) 61 | rust_category.SetEnabled(True) 62 | 63 | attach_synthetic_to_type(TupleSynthProvider, r'^\(.*\)$', True) 64 | # *-windows-msvc uses this name since 1.47 65 | attach_synthetic_to_type(MsvcTupleSynthProvider, r'^tuple\$?<.+>$', True) 66 | 67 | attach_synthetic_to_type(CharSynthProvider, 'char32_t') 68 | 69 | # there is no 1 byte char type in rust, so these have to be u8/i8 70 | attach_synthetic_to_type(U8SynthProvider, 'unsigned char') 71 | attach_synthetic_to_type(I8SynthProvider, 'char') 72 | 73 | attach_synthetic_to_type(StrSliceSynthProvider, '&str') 74 | attach_synthetic_to_type(StrSliceSynthProvider, 'str*') 75 | # *-windows-msvc uses this name since 1.5? 76 | attach_synthetic_to_type(StrSliceSynthProvider, 'str') 77 | attach_synthetic_to_type(StrSliceSynthProvider, 'ref$') 78 | attach_synthetic_to_type(StrSliceSynthProvider, 'ref_mut$') 79 | 80 | attach_synthetic_to_type(StdStringSynthProvider, 81 | '^(collections|alloc)::string::String$', True) 82 | attach_synthetic_to_type(StdVectorSynthProvider, 83 | r'^(collections|alloc)::vec::Vec<.+>$', True) 84 | attach_synthetic_to_type(StdVecDequeSynthProvider, 85 | r'^(collections|alloc::collections)::vec_deque::VecDeque<.+>$', True) 86 | 87 | attach_synthetic_to_type(MsvcEnumSynthProvider, r'^enum\$<.+>$', True) 88 | attach_synthetic_to_type(MsvcEnum2SynthProvider, r'^enum2\$<.+>$', True) 89 | 90 | attach_synthetic_to_type(SliceSynthProvider, r'^&(mut *)?\[.*\]$', True) 91 | attach_synthetic_to_type(MsvcSliceSynthProvider, 92 | r'^(mut *)?slice\$?<.+>.*$', True) 93 | attach_synthetic_to_type(MsvcSliceSynthProvider, 94 | r'^ref(_mut)?\$.*>$', True) 95 | 96 | attach_synthetic_to_type(StdCStringSynthProvider, 97 | '^(std|alloc)::ffi::c_str::CString$', True) 98 | attach_synthetic_to_type(StdCStrSynthProvider, 99 | '^&?(std|core)::ffi::c_str::CStr$', True) 100 | attach_synthetic_to_type(StdCStrSynthProvider, 101 | 'ref$') 102 | attach_synthetic_to_type(StdCStrSynthProvider, 103 | 'ref_mut$') 104 | 105 | attach_synthetic_to_type(StdOsStringSynthProvider, 106 | 'std::ffi::os_str::OsString') 107 | attach_synthetic_to_type(StdOsStrSynthProvider, 108 | '^&?std::ffi::os_str::OsStr', True) 109 | attach_synthetic_to_type(StdOsStrSynthProvider, 110 | 'ref$') 111 | attach_synthetic_to_type(StdOsStrSynthProvider, 112 | 'ref_mut$') 113 | 114 | attach_synthetic_to_type(StdPathBufSynthProvider, 'std::path::PathBuf') 115 | attach_synthetic_to_type(StdPathSynthProvider, '^&?std::path::Path', True) 116 | attach_synthetic_to_type(StdPathSynthProvider, 'ref$') 117 | attach_synthetic_to_type(StdPathSynthProvider, 'ref_mut$') 118 | 119 | attach_synthetic_to_type(StdRcSynthProvider, r'^alloc::rc::Rc<.+>$', True) 120 | attach_synthetic_to_type( 121 | StdRcSynthProvider, r'^alloc::rc::Weak<.+>$', True) 122 | attach_synthetic_to_type( 123 | StdArcSynthProvider, r'^alloc::(sync|arc)::Arc<.+>$', True) 124 | attach_synthetic_to_type( 125 | StdArcSynthProvider, r'^alloc::(sync|arc)::Weak<.+>$', True) 126 | attach_synthetic_to_type(StdMutexSynthProvider, 127 | r'^std::sync::mutex::Mutex<.+>$', True) 128 | 129 | attach_synthetic_to_type(StdCellSynthProvider, 130 | r'^core::cell::Cell<.+>$', True) 131 | attach_synthetic_to_type(StdUnsafeCellSynthProvider, 132 | r'^core::cell::UnsafeCell<.+>$', True) 133 | attach_synthetic_to_type(StdRefCellSynthProvider, 134 | r'^core::cell::RefCell<.+>$', True) 135 | attach_synthetic_to_type( 136 | StdRefCellBorrowSynthProvider, r'^core::cell::Ref<.+>$', True) 137 | attach_synthetic_to_type( 138 | StdRefCellBorrowSynthProvider, r'^core::cell::RefMut<.+>$', True) 139 | 140 | attach_synthetic_to_type( 141 | StdHashMapSynthProvider, r'^std::collections::hash::map::HashMap<.+>$', True) 142 | attach_synthetic_to_type( 143 | StdHashSetSynthProvider, r'^std::collections::hash::set::HashSet<.+>$', True) 144 | 145 | attach_synthetic_to_type(OptionSynthProvider, 146 | r'^core::option::Option<.+>$', True) 147 | attach_synthetic_to_type(ResultSynthProvider, 148 | r'^core::result::Result<.+>$', True) 149 | attach_synthetic_to_type(CowSynthProvider, 150 | r'^alloc::borrow::Cow<.+>$', True) 151 | 152 | attach_synthetic_to_type(CrossbeamAtomicCellSynthProvider, 153 | r'^crossbeam_utils::atomic::atomic_cell::AtomicCell<.+>$', True) 154 | 155 | debugger.HandleCommand( 156 | "type summary add" 157 | + f" --python-function {__name__}.enum_summary_provider" 158 | + f" --recognizer-function {__name__}.enum_recognizer_function", 159 | ) 160 | debugger.HandleCommand( 161 | "type synthetic add" 162 | + f" --python-class {__name__}.GenericEnumSynthProvider" 163 | + f" --recognizer-function {__name__}.enum_recognizer_function", 164 | ) 165 | 166 | if 'rust' in internal_dict.get('source_languages', []): 167 | lldb.SBDebugger.SetInternalVariable('target.process.thread.step-avoid-regexp', 168 | '^ 231 | def read_unique_ptr(valobj): 232 | pointer = valobj.GetChildMemberWithName('pointer') 233 | if pointer.TypeIsPointerType(): # Between 1.33 and 1.63 pointer was just *const T 234 | return pointer 235 | return pointer.GetChildAtIndex(0) 236 | 237 | 238 | def string_from_addr(process, addr, length): 239 | if length <= 0: 240 | return u'' 241 | error = lldb.SBError() 242 | data = process.ReadMemory(addr, length, error) 243 | if error.Success(): 244 | return data.decode('utf8', 'replace') 245 | else: 246 | raise Exception('ReadMemory error: %s', error.GetCString()) 247 | 248 | 249 | def string_from_ptr(pointer, length): 250 | return string_from_addr(pointer.GetProcess(), pointer.GetValueAsUnsigned(), length) 251 | 252 | 253 | # turns foo::Bar::Baz::Quux into Quux 254 | def unscope_typename(type_name): 255 | start = 0 256 | level = 0 257 | prev_was_quote = False 258 | for i, c in enumerate(type_name): 259 | if c == '<': 260 | level += 1 261 | continue 262 | if c == '>': 263 | level -= 1 264 | continue 265 | if c == ':': 266 | if prev_was_quote: 267 | if level == 0: 268 | start = i + 1 269 | prev_was_quote = False 270 | continue 271 | prev_was_quote = True 272 | continue 273 | prev_was_quote = False 274 | 275 | return type_name[start::] 276 | 277 | # turns Cow::Borrowed::("asdf") into Cow::Borrowed("asdf") 278 | def drop_template_args(type_name): 279 | res = "" 280 | level = 0 281 | start = 0 282 | for i, c in enumerate(type_name): 283 | if c == '<': 284 | if level == 0: 285 | res += type_name[start:i] 286 | level += 1 287 | elif c == '>': 288 | level -= 1 289 | if level == 0: 290 | start = i + 1 291 | res += type_name[start:] 292 | return res 293 | 294 | 295 | def get_template_params(type_name): 296 | params = [] 297 | level = 0 298 | start = 0 299 | for i, c in enumerate(type_name): 300 | if c == '<': 301 | level += 1 302 | if level == 1: 303 | start = i + 1 304 | elif c == '>': 305 | level -= 1 306 | if level == 0: 307 | params.append(type_name[start:i].strip()) 308 | elif c == ',' and level == 1: 309 | params.append(type_name[start:i].strip()) 310 | start = i + 1 311 | return params 312 | 313 | 314 | def obj_summary(valobj, obj_typename=None, unavailable='{...}', parenthesize_single_value=False, max_len=32): 315 | summary = valobj.GetSummary() 316 | if summary is not None: 317 | if parenthesize_single_value: 318 | return f"({summary})" 319 | return summary 320 | child_count = valobj.GetNumChildren() 321 | if child_count != 0: 322 | if valobj.GetChildAtIndex(0).GetName() in ['0', '__0'] and obj_typename is None: 323 | return tuple_summary(valobj) 324 | 325 | if obj_typename is None: 326 | summary = "{" 327 | else: 328 | summary = f"{obj_typename}{{" 329 | 330 | for i in range(child_count): 331 | name = valobj.GetType().GetFieldAtIndex(i).GetName() 332 | value = valobj.GetChildAtIndex(i) 333 | member_summary = f"{name}: {obj_summary(value)}" 334 | if i != 0: 335 | summary += ", " 336 | if len(summary) + 1 + len(member_summary) > max_len: 337 | summary += ".." 338 | break 339 | summary += member_summary 340 | summary += "}" 341 | if obj_typename is not None and parenthesize_single_value: 342 | return f"({summary})" 343 | return summary 344 | 345 | summary = valobj.GetValue() 346 | if summary is not None: 347 | if obj_typename is None: 348 | res = summary 349 | else: 350 | res = f"{obj_typename}({summary})" 351 | if parenthesize_single_value: 352 | return f"({res})" 353 | return res 354 | 355 | return unavailable 356 | 357 | 358 | def sequence_summary(childern, max_len=MAX_STRING_SUMMARY_LENGTH, max_elem_count= MAX_SEQUENCE_SUMMARY_LENGTH): 359 | s = '' 360 | for (i, child) in enumerate(childern): 361 | if len(s) > 0: 362 | s += ', ' 363 | summary = obj_summary(child) 364 | if len(s + summary) > max_len or i >= max_elem_count: 365 | s += '...' 366 | break 367 | s += summary 368 | return s 369 | 370 | 371 | def tuple_summary(obj, skip_first=0, max_len=32, include_parens=True): 372 | if include_parens: 373 | s = "(" 374 | else: 375 | s = "" 376 | for i in range(skip_first, obj.GetNumChildren()): 377 | if i > 0: 378 | s += ', ' 379 | os = obj_summary(obj.GetChildAtIndex(i), max_len=max_len-len(s)-1) 380 | if len(s) + len(os) + int(include_parens) > max_len: 381 | s += '..' 382 | break 383 | s += os 384 | if include_parens: 385 | s += ')' 386 | return s 387 | 388 | 389 | class RustSynthProvider(object): 390 | synth_by_id = weakref.WeakValueDictionary() 391 | next_id = 0 392 | obj_id = 0 393 | valobj = None 394 | summary = None 395 | 396 | def __init__(self, valobj, dict={}): 397 | self.valobj = valobj 398 | self.obj_id = RustSynthProvider.next_id 399 | RustSynthProvider.synth_by_id[self.obj_id] = self 400 | RustSynthProvider.next_id += 1 401 | 402 | def update(self): 403 | return True 404 | 405 | def has_children(self): 406 | return False 407 | 408 | def num_children(self): 409 | return 0 410 | 411 | def get_child_at_index(self, index): 412 | return None 413 | 414 | def get_child_index(self, name): 415 | if name == '$$object-id$$': 416 | return self.obj_id 417 | 418 | return self.get_index_of_child(name) 419 | 420 | def get_summary(self): 421 | return self.summary 422 | 423 | 424 | class CharSynthProvider(RustSynthProvider): 425 | def update(self): 426 | value = self.valobj.GetValueAsUnsigned() 427 | c = chr(value) 428 | if c.isprintable(): 429 | self.summary = f"'{c}'" 430 | else: 431 | self.summary = f"U+0x{value:08X}" 432 | 433 | 434 | class U8SynthProvider(RustSynthProvider): 435 | def update(self): 436 | value = self.valobj.GetValueAsUnsigned() 437 | self.summary = f"{int(value)}" 438 | 439 | 440 | class I8SynthProvider(RustSynthProvider): 441 | def update(self): 442 | value = self.valobj.GetValueAsSigned() 443 | self.summary = f"{int(value)}" 444 | 445 | 446 | class TupleSynthProvider(RustSynthProvider): 447 | def update(self): 448 | self.summary = tuple_summary(self.valobj) 449 | 450 | def has_children(self): 451 | return True 452 | 453 | def num_children(self): 454 | return self.valobj.GetNumChildren() 455 | 456 | def get_index_of_child(self, name): 457 | return int(name.lstrip('_[').rstrip(']')) 458 | 459 | def get_child_at_index(self, index): 460 | value = self.valobj.GetChildAtIndex(index) 461 | value = self.valobj.CreateValueFromData(str(index), value.GetData(), value.GetType()) 462 | return value 463 | 464 | 465 | class ArrayLikeSynthProvider(RustSynthProvider): 466 | '''Base class for providers that represent array-like objects''' 467 | 468 | def update(self): 469 | self.ptr, self.len = self.ptr_and_len(self.valobj) # type: ignore 470 | self.item_type = self.ptr.GetType().GetPointeeType() 471 | self.item_size = self.item_type.GetByteSize() 472 | 473 | def ptr_and_len(self, obj): 474 | pass # abstract 475 | 476 | def num_children(self): 477 | return self.len 478 | 479 | def has_children(self): 480 | return True 481 | 482 | def get_child_at_index(self, index): 483 | if not 0 <= index < self.len: 484 | return None 485 | offset = index * self.item_size 486 | return self.ptr.CreateChildAtOffset('[%s]' % index, offset, self.item_type) 487 | 488 | def get_index_of_child(self, name): 489 | return int(name.lstrip('[').rstrip(']')) 490 | 491 | def get_summary(self): 492 | return '(%d)' % (self.len,) 493 | 494 | 495 | class StdVectorSynthProvider(ArrayLikeSynthProvider): 496 | def ptr_and_len(self, vec): 497 | element_type = self.valobj.GetType().GetTemplateArgumentType(0) 498 | ptr = read_unique_ptr(gcm(vec, 'buf', 'inner', 'ptr', 'pointer')) 499 | ptr = ptr.Cast(element_type.GetPointerType()) 500 | len = gcm(vec, 'len').GetValueAsUnsigned() 501 | return (ptr, len) 502 | 503 | def get_summary(self): 504 | return '(%d) vec![%s]' % (self.len, sequence_summary((self.get_child_at_index(i) for i in range(self.len)))) 505 | 506 | 507 | class StdVecDequeSynthProvider(RustSynthProvider): 508 | def update(self): 509 | element_type = self.valobj.GetType().GetTemplateArgumentType(0) 510 | ptr = read_unique_ptr( 511 | gcm(self.valobj, 'buf', 'inner', 'ptr', 'pointer')) 512 | self.ptr = ptr.Cast(element_type.GetPointerType()) 513 | self.cap = ( 514 | gcm(self.valobj, 'buf', 'inner', 'cap') 515 | .GetChildAtIndex(0) 516 | .GetValueAsUnsigned() 517 | ) 518 | 519 | head = gcm(self.valobj, 'head').GetValueAsUnsigned() 520 | 521 | # rust 1.67 changed from a head, tail implementation to a head, length impl 522 | # https://github.com/rust-lang/rust/pull/102991 523 | vd_len = gcm(self.valobj, 'len') 524 | if vd_len.IsValid(): 525 | self.len = vd_len.GetValueAsUnsigned() 526 | self.startptr = head 527 | else: 528 | tail = gcm(self.valobj, 'tail').GetValueAsUnsigned() 529 | self.len = head - tail 530 | self.startptr = tail 531 | 532 | self.item_type = self.ptr.GetType().GetPointeeType() 533 | self.item_size = self.item_type.GetByteSize() 534 | 535 | def num_children(self): 536 | return self.len 537 | 538 | def has_children(self): 539 | return True 540 | 541 | def get_child_at_index(self, index): 542 | if not 0 <= index < self.num_children(): 543 | return None 544 | offset = ((self.startptr + index) % self.cap) * self.item_size 545 | return self.ptr.CreateChildAtOffset('[%s]' % index, offset, self.item_type) 546 | 547 | def get_index_of_child(self, name): 548 | return int(name.lstrip('[').rstrip(']')) 549 | 550 | def get_summary(self): 551 | return '(%d) VecDeque[%s]' % ( 552 | self.num_children(), 553 | sequence_summary((self.get_child_at_index(i) 554 | for i in range(self.num_children()))) 555 | ) 556 | 557 | 558 | class SliceSynthProvider(ArrayLikeSynthProvider): 559 | def ptr_and_len(self, vec): 560 | return ( 561 | gcm(vec, 'data_ptr'), 562 | gcm(vec, 'length').GetValueAsUnsigned() 563 | ) 564 | 565 | def get_summary(self): 566 | return '(%d) &[%s]' % (self.len, sequence_summary((self.get_child_at_index(i) for i in range(self.len)))) 567 | 568 | 569 | class MsvcSliceSynthProvider(SliceSynthProvider): 570 | def get_type_name(self): 571 | tparams = get_template_params(self.valobj.GetTypeName()) 572 | return '&[' + tparams[0] + ']' 573 | 574 | 575 | # Base class for *String providers 576 | class StringLikeSynthProvider(ArrayLikeSynthProvider): 577 | def update(self): 578 | super().update() 579 | self.strval = string_from_ptr( 580 | self.ptr, 581 | min(self.len, MAX_STRING_SUMMARY_LENGTH) 582 | ) 583 | if self.len > MAX_STRING_SUMMARY_LENGTH: 584 | self.strval += u'...' 585 | 586 | def get_child_at_index(self, index): 587 | ch = ArrayLikeSynthProvider.get_child_at_index(self, index) 588 | ch.SetFormat(lldb.eFormatChar) 589 | return ch 590 | 591 | def get_summary(self): 592 | return u'"%s"' % self.strval 593 | 594 | 595 | class StrSliceSynthProvider(StringLikeSynthProvider): 596 | def ptr_and_len(self, valobj): 597 | return ( 598 | gcm(valobj, 'data_ptr'), 599 | gcm(valobj, 'length').GetValueAsUnsigned() 600 | ) 601 | 602 | def get_type_name(self): 603 | return '&str' 604 | 605 | 606 | class StdStringSynthProvider(StringLikeSynthProvider): 607 | def ptr_and_len(self, valobj): 608 | vec = gcm(valobj, 'vec') 609 | return ( 610 | read_unique_ptr(gcm(vec, 'buf', 'inner', 'ptr', 'pointer')), 611 | gcm(vec, 'len').GetValueAsUnsigned() 612 | ) 613 | 614 | 615 | class StdCStringSynthProvider(StringLikeSynthProvider): 616 | def ptr_and_len(self, valobj): 617 | vec = gcm(valobj, 'inner') 618 | return ( 619 | gcm(vec, 'data_ptr'), 620 | gcm(vec, 'length').GetValueAsUnsigned() - 1 621 | ) 622 | 623 | 624 | class StdOsStringSynthProvider(StringLikeSynthProvider): 625 | def ptr_and_len(self, valobj): 626 | vec = gcm(valobj, 'inner', 'inner') 627 | tmp = gcm(vec, 'bytes') # Windows OSString has an extra layer 628 | if tmp.IsValid(): 629 | vec = tmp 630 | return ( 631 | read_unique_ptr(gcm(vec, 'buf', 'ptr')), 632 | gcm(vec, 'len').GetValueAsUnsigned() 633 | ) 634 | 635 | 636 | class FFISliceSynthProvider(StringLikeSynthProvider): 637 | def ptr_and_len(self, valobj): 638 | process = valobj.GetProcess() 639 | slice_ptr = valobj.GetLoadAddress() 640 | data_ptr_type = valobj.GetTarget().GetBasicType( 641 | lldb.eBasicTypeChar).GetPointerType() 642 | # Unsized slice objects have incomplete debug info, so here we just assume standard slice 643 | # reference layout: [, ] 644 | error = lldb.SBError() 645 | pointer = valobj.CreateValueFromAddress( 646 | 'data', slice_ptr, data_ptr_type) 647 | length = process.ReadPointerFromMemory( 648 | slice_ptr + process.GetAddressByteSize(), error) 649 | return pointer, length 650 | 651 | 652 | class StdCStrSynthProvider(FFISliceSynthProvider): 653 | def ptr_and_len(self, valobj): 654 | ptr, len = FFISliceSynthProvider.ptr_and_len(self, valobj) 655 | return (ptr, len-1) # drop terminaing '\0' 656 | 657 | 658 | class StdOsStrSynthProvider(FFISliceSynthProvider): 659 | pass 660 | 661 | 662 | class StdPathBufSynthProvider(StdOsStringSynthProvider): 663 | def ptr_and_len(self, valobj): 664 | return StdOsStringSynthProvider.ptr_and_len(self, gcm(valobj, 'inner')) 665 | 666 | 667 | class StdPathSynthProvider(FFISliceSynthProvider): 668 | pass 669 | 670 | 671 | class DerefSynthProvider(RustSynthProvider): 672 | deref = lldb.SBValue() 673 | 674 | def has_children(self): 675 | return self.deref.MightHaveChildren() 676 | 677 | def num_children(self): 678 | return self.deref.GetNumChildren() 679 | 680 | def get_child_at_index(self, index): 681 | return self.deref.GetChildAtIndex(index) 682 | 683 | def get_index_of_child(self, name): 684 | return self.deref.GetIndexOfChildWithName(name) 685 | 686 | def get_summary(self): 687 | return obj_summary(self.deref) 688 | 689 | 690 | # Base for Rc and Arc 691 | class StdRefCountedSynthProvider(RustSynthProvider): 692 | weak = 0 693 | strong = 0 694 | slice_len = None 695 | value = None 696 | 697 | def has_children(self): 698 | return True 699 | 700 | def num_children(self): 701 | return self.value.GetNumChildren() if self.slice_len is None else self.slice_len 702 | 703 | def get_child_at_index(self, i): 704 | if self.slice_len: 705 | elem_size = self.value.GetByteSize() 706 | return self.value.CreateChildAtOffset( 707 | f'[{i}]', i * elem_size, self.value.GetType() 708 | ) 709 | 710 | return self.value.GetChildAtIndex(i) 711 | 712 | 713 | def get_index_of_child(self, name): 714 | if self.slice_len is not None: 715 | return int(name.lstrip('[').rstrip(']')) 716 | 717 | return self.value.GetIndexOfChildWithName(name) 718 | 719 | def get_summary(self): 720 | if self.weak != 0: 721 | s = '(strong:%d, weak:%d) ' % (self.strong, self.weak) 722 | else: 723 | s = '(strong:%d) ' % self.strong 724 | if self.strong > 0: 725 | if self.slice_len is not None: 726 | if self.value.GetType().GetName() == "unsigned char": 727 | str_data = string_from_addr( 728 | self.value.GetProcess(), 729 | self.value.GetLoadAddress(), 730 | min(MAX_STRING_SUMMARY_LENGTH, self.slice_len) 731 | ) 732 | s += f"\"{str_data}\"" 733 | else: 734 | s += "[%s]" % sequence_summary(( 735 | self.get_child_at_index(i) for i in range(self.slice_len) 736 | )) 737 | else: 738 | s += obj_summary(self.value) 739 | else: 740 | s += '' 741 | return s 742 | 743 | 744 | class StdRcSynthProvider(StdRefCountedSynthProvider): 745 | def update(self): 746 | inner = read_unique_ptr(gcm(self.valobj, 'ptr')) 747 | self.strong = gcm(inner, 'strong', 'value', 'value').GetValueAsUnsigned() 748 | self.weak = gcm(inner, 'weak', 'value', 'value').GetValueAsUnsigned() 749 | if self.strong > 0: 750 | self.value = gcm(inner, 'value') 751 | self.weak -= 1 # There's an implicit weak reference communally owned by all the strong pointers 752 | if self.valobj.GetType().size == 2 * TARGET_ADDR_SIZE: 753 | self.slice_len = gcm(self.valobj, "ptr", "pointer", "length").GetValueAsUnsigned() 754 | else: 755 | self.value = lldb.SBValue() 756 | self.value.SetPreferSyntheticValue(True) 757 | 758 | 759 | class StdArcSynthProvider(StdRefCountedSynthProvider): 760 | def update(self): 761 | inner = read_unique_ptr(gcm(self.valobj, 'ptr')) 762 | self.strong = gcm(inner, 'strong', 'v', 'value').GetValueAsUnsigned() 763 | self.weak = gcm(inner, 'weak', 'v', 'value').GetValueAsUnsigned() 764 | if self.strong > 0: 765 | self.value = gcm(inner, 'data') 766 | if self.valobj.GetType().size == 2 * TARGET_ADDR_SIZE: 767 | self.slice_len = gcm(self.valobj, "ptr", "pointer", "length").GetValueAsUnsigned() 768 | self.weak -= 1 # There's an implicit weak reference communally owned by all the strong pointers 769 | else: 770 | self.value = lldb.SBValue() 771 | self.value.SetPreferSyntheticValue(True) 772 | 773 | 774 | class StdMutexSynthProvider(DerefSynthProvider): 775 | def update(self): 776 | self.deref = gcm(self.valobj, 'data', 'value') 777 | self.deref.SetPreferSyntheticValue(True) 778 | 779 | 780 | class StdCellSynthProvider(DerefSynthProvider): 781 | def update(self): 782 | self.deref = gcm(self.valobj, 'value', 'value') 783 | self.deref.SetPreferSyntheticValue(True) 784 | 785 | 786 | class StdUnsafeCellSynthProvider(DerefSynthProvider): 787 | def update(self): 788 | self.deref = gcm(self.valobj, 'value') 789 | self.deref.SetPreferSyntheticValue(True) 790 | 791 | class StdRefCellSynthProvider(DerefSynthProvider): 792 | def update(self): 793 | self.deref = gcm(self.valobj, 'value', 'value') 794 | self.deref.SetPreferSyntheticValue(True) 795 | 796 | def get_summary(self): 797 | borrow = gcm(self.valobj, 'borrow', 'value', 798 | 'value').GetValueAsSigned() 799 | s = '' 800 | if borrow < 0: 801 | s = '(borrowed:mut) ' 802 | elif borrow > 0: 803 | s = '(borrowed:%d) ' % borrow 804 | return s + obj_summary(self.deref) 805 | 806 | 807 | class StdRefCellBorrowSynthProvider(DerefSynthProvider): 808 | def update(self): 809 | self.deref = gcm(self.valobj, 'value', 'pointer').Dereference() 810 | self.deref.SetPreferSyntheticValue(True) 811 | 812 | 813 | class EnumSynthProvider(RustSynthProvider): 814 | variant = lldb.SBValue() 815 | typename_summary = "" 816 | variant_name = "" 817 | variant_summary = "" 818 | skip_first = 0 819 | 820 | def has_children(self): 821 | return self.variant.MightHaveChildren() 822 | 823 | def num_children(self): 824 | return self.variant.GetNumChildren() - self.skip_first 825 | 826 | def get_child_at_index(self, index): 827 | return self.variant.GetChildAtIndex(index + self.skip_first) 828 | 829 | def get_index_of_child(self, name): 830 | return self.variant.GetIndexOfChildWithName(name) - self.skip_first 831 | 832 | def get_summary(self): 833 | value_summary = self.variant_name + self.variant_summary 834 | 835 | if self.typename_summary != "": 836 | return self.typename_summary + "::" + value_summary 837 | else: 838 | return value_summary 839 | 840 | 841 | def get_enum_discriminator_value(union, index): 842 | obj = union.GetChildAtIndex(index) 843 | if not obj or obj.GetNumChildren() < 1: 844 | return None 845 | 846 | discr = obj.GetChildAtIndex(0) 847 | if not discr or discr.GetName() != "$discr$": 848 | return None 849 | 850 | return discr.GetValueAsUnsigned() 851 | 852 | def enum_summary_provider(valobj, dict): 853 | return get_synth_summary(GenericEnumSynthProvider, valobj, dict) 854 | 855 | def enum_recognizer_function(sbtype, _internal_dict): 856 | if sbtype.GetNumberOfFields() != 1: 857 | return False 858 | 859 | if sbtype.GetFieldAtIndex(0).GetName() != "$variants$": 860 | return False 861 | 862 | name = sbtype.GetName() 863 | special_cases = ["core::option::Option", "core::result::Result", "alloc::borrow::Cow"] 864 | for case in special_cases: 865 | if name.startswith(case): 866 | return False 867 | 868 | return True 869 | 870 | 871 | class GenericEnumSynthProvider(EnumSynthProvider): 872 | def update(self): 873 | self.summary = '' 874 | self.variant = self.valobj 875 | 876 | self.valobj.SetPreferSyntheticValue(False) 877 | union = self.valobj.GetChildAtIndex(0) 878 | union.SetPreferSyntheticValue(False) 879 | 880 | # at this point we assume this is a rust enum, 881 | # so if we fail further down the line we report an error 882 | self.variant_name = '' 883 | 884 | enum_type = self.valobj.GetType() 885 | if enum_type.IsPointerType(): 886 | enum_name = "&" + \ 887 | unscope_typename(enum_type.GetPointeeType().GetName()) 888 | else: 889 | enum_name = unscope_typename(enum_type.GetName()) 890 | self.typename_summary = enum_name 891 | 892 | variant_count = union.GetNumChildren() 893 | 894 | discriminator = None 895 | first_variant_without_discriminator = None 896 | 897 | for i in range(variant_count): 898 | dc = get_enum_discriminator_value(union, i) 899 | if dc is None: 900 | if first_variant_without_discriminator is None: 901 | first_variant_without_discriminator = i 902 | else: 903 | return # multiple variants without discriminator 904 | else: 905 | if discriminator is not None: 906 | if dc != discriminator: 907 | return # conflicting discriminator values 908 | else: 909 | discriminator = dc 910 | 911 | selected_variant = discriminator 912 | 913 | if first_variant_without_discriminator is not None: 914 | # probably a pointer based niche 915 | # all of this is just based on trial and error 916 | high_bit = 1 << (8 * TARGET_ADDR_SIZE - 1) 917 | 918 | if variant_count == 1: 919 | selected_variant = 0 920 | elif discriminator >= high_bit: 921 | selected_variant = discriminator - high_bit 922 | if selected_variant >= first_variant_without_discriminator: 923 | if selected_variant + 1 < variant_count: 924 | selected_variant += 1 925 | elif discriminator == 0 or discriminator >= variant_count : 926 | selected_variant = first_variant_without_discriminator 927 | 928 | if selected_variant >= variant_count: 929 | return 930 | 931 | union.SetPreferSyntheticValue(True) 932 | variant_outer = union.GetChildAtIndex(selected_variant) 933 | 934 | if variant_outer.GetNumChildren() == 1 and selected_variant == first_variant_without_discriminator: 935 | variant_outer_subindex = 0 936 | elif variant_outer.GetNumChildren() != 2: 937 | return 938 | else: 939 | variant_outer_subindex = 1 940 | 941 | variant_outer.SetPreferSyntheticValue(True) 942 | variant = variant_outer.GetChildAtIndex(variant_outer_subindex) 943 | 944 | # GetTypeName() gives weird results, e.g. `Foo::A:8`. Don't ask me why. 945 | variant_typename = drop_template_args(unscope_typename(variant.GetType().GetName())) 946 | self.variant_name = variant_typename 947 | 948 | variant_deref = False 949 | 950 | variant_child_count = variant.GetNumChildren() 951 | if variant_child_count == 1 and variant.GetChildAtIndex(0).GetName() in ['0', '__0']: 952 | variant = variant.GetChildAtIndex(0) 953 | variant_child_count = variant.GetNumChildren() 954 | variant_deref = True 955 | 956 | if variant_child_count == 0 and variant.GetValue() is None: 957 | summary = variant.GetSummary() 958 | if summary is not None: 959 | self.variant = variant 960 | self.variant_summary = f"({summary})" 961 | return 962 | 963 | objname = None 964 | if variant_deref and variant_child_count != 0: 965 | objname = variant_typename 966 | 967 | self.variant_summary = obj_summary( 968 | variant, 969 | obj_typename=objname, 970 | parenthesize_single_value=True 971 | ) 972 | 973 | self.variant = variant 974 | 975 | 976 | class OptionSynthProvider(GenericEnumSynthProvider): 977 | def update(self): 978 | super().update() 979 | self.typename_summary = "" 980 | # turn `Some(..)` into `Some(..)` 981 | if self.variant_name.startswith("Some"): 982 | self.variant_name = "Some" 983 | elif self.variant_name.startswith("None"): 984 | self.variant_name = "None" 985 | 986 | 987 | class ResultSynthProvider(GenericEnumSynthProvider): 988 | def update(self): 989 | super().update() 990 | self.typename_summary = "" 991 | # turn `Ok(..)` into `Ok(..)` 992 | if self.variant_name.startswith("Ok"): 993 | self.variant_name = "Ok" 994 | elif self.variant_name.startswith("Err"): 995 | self.variant_name = "Err" 996 | 997 | 998 | class CowSynthProvider(GenericEnumSynthProvider): 999 | def update(self): 1000 | super().update() 1001 | self.typename_summary = "" 1002 | # turn `Borrowed(..)` into `Borrowed(..)` 1003 | if self.variant_name.startswith("Borrowed"): 1004 | self.variant_name = "Borrowed" 1005 | elif self.variant_name.startswith("Owned"): 1006 | self.variant_name = "Owned" 1007 | 1008 | 1009 | class MsvcTupleSynthProvider(RustSynthProvider): 1010 | def update(self): 1011 | tparams = get_template_params(self.valobj.GetTypeName()) 1012 | self.type_name = '(' + ', '.join(tparams) + ')' 1013 | 1014 | def has_children(self): 1015 | return self.valobj.MightHaveChildren() 1016 | 1017 | def num_children(self): 1018 | return self.valobj.GetNumChildren() 1019 | 1020 | def get_child_at_index(self, index): 1021 | child = self.valobj.GetChildAtIndex(index) 1022 | return child.CreateChildAtOffset(str(index), 0, child.GetType()) 1023 | 1024 | def get_index_of_child(self, name): 1025 | return str(name) 1026 | 1027 | def get_summary(self): 1028 | return tuple_summary(self.valobj) 1029 | 1030 | def get_type_name(self): 1031 | return self.type_name 1032 | 1033 | 1034 | class MsvcEnumSynthProvider(EnumSynthProvider): 1035 | is_tuple_variant = False 1036 | 1037 | def update(self): 1038 | tparams = get_template_params(self.valobj.GetTypeName()) 1039 | if len(tparams) == 1: # Regular enum 1040 | discr = gcm(self.valobj, 'discriminant') 1041 | self.variant = gcm(self.valobj, 'variant' + 1042 | str(discr.GetValueAsUnsigned())) 1043 | variant_name = discr.GetValue() 1044 | else: # Niche enum 1045 | dataful_min = int(tparams[1]) 1046 | dataful_max = int(tparams[2]) 1047 | dataful_var = tparams[3] 1048 | discr = gcm(self.valobj, 'discriminant') 1049 | if dataful_min <= discr.GetValueAsUnsigned() <= dataful_max: 1050 | self.variant = gcm(self.valobj, 'dataful_variant') 1051 | variant_name = dataful_var 1052 | else: 1053 | variant_name = discr.GetValue() 1054 | 1055 | self.type_name = tparams[0] 1056 | 1057 | if self.variant.IsValid() and self.variant.GetNumChildren() > self.skip_first: 1058 | if self.variant.GetChildAtIndex(self.skip_first).GetName() == '__0': 1059 | self.is_tuple_variant = True 1060 | self.summary = variant_name + \ 1061 | tuple_summary(self.variant, skip_first=self.skip_first) 1062 | else: 1063 | self.summary = variant_name + '{...}' 1064 | else: 1065 | self.summary = variant_name 1066 | 1067 | def get_child_at_index(self, index): 1068 | child = self.variant.GetChildAtIndex(index + self.skip_first) 1069 | if self.is_tuple_variant: 1070 | return child.CreateChildAtOffset(str(index), 0, child.GetType()) 1071 | else: 1072 | return child 1073 | 1074 | def get_index_of_child(self, name): 1075 | if self.is_tuple_variant: 1076 | return int(name) 1077 | else: 1078 | return self.variant.GetIndexOfChildWithName(name) - self.skip_first 1079 | 1080 | def get_type_name(self): 1081 | return self.type_name 1082 | 1083 | 1084 | class MsvcEnum2SynthProvider(EnumSynthProvider): 1085 | is_tuple_variant = False 1086 | 1087 | def update(self): 1088 | tparams = get_template_params(self.valobj.GetTypeName()) 1089 | 1090 | if len(tparams) == 1: # Regular enum 1091 | discr = gcm(self.valobj, 'tag') 1092 | self.variant = gcm(self.valobj, 'variant' + 1093 | str(discr.GetValueAsUnsigned())).GetChildAtIndex(0) 1094 | else: # Niche enum 1095 | dataful_min = int(tparams[1]) 1096 | dataful_max = int(tparams[2]) 1097 | discr = gcm(self.valobj, 'tag') 1098 | if dataful_min <= discr.GetValueAsUnsigned() <= dataful_max: 1099 | self.variant = gcm(self.valobj, 'dataful_variant') 1100 | 1101 | names = re.split("::", self.variant.GetTypeName()) 1102 | variant_name = names[-1] 1103 | self.type_name = tparams[0] 1104 | 1105 | if self.variant.IsValid() and self.variant.GetNumChildren() > self.skip_first: 1106 | if self.variant.GetChildAtIndex(self.skip_first).GetName() == '__0': 1107 | self.is_tuple_variant = True 1108 | self.summary = variant_name + \ 1109 | tuple_summary(self.variant, skip_first=self.skip_first) 1110 | else: 1111 | self.summary = variant_name + " " + obj_summary(self.variant) 1112 | else: 1113 | self.summary = variant_name 1114 | 1115 | def get_summary(self): 1116 | return self.summary 1117 | 1118 | 1119 | class StdHashMapSynthProvider(RustSynthProvider): 1120 | def update(self): 1121 | self.initialize_table(gcm(self.valobj, 'base', 'table')) 1122 | 1123 | def initialize_table(self, table): 1124 | assert table.IsValid() 1125 | 1126 | if table.type.GetNumberOfTemplateArguments() > 0: 1127 | item_ty = table.type.GetTemplateArgumentType(0) 1128 | else: # we must be on windows-msvc - try to look up item type by name 1129 | table_ty_name = table.GetType().GetName() # "hashbrown::raw::RawTable" 1130 | item_ty_name = get_template_params(table_ty_name)[0] 1131 | item_ty = table.GetTarget().FindTypes(item_ty_name).GetTypeAtIndex(0) 1132 | 1133 | if item_ty.IsTypedefType(): 1134 | item_ty = item_ty.GetTypedefedType() 1135 | 1136 | inner_table = table.GetChildMemberWithName('table') 1137 | if inner_table.IsValid(): 1138 | self.initialize_hashbrown_v2( 1139 | inner_table, item_ty) # 1.52 <= std_version 1140 | else: 1141 | if not table.GetChildMemberWithName('data'): 1142 | self.initialize_hashbrown_v2( 1143 | table, item_ty) # ? <= std_version < 1.52 1144 | else: 1145 | self.initialize_hashbrown_v1( 1146 | table, item_ty) # 1.36 <= std_version < ? 1147 | 1148 | def initialize_hashbrown_v2(self, table, item_ty): 1149 | self.num_buckets = gcm(table, 'bucket_mask').GetValueAsUnsigned() + 1 1150 | ctrl_ptr = gcm(table, 'ctrl', 'pointer') 1151 | ctrl = ctrl_ptr.GetPointeeData(0, self.num_buckets) 1152 | # Buckets are located above `ctrl`, in reverse order. 1153 | start_addr = ctrl_ptr.GetValueAsUnsigned() - item_ty.GetByteSize() * \ 1154 | self.num_buckets 1155 | buckets_ty = item_ty.GetArrayType(self.num_buckets) 1156 | self.buckets = self.valobj.CreateValueFromAddress( 1157 | 'data', start_addr, buckets_ty) 1158 | error = lldb.SBError() 1159 | self.valid_indices = [] 1160 | for i in range(self.num_buckets): 1161 | if ctrl.GetUnsignedInt8(error, i) & 0x80 == 0: 1162 | self.valid_indices.append(self.num_buckets - 1 - i) 1163 | 1164 | def initialize_hashbrown_v1(self, table, item_ty): 1165 | self.num_buckets = gcm(table, 'bucket_mask').GetValueAsUnsigned() + 1 1166 | ctrl_ptr = gcm(table, 'ctrl', 'pointer') 1167 | ctrl = ctrl_ptr.GetPointeeData(0, self.num_buckets) 1168 | buckets_ty = item_ty.GetArrayType(self.num_buckets) 1169 | self.buckets = gcm( 1170 | table, 'data', 'pointer').Dereference().Cast(buckets_ty) 1171 | error = lldb.SBError() 1172 | self.valid_indices = [] 1173 | for i in range(self.num_buckets): 1174 | if ctrl.GetUnsignedInt8(error, i) & 0x80 == 0: 1175 | self.valid_indices.append(i) 1176 | 1177 | def has_children(self): 1178 | return True 1179 | 1180 | def num_children(self): 1181 | return len(self.valid_indices) 1182 | 1183 | def get_child_at_index(self, index): 1184 | bucket_idx = self.valid_indices[index] 1185 | item = self.buckets.GetChildAtIndex(bucket_idx) 1186 | item.SetPreferSyntheticValue(True) 1187 | v = item.CreateChildAtOffset('[%d]' % index, 0, item.GetType()) 1188 | v.SetPreferSyntheticValue(True) 1189 | return v 1190 | 1191 | def get_index_of_child(self, name): 1192 | return int(name.lstrip('[').rstrip(']')) 1193 | 1194 | def get_summary(self): 1195 | return 'size=%d, capacity=%d' % (self.num_children(), self.num_buckets) 1196 | 1197 | 1198 | class StdHashSetSynthProvider(StdHashMapSynthProvider): 1199 | def update(self): 1200 | table = gcm(self.valobj, 'base', 'map', 'table') # std_version >= 1.48 1201 | if not table.IsValid(): 1202 | table = gcm(self.valobj, 'map', 'base', 1203 | 'table') # std_version < 1.48 1204 | self.initialize_table(table) 1205 | 1206 | def get_child_at_index(self, index): 1207 | bucket_idx = self.valid_indices[index] 1208 | item = self.buckets.GetChildAtIndex(bucket_idx).GetChildAtIndex(0) 1209 | return item.CreateChildAtOffset('[%d]' % index, 0, item.GetType()) 1210 | 1211 | class CrossbeamAtomicCellSynthProvider(DerefSynthProvider): 1212 | def update(self): 1213 | self.deref = gcm(self.valobj, 'value', 'value', 'value', 'value') 1214 | self.deref.SetPreferSyntheticValue(True) 1215 | 1216 | 1217 | def __lldb_init_module(debugger_obj, internal_dict): # pyright: ignore 1218 | initialize_category(debugger_obj, internal_dict) 1219 | print(f"loaded rust-prettifier-for-lldb from {__file__}") 1220 | --------------------------------------------------------------------------------