vico
vico

Reputation: 18175

Debugging several steps in one line using GDB

Trying to debug line that has line number 28 using GDB.

printf("file type: %s\n", filetype[(sb.st_mode >> 12) & 017]);

I do:

break 28
p sb.st_mode

Output:

$1 = 33270

If I press n code will go to next line. But I need result of sb.st_mode >> 12. And then the result of (sb.st_mode >> 12) & 017. How to achieve this?

What does $1 means?

Upvotes: 0

Views: 496

Answers (1)

Andrew
Andrew

Reputation: 4751

You can enter more complex expressions at the gdb prompt, and the expression will be evaluated, if the language is C then this should be no problem. So:

(gdb) p (sb.st_mode >> 12) & 017
(gdb) p filetype[(sb.st_mode >> 12) & 017]

In languages like C++ where you have operator overloading then some of the above might not work, as the code for the operator function might not be available. gdb will let you know when you hit such cases, so initially, don't worry about them.

When gdb prints a result it also assigns the result to a convenience variable for you, so you can easily access the result again, so:

(gdb) p $1

Will reprint the result that was assigned to $1. In your case this might not seem very useful as you can easily re-evaluate your expression, but in some cases the result can't be re-evaluated. For example, the finish command causes gdb to finish the current function. The result returned by that function is printed, and assigned to a convenience variable. Obviously you can't (easily) re-finish a function a second time, but if you want to re-print the result you can thanks to the convenience variable.

There's also a special convenience variable $ which is always the last result that gdb printed.

You can also make use of convenience variables inside expressions, like this:

(gdb) p sb.st_mode
$1 = 33270
(gdb) p/x $1
$2 = 0x81f6
(gdb) p $1 >> 12
$3 = 8
(gdb) p $3 & 0x17
$4 = 0

Upvotes: 1

Related Questions