gdb-打印宏名称而不是值

时间:2019-04-02 08:03:21

标签: c gdb

是否可以在gdb中展开宏?

我已经使用-g3编译了二进制文件,并且可以看到宏定义:

(gdb) info macro  NGX_CORE_MODULE
Defined at /path/src/core/ngx_conf_file.h:70
  included at /path/src/core/ngx_core.h:86
  included at /path/src/core/ngx_cycle.c:9
#define NGX_CORE_MODULE 0x45524F43
(gdb) 

但是当我看到变量时,我看到的是数值而不是宏名

(gdb) p/x cycle->modules[0]->type
$17 = 0x45524f43
(gdb) 

是否有可能得到这样的东西:

(gdb) p cycle->modules[0]->type
$17 = NGX_CORE_MODULE
(gdb) 

我尝试过这样的用户定义函数:

define expand_module_type_macro
if $arg0 == 0x45524F43
   print "NGX_CORE_MODULE"
else 
if $arg0 == 0x464E4F43
   print "NGX_CONF_MODULE"
else
   print $arg0
end
end
end

它有效

(gdb) expand_module_type_macro cycle->modules[0]->type
$18 = "NGX_CORE_MODULE"
(gdb) 

但是它没有实际用途,因为我不能在复杂的输出中使用它:

(gdb) printf "module type=%s\n", expand_module_type_macro cycle->modules[0]->type
No symbol "expand_module_type_macro" in current context.
(gdb) set $m = expand_module_type_macro cycle->modules[0]->type
No symbol "expand_module_type_macro" in current context.
(gdb) 

1 个答案:

答案 0 :(得分:0)

You might get something useful by creating a convenience function in python. I tested using this C program:

int var1 = 1234;
int var2 = 4567;

int
main ()
{
  return 0;
}

And using this python script:

class ExpandMacro (gdb.Function):
    """Expand a value to a string, replacing with
    macro name where possible."""

    def __init__ (self):
        super (ExpandMacro, self).__init__ ("expand")

    def invoke (self, value):
        if (value == 1234):
            return "MY_MACRO"
        else:
            return str (value)

ExpandMacro ()

Then my GDB session:

(gdb) start
# .... snip ....
7     return 0;
(gdb) source lookup.py 
(gdb) p $expand (var1)
$1 = "MY_MACRO"
(gdb) p $expand (var2)
$2 = "4567"
(gdb) printf "var1=%s\n", $expand (var1)
var1=MY_MACRO
(gdb) printf "var2=%s\n", $expand (var2)
var2=4567

In order to use the returned value with a %s format inside printf, I always return a string.