如何检查GDB中函数的返回值?


Answers:


119

我想有更好的方法可以执行此操作,但是finish命令会执行到弹出当前堆栈帧并打印返回值为止-给定程序

int fun() {
    return 42;
}

int main( int argc, char *v[] ) {
    fun();
    return 0;
}

您可以这样调试它-

(gdb) r
Starting program: /usr/home/hark/a.out 

Breakpoint 1, fun () at test.c:2
2               return 42;
(gdb) finish
Run till exit from #0  fun () at test.c:2
main () at test.c:7
7               return 0;
Value returned is $1 = 42
(gdb) 

finish命令可以缩写为fin。不要使用f,这是framecommand的缩写!


3
好答案,伙计。我使用的是“返回”,实际上实际上是从框架中强制返回(显然没有返回值),
无法解决

可能会出现愚蠢的问题,如果函数没有返回值怎么办?
Roon13

45

是的,只需EAX输入即可检查寄存器print $eax。对于大多数函数,即使不使用返回值,它也会存储在该寄存器中。

例外情况是返回大于32位的类型的函数,特别是返回64位整数(long long),doubles和structsor的函数classes

另一个例外是,如果您未在Intel架构上运行。在这种情况下,您必须弄清楚使用哪个寄存器(如果有)。


8
不使用在sparc上运行的intel机器。g0是存储返回值的位置,但是我想要独立于体系结构的东西
。– fuad

1
感谢您的澄清;我以为您正在使用x86。但是除非您打算跨多个体系结构编写GDB脚本,否则我看不出不使用“ print $ g0”的充分理由,因为它没有任何副作用(与其他答案不同)。
亚当·罗森菲尔德

当然。抱歉,它是o0,而不是g0。寄存器g0始终为
0。– fuad

8

这是没有符号的操作方法。

gdb ls
This GDB was configured as "ppc64-yellowdog-linux-gnu"...
(no debugging symbols found)
Using host libthread_db library "/lib64/libthread_db.so.1".

(gdb) break __libc_start_main
Breakpoint 1 at 0x10013cb0
(gdb) r
Starting program: /bin/ls
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
Breakpoint 1 at 0xfdfed3c
(no debugging symbols found)
[Thread debugging using libthread_db enabled]
[New Thread 4160418656 (LWP 10650)]
(no debugging symbols found)
(no debugging symbols found)
[Switching to Thread 4160418656 (LWP 10650)]

Breakpoint 1, 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6
(gdb) info frame
Stack level 0, frame at 0xffd719a0:
 pc = 0xfdfed3c in __libc_start_main; saved pc 0x0
 called by frame at 0x0
 Arglist at 0xffd71970, args:
 Locals at 0xffd71970, Previous frame's sp is 0xffd719a0
 Saved registers:
  r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,
  r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,
  pc at 0xffd719a4, lr at 0xffd719a4
(gdb) frame 0
#0  0x0fdfed3c in __libc_start_main () from /lib/libc.so.6
(gdb) info fr
Stack level 0, frame at 0xffd719a0:
 pc = 0xfdfed3c in __libc_start_main; saved pc 0x0
 called by frame at 0x0
 Arglist at 0xffd71970, args:
 Locals at 0xffd71970, Previous frame's sp is 0xffd719a0
 Saved registers:
  r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,
  r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,
  pc at 0xffd719a4, lr at 0xffd719a4

格式化有点混乱,请注意使用“信息框架”检查框架,并使用“框架#”将上下文导航到另一个上下文(在堆栈上下)

bt还显示了一个简短的堆栈以提供帮助。


我在那里看不到任何返回值信息。
Trass3r
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.