Use GDB, how to manipulate memory or variable?

I wish to modify the raw buffer through pointer while debug, or run an expression, but failed to make it.

Bellow is my operation, any wrong have I done?

(gdb) b 6
Breakpoint 1 at 0x8bfa: file src/main.rs, line 6.
(gdb) r
Starting program: /.../modify_vec/target/debug/modify_vec
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Pointer to the buffer: 0x5555555a7ba0

Breakpoint 1, modify_vec::main () at src/main.rs:6
6	    println!("Pointer to the buffer: {:?}", v_ptr);
(gdb) list
1
2	fn main() {
3	    let mut v = vec![1, 2, 3, 4, 5];
4	    let v_ptr = v.as_ptr();
5	    println!("Pointer to the buffer: {:p}", v_ptr);
6	    println!("Pointer to the buffer: {:?}", v_ptr);
7	    println!("v: {:?} ", v);
8
9	}
10
(gdb) p v_ptr
$1 = (*mut i32) 0x5555555a7ba0
(gdb) p v
$2 = Vec(size=5) = {1, 2, 3, 4, 5}
(gdb) x/8hw 0x5555555a7ba0
0x5555555a7ba0:	1	2	3	4
0x5555555a7bb0:	5	0	132177	0
(gdb) p *0x5555555a7ba0
Attempt to take contents of a non-pointer value.
>>> 
>>> 
>>> set *0x5555555a7ba0 = 9
Attempt to take contents of a non-pointer value.
>>> v.push(9)
Undefined command: "v.push".  Try "help".
>>> call v.push(9)
Could not find function named 'alloc::vec::Vec<i32, alloc::alloc::Global>::push'
>>> p v.push(9)
Could not find function named 'alloc::vec::Vec<i32, alloc::alloc::Global>::push'
>>> p v.len()
Could not find function named 'alloc::vec::Vec<i32, alloc::alloc::Global>::len'
>>> p v
$2 = Vec(size=5) = {[0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 5}
>>>

(gdb) set *v_ptr = 9
(gdb) set *(v_ptr + 2) = 9
(gdb) x /10dw v_ptr
0x55555a7ad0:   9       2       9       4
0x55555a7ae0:   5       0       132385  0
0x55555a7af0:   0       0
(gdb) 

A little tip if you are not aware:

(gdb) layout src

To go into TUI mode and see your source code live :).

2 Likes

Thanks, it work!
It is boring to switch among all kind of layout, and there is a awesome TUI that I currently use:
GitHub - cyrus-and/gdb-dashboard: Modular visual interface for GDB in Python
It provide a .gdbinit configure file, just copy it to ~/.gdbinit to setup. Then start gdb, once gdb stop at breakpoint, the TUI will show up.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.