Code Debugging with GDB - part 2: Custom Commands

Abstract

This article describes custom commands in GDB and how to write it.

Customize a gdb command

Syntax

1
2
3
define <command-name>
<body>
end
1
2
3
define <defined-command-name><sub-command-name>
<body>
end

Debug

1
2
3
4
5
6
7
8
9
10
11
ethanol@ethanol:~/Desktop/pic$ gdb -q ./main_mix
GEF for linux ready, type `gef' to start, `gef config' to configure
96 commands loaded for GDB 9.2 using Python engine 3.8
Reading symbols from ./main_mix...
gef➤ define hello
Type commands for definition of "hello".
End with a line saying just "end".
>echo hello, world\n
>end
gef➤ hello
hello, world

View custom gdb command

1
2
3
4
5
6
7
gef➤  show user
User command "hello":
echo hello, world\n

gef➤ show user hello
User command "hello":
echo hello, world\n

Get parameters

1
2
3
echo $arg0
echo $arg1
echo $arg<n-1>
1
2
3
4
5
6
7
8
9
10
11
gef➤  define log_info
Type commands for definition of "log_info".
End with a line saying just "end".
>echo argc=$argc\n
>echo arg1=$arg0\n
>echo arg2=$arg1\n
>end
gef➤ log_info hello world
argc=2
arg1=hello
arg2=world

Use conditional branching

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
gef➤  define log_info
Type commands for definition of "log_info".
End with a line saying just "end".
>if $argc==2
>echo argc=$argc\n
>echo arg1=$arg0\n
>echo arg2=$arg1\n
>else
>echo args error\n
>end
>end
gef➤ log_info hello world
argc=2
arg1=hello
arg2=world

Use loop

1
2
3
4
5
6
7
8
9
10
11
12
define log_info
if $argc < 1
echo args error\n
return
end

set $i = 0
while $1 < argc
printf "%dth arg\n", $i
set $i = $i + 1
end
end

Execute custom gdb commands in files

In gdb:

1
2
source cmd.gdb
show user