代码调试篇(2):如何编写 gdb 自定义命令
Author:stormQ
Monday, 25. February 2019 10:31PM
目录
定义 gdb 命令
的语法格式:
# 自定义一个 gdb 命令
define
end
和
# 为已定义的 gdb 命令(gdb 预定义的或用户自定义的)定义一个子命令
define
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
示例:
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)
返回上一级
如果你觉得本文对你有所帮助,欢迎关注公众号,支持一下!