代码调试篇(2):如何编写 gdb 自定义命令
Author: stormQ
Created: Monday, 25. February 2019 10:31PM
Last Modified: Monday, 26. October 2020 11:31PM
本文描述了如何编写自定义的 gdb 命令,从而提高调试效率。
定义 gdb 命令
的语法格式:
# 自定义一个 gdb 命令
define <command-name>
<body>
end
和
# 为已定义的 gdb 命令(gdb 预定义的或用户自定义的)定义一个子命令
define <defined-command-name> <sub-command-name>
<body>
end
示例:
define ptitle
echo hello, world\n
end
上述示例,定义了一个输出常量字符串hello, world
并换行的命令ptitle
。
调试:
$ gdb -q ./main
Reading symbols from ./main...done.
(gdb) define ptitle
Type commands for definition of "ptitle".
End with a line saying just "end".
>echo hello, world\n
>end
(gdb) ptitle
hello, world
(gdb)
查看所有的自定义 gdb 命令:
(gdb) show user
User command "ptitle":
echo hello, world\n
User command "ptitle1":
echo a\n
查看指定的自定义 gdb 命令:
(gdb) show user ptitle1
User command "ptitle1":
echo a\n
打印自定义 gdb 命令的实参个数,在其函数体中:
echo $argc
打印自定义 gdb 命令的参数,在其函数体中:
# 打印第 1 个参数(从左到右)
echo $arg0
# 打印第 2 个参数(从左到右)
echo $arg1
# 打印第 n 个参数(从左到右)
echo $arg<n-1>
示例:
define log_info
echo argc = $argc\n
echo 1th arg: = $arg0\n
echo 2th arg: = $arg1\n
end
调试:
$ gdb -q ./main
Reading symbols from ./main...done.
(gdb) define log_info
Type commands for definition of "log_info".
End with a line saying just "end".
>echo argc = $argc\n
>echo 1th arg: = $arg0\n
>echo 2th arg: = $arg1\n
>end
(gdb) log_info hello world
argc = 2
1th arg: = hello
2th arg: = world
(gdb)
示例:
define log_info
if $argc == 2
echo 1th arg: = $arg0\n
echo 2th arg: = $arg1\n
else
echo args error\n
end
end
调试:
$ gdb -q ./main
Reading symbols from ./main...done.
(gdb) define log_info
Type commands for definition of "log_info".
End with a line saying just "end".
>if $argc == 2
>echo 1th arg: = $arg0\n
>echo 2th arg: = $arg1\n
>else
>echo args error\n
>end
>end
(gdb) log_info 1
args error
(gdb) log_info 1 2 3
args error
(gdb) log_info 1 2
1th arg: = 1
2th arg: = 2
(gdb)
示例:
define log_info
if $argc < 1
echo args error\n
return
end
set $i = 0
while $i < $argc
printf "%dth arg\n", $i
set $i = $i + 1
end
end
调试:
$ gdb -q ./main
Reading symbols from ./main...done.
(gdb) define log_info
Type commands for definition of "log_info".
End with a line saying just "end".
>if $argc < 1
>echo args error\n
>return
>end
>set $i = 0
>while $i < $argc
>printf "%dth arg\n", $i
>set $i = $i + 1
>end
>end
(gdb) log_info
args error
No selected frame.
(gdb) log_info a b c d
0th arg
1th arg
2th arg
3th arg
(gdb)
示例:
(gdb) source cmd.gdb
注:cmd.gdb
为存放自定义 gdb 命令的文件路径
调试:
$ gdb -q ./main
Reading symbols from ./main...done.
(gdb) source cmd.gdb
(gdb) show user
User command "log_info":
if $argc < 1
echo args error\n
return
end
set $i = 0
while $i < $argc
printf "%dth arg\n", $i
set $i = $i + 1
end
(gdb)