0%

Reverse debugging for gdb

在gdb 7.0之後加入的Reverse debugging,終於有時間可以玩玩看了。
同樣的,來個程式範例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

void foo() {
printf("inside foo()");
int x = 6;
x += 2;
}

int main() {
int x = 0;
x = x + 2;
foo();
printf("x = %d\n", x);
x = 4;
return 0;
}

編譯它

1
gdb -g -o test test.c

使用gdb來玩玩看,最簡單的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ gdb test
(gdb) start
Temporary breakpoint 1, main () at test.c:10
10 int x = 0;
(gdb) record
(gdb) next
11 x = x + 2;
(gdb) disp x
1: x = 0
(gdb) next
12 foo();
1: x = 2
(gdb) reverse-next
11 x = x + 2;
1: x = 0

在使用之前,要先用record記錄操作順序,才有機會還原狀態。不用的時候可以使用record stop停止。
接著常用的step, next, stepi跟nexti都有逆向版。可以參考GDB and Reverse Debugging

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(gdb) b 15
Breakpoint 2 at 0x400578: file test.c, line 15.
(gdb) continue
Continuing.
inside foo()x = 2

Breakpoint 2, main () at test.c:15
15 return 0;
(gdb) b foo
Breakpoint 3 at 0x400524: file test.c, line 4.
(gdb) reverse-continue
Continuing.

Breakpoint 3, foo () at test.c:4
4 printf("inside foo()");

想要追蹤之前執行過的中斷點該怎麼辦? 使用reverse-continue
也可以用watchpointer來追蹤到底如何被修改的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(gdb) set can-use-hw-watchpoints 0
(gdb) watch x
Watchpoint 3: x
(gdb) continue
Continuing.
Watchpoint 3: x

Old value = 0
New value = 2
(gdb) reverse-continue
Continuing.
Watchpoint 3: x

Old value = 2
New value = 0
main () at test.c:11
11 x = x + 2;

更多的gdb使用教學,可以參考