Now Reading
Beej’s Fast Information to GDB

Beej’s Fast Information to GDB

2023-11-05 14:53:58


Beej’s Fast Information to GDB

Launch 2 (2009 Jun 14)

Translations:

This can be a very quick-and-dirty information meant to get you began with
the GNU Debugger, gdb, from the command line in a
terminal. Usually occasions gdb is run through an IDE, however
many individuals on the market shun IDEs for a wide range of causes, and this
tutorial is for you!

Once more, that is solely a getting-started information. There’s a lot a lot MUCH
extra to study what the debugger does than is written in these few
brief paragraphs. Take a look at your “man” pages or the web sources
listed under for more information.

This tutorial is supposed to be learn so as, as much as, however not together with,
the “Misc” part.

Contents


Compiling

It’s a must to inform your compiler to compile your code with symbolic
debugging info included. This is the best way to do it with gcc, with the -g change:


$ gcc -g hiya.c -o hiya

$ g++ -g hiya.cpp -o hiya

As soon as you have achieved that, it’s best to have the ability to view program listings in
the debugger.


Extra Info

Take a look at the Official GDB
Documentation
for extra info than you may shake a stick
at!

Additionally, an excellent GNU GDB front-end is DDD, the
DataDisplayDebugger
.


License

Creative Commons License

Beej’s Fast Information to GDB by Brian “Beej Jorgensen” Hall is licensed underneath a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.


Beginning The Debugger

First issues first: you may enter assist at
any gdb immediate and get extra info. Additionally,
you may enter give up to give up the debugger.
Lastly, simply hitting RETURN will repeat the
final command entered. Now let’s hearth it up!

There are a number of methods to start out the debugger (e.g. in the event you had been an IDE
you would possibly begin it with a selected mode that is not so human-friendly)
however I am going to point out two of them right here: vanilla console mode and curses GUI
mode. The GUI is best, however let’s shortly cowl the easy one, and
launch a program referred to as hiya within the debugger:

$ gdb hiya
GNU gdb 6.8
Copyright (C) 2008 Free Software program Basis, Inc.
License GPLv3+: GNU GPL model 3 or later <http://gnu.org/licenses/gpl.html>
That is free software program: you might be free to alter and redistribute it.
There may be NO WARRANTY, to the extent permitted by legislation.  Kind "present copying"
and "present guarantee" for particulars.
This GDB was configured as "i486-slackware-linux"...
(gdb) run
Beginning program: /residence/beej/hiya 
Hi there, world!

Program exited usually.
(gdb) 

The final line is the gdb immediate, ready for
you to inform it what to do. Kind r or run to run this system. (gdb permits you to abbreviate instructions till they
develop into ambiguous.)

To start out in neato and highly-recommended GUI mode, begin the
debugger with gdb -tui. (For lots of the
examples, under, I present the output of gdb‘s dumb
terminal mode, however in actual life I take advantage of TUI mode completely.)

And here’s a screenshot of what you may see, roughly:

All the traditional gdb instructions will work in GUI
mode, and moreover the arrow keys and pgup/pgdown keys will scroll
the supply window (when it has focus, which it does by default). Additionally,
you may change which file or perform is displayed within the supply window
by giving the command record with a location as
an argument, for instance, “record hiya.c:5 to
deliver up the file hiya.c on line 5. (See “Breakpoints“, under, for pattern
areas—the identical areas that work with breakpoints will work
with the record command.) As a facet be aware, record additionally works in dumb terminal mode.

Now, discover that we handed the identify of the executable on the command
line. An alternative choice you could have is to simply begin gdb with nothing else on the command line, then give
it the command file hiya, and that can trigger
the executable “hiya” to be loaded up.

Command line arguments! What if you must get one thing into argv in your program? Cross them as arguments to
the run command if you begin execution:

$ gdb hiya
GNU gdb 6.8
Copyright (C) 2008 Free Software program Basis, Inc.
License GPLv3+: GNU GPL model 3 or later <http://gnu.org/licenses/gpl.html>
That is free software program: you might be free to alter and redistribute it.
There may be NO WARRANTY, to the extent permitted by legislation.  Kind "present copying"
and "present guarantee" for particulars.
This GDB was configured as "i486-slackware-linux"...
(gdb) run arg1 arg2
Beginning program: /residence/beej/hiya arg1 arg2
Hi there, world!

Program exited usually.
(gdb) 

Discover the place it says “Beginning Program”, above, it exhibits the
arguments “arg1” and “arg2” being handed to “hiya”.


Breakpoints

Simply beginning the debugger to run this system straight via is not
very helpful—we have to cease execution and get into stepping
mode.

First, earlier than you difficulty the run command, you
must set a breakpoint someplace you’d wish to cease. You employ the break or b command, and
specify a location, which is usually a perform identify, a line quantity, or a
supply file and line quantity. These are examples of areas, that are
utilized by numerous different instructions in addition to break:

break fundamental Break initially of the fundamental() perform
break 5 Break at line 5 of the present file
break hiya.c:5 Break at line 5 of hiya.c

So for this check, let’s set a breakpoint at fundamental(), and begin this system:

$ gdb hiya
GNU gdb 6.8
Copyright (C) 2008 Free Software program Basis, Inc.
License GPLv3+: GNU GPL model 3 or later <http://gnu.org/licenses/gpl.html>
That is free software program: you might be free to alter and redistribute it.
There may be NO WARRANTY, to the extent permitted by legislation.  Kind "present copying"
and "present guarantee" for particulars.
This GDB was configured as "i486-slackware-linux"...
(gdb) b fundamental
Breakpoint 1 at 0x8048395: file hiya.c, line 5.
(gdb) r
Beginning program: /residence/beej/hiya 

Breakpoint 1, fundamental () at hiya.c:5
5		printf("Hi there, world!n");
(gdb)

As you see, we have arrived at fundamental() and
execution has stopped on the breakpoint we set there. If you happen to’re operating
in dumb terminal mode, gdb will print the road it
will execute subsequent. If you happen to’re operating in cool GUI mode, the road it’ll
execute subsequent will likely be highlighted within the supply window.

To record the present breakpoints, use the data command, like so: “data
breakpoints
” (or the shorter “i b“):

(gdb) b fundamental
Breakpoint 1 at 0x8048395: file hiya.c, line 5.
(gdb) i b
Num     Kind           Disp Enb Deal with    What
1       breakpoint     maintain y   0x08048395 in fundamental at hiya.c:5

To clear a breakpoint, use the clear command
with the breakpoint location. You may also clear a breakpoint by quantity
with the delete command.

Moreover, you may allow or disable breakpoints, although these two instructions
take a breakpoint quantity as an argument, not a location! The
enabled/disabled standing of a breakpoint is seen underneath the “Enb”
column within the breakpoint itemizing.

(gdb) i b
Num     Kind           Disp Enb Deal with    What
1       breakpoint     maintain y   0x08048395 in fundamental at hiya.c:5
(gdb) disable 1
(gdb) i b
Num     Kind           Disp Enb Deal with    What
1       breakpoint     maintain n   0x08048395 in fundamental at hiya.c:5
(gdb) clear fundamental
Deleted breakpoint 1 
(gdb) i b
No breakpoints or watchpoints.


Stepping Round

As soon as execution stops at a breakpoint, you may inform the debugger to do
a couple of issues. Let’s begin with the subsequent
command (or n). This command strikes you to the
subsequent assertion within the present perform (or returns to the perform’s
caller in the event you’ve stepped off the tip of the perform.) This is a pattern
run; keep in mind that gdb is printing the road it
will execute subsequent
simply earlier than the “(gdb)” immediate. Additionally discover that
after we run subsequent on the printf() line, we see the output seem.

(gdb) b fundamental
Breakpoint 1 at 0x8048395: file hiya.c, line 5.
(gdb) r
Beginning program: /residence/beej/hiya 

Breakpoint 1, fundamental () at hiya.c:5
5		printf("Hi there, world!n");
(gdb) subsequent
Hi there, world!
7		return 0;
(gdb) subsequent
8	}
(gdb) subsequent
0xb7d6c6a5 in __libc_start_main () from /lib/libc.so.6
(gdb) subsequent
Single stepping till exit from perform __libc_start_main, 
which has no line quantity info.

Program exited usually.
(gdb) 

(That bizarre stuff on the finish about
__libc_start_main()
exhibits you that there was one other perform that
referred to as your fundamental() perform! It wasn’t
compiled with debugging info so we won’t see the supply, however we
can nonetheless step via it—which we do—and this system exits
usually.)

Now, discover that subsequent steps over
perform calls. This doesn’t suggest that perform would not get referred to as; it
signifies that subsequent will execute the perform till
it is achieved, after which return you to the subsequent line in your present
perform.

What when you have a perform you wish to step into out of your
present perform, and hint via that perform line-by-line? Use the
step (or s) command to
do that. It really works similar to subsequent, besides it
steps into features.

As an example you are bored with single stepping, and simply need this system
to run once more. Use the proceed (or c) command to proceed execution.

What if this system is operating however you forgot to set breakpoints?
You may hit CTRL-C and that’ll cease this system
wherever it occurs to be and return you to a “(gdb)” immediate. At that
level, you possibly can arrange a correct breakpoint someplace and proceed to that breakpoint.

One last shortcut is that simply hitting RETURN will repeat the final command entered; this
will prevent typing subsequent again and again
once more.


Analyzing Variables

In case you have some variables you want to examine over the course of the
run, you may show them, however provided that the
variable is at the moment in scope. Every time you step the code, the worth
of the variable will likely be displayed (if it is in scope).

(The next output is lacking supply code output between traces for
readability—it is what you’d see in GUI mode. Think about you are seeing
the spotlight bar bouncing across the supply code whilst you’re operating
this:)

(gdb) b fundamental
Breakpoint 1 at 0x8048365: file hiya.c, line 5.
(gdb) r
Beginning program: /residence/beej/hiya 

Breakpoint 1, fundamental () at hiya.c:5
(gdb) disp i
1: i = -1207447872
(gdb) subsequent
1: i = 1
(gdb) subsequent
1: i = 1
(gdb) subsequent
1: i = 2
(gdb) subsequent
1: i = 2
(gdb) subsequent
1: i = 4
(gdb) subsequent
1: i = 4
(gdb) subsequent
1: i = 4
(gdb) 

The quantity to the left of “i”, above, is the show variety of the
variable. Use this quantity to undisplay the
variable. If you happen to overlook the show numbers, you may sort data show to get them:

(gdb) b fundamental
Breakpoint 1 at 0x8048365: file hiya.c, line 5.
(gdb) r
Beginning program: /residence/beej/hiya 

Breakpoint 1, fundamental () at hiya.c:5
(gdb) show i
1: i = -1207447872
(gdb) data show
Auto-display expressions now in impact:
Num Enb Expression
1:   y  i
(gdb) undisplay 1
(gdb)

If you happen to simply wish to one-off know the worth of a variable, you may print it. Right here we see the worth of “i” is 40:

(gdb) print i
$1 = 40
(gdb)

(The “$” with the quantity after it means one thing, but it surely’s not
vital for freshmen.)

There’s additionally a useful printf command that you simply
can use to higher format your output if you wish to:

(gdb) printf "%dn", i
40
(gdb) printf "%08Xn", i
00000028
(gdb)


Misc Stuff

That is stuff that does not actually match within the earlier sections, but it surely
enjoyable sufficient to record someplace.


Stack Manipulation

The command backtrace (or bt) will present you the present perform name
stack, with the present perform on the high, and the callers so as
beneath it:

(gdb) backtrace
#0  subsubfunction () at hiya.c:5
#1  0x080483a7 in subfunction () at hiya.c:10
#2  0x080483cf in fundamental () at hiya.c:16
(gdb)

Kind assist stack for more information on what you
can do with this.


Extra Stepping Strategies

To exit the present perform and return to the calling perform, use
the end command.

To step for a single meeting instruction, use the stepi command.

To proceed to a selected location, use the advance command, specifying a location like these
proven within the “Breakpoints” part, above.
This is an instance which advances from the present location till the
perform subsubfunction() is known as:

Breakpoint 1, fundamental () at hiya.c:15
15		printf("Hi there, world!n");
(gdb) advance subsubfunction
Hi there, world!
subsubfunction () at hiya.c:5
5		printf("Deepest!n");
(gdb) 

advance is simply shorthand for “proceed to
this momentary breakpoint.”


Leaping to an Arbitrary Part of Code

The bounce command works precisely like proceed, besides it takes a location to leap to as
an argument. (See the the “Breakpoints
part, above, for extra info on areas.)

If it’s essential to cease on the bounce vacation spot, set a breakpoint there
first.


Altering Variables and Values at Runtime

You should use the set variable command with an
expression to judge, and this lets you change the worth of a
variable throughout the run. You may also shorthand this by simply utilizing set with a parenthesized expression after it:

Breakpoint 1, fundamental () at hiya.c:15
15		int i = 10;
(gdb) print i
$1 = -1208234304
(gdb) set (i = 20)
(gdb) print i
$2 = 20
(gdb) set variable i = 40
(gdb) print i
$3 = 40
(gdb) 

This, together with the bounce command, might help
you repeat sections of code with out restarting this system.


{Hardware} Watchpoints

{Hardware} watchpoints are particular breakpoints that can set off
at any time when an expression modifications. Usually you simply wish to know when a
variable modifications (is written to), and for that you need to use the watch command:

Breakpoint 1, fundamental () at hiya.c:5
5		int i = 1;
(gdb) watch i
{Hardware} watchpoint 2: i
(gdb) proceed
Persevering with.
{Hardware} watchpoint 2: i

Previous worth = -1208361280
New worth = 2
fundamental () at hiya.c:7
7		whereas (i < 100) {
(gdb) proceed
Persevering with.
{Hardware} watchpoint 2: i

Previous worth = 2
New worth = 3
fundamental () at hiya.c:7
7		whereas (i < 100) {
(gdb)

Be aware that watch takes an expression as an
argument, so you may put a variable identify in there, or one thing extra
complicated like *(p+5) or a[15]. I’ve even tried it with conditional
expressions like i > 10, however have had
blended outcomes.

You will get an inventory of watch factors with data
break
or data watch, and you may delete
them by quantity with the delete command.

Lastly, you need to use rwatch to detect when a
variable is learn, and you need to use awatch to
detect when a variable is both learn or written.


Connect to a Working Course of

In case your program is already going and also you wish to cease it and debug,
first you may want the method ID (PID), which will likely be a quantity. (Get it
from Unix’s ps command.) Then you definitely’ll use the connect command with the PID to connect to (and
break) the operating program.

For this, you may simply begin gdb with no
arguments.

Within the following full run, you may discover a couple of issues. First I
connect to the operating course of, and it tells me it is in some perform
deep down referred to as __nanosleep_nocancel(), which
is not too shocking since I referred to as sleep() in
my code. Certainly, asking for a backtrace exhibits
precisely this name stack. So I say end a
couple occasions to get again as much as fundamental().

$ gdb
GNU gdb 6.8
Copyright (C) 2008 Free Software program Basis, Inc.
License GPLv3+: GNU GPL model 3 or later <http://gnu.org/licenses/gpl.html>
That is free software program: you might be free to alter and redistribute it.
There may be NO WARRANTY, to the extent permitted by legislation.  Kind "present copying"
and "present guarantee" for particulars.
This GDB was configured as "i486-slackware-linux".
(gdb) connect 3490
Attaching to course of 3490
Studying symbols from /residence/beej/hiya...achieved.
Studying symbols from /lib/libsafe.so.2...achieved.
Loaded symbols for /lib/libsafe.so.2
Studying symbols from /lib/libc.so.6...achieved.
Loaded symbols for /lib/libc.so.6
Studying symbols from /lib/libdl.so.2...achieved.
Loaded symbols for /lib/libdl.so.2
Studying symbols from /lib/ld-linux.so.2...achieved.
Loaded symbols for /lib/ld-linux.so.2
0xb7eab21b in __nanosleep_nocancel () from /lib/libc.so.6
(gdb) backtrace 
#0  0xb7eab21b in __nanosleep_nocancel () from /lib/libc.so.6
#1  0xb7eab05f in sleep () from /lib/libc.so.6
#2  0x080483ab in fundamental () at hiya.c:10
(gdb) end
Run until exit from #0  0xb7eab21b in __nanosleep_nocancel ()
   from /lib/libc.so.6
0xb7eab05f in sleep () from /lib/libc.so.6
(gdb) end
Run until exit from #0  0xb7eab05f in sleep () from /lib/libc.so.6
0x080483ab in fundamental () at hiya.c:10
10			sleep(1);
(gdb) record
5	{
6		int i = 1;
7	
8		whereas (i < 60) {
9			i++;
10			sleep(1);
11		}
12	
13		return 0;
14	}
(gdb) print i
$1 = 19
(gdb) give up
This system is operating.  Stop anyway (and detach it)? (y or n) y
Detaching from program: /residence/beej/hiya, course of 3490

Discover that after I get again to fundamental(), I
print the worth of i and it is 19—as a result of on this case the
program has been operating for 19 seconds, and i will get incremented
as soon as per second.

As soon as we have give up the debugger and indifferent from this system, the
program returns to operating usually.

Combine this with set variable, above, and
you have acquired some energy!


Utilizing Coredumps for Postmortem Evaluation

As an example you construct and run a program, and it dumps core on you for
some motive or one other:

$ cc -g -o foo foo.c
$ ./foo
Segmentation fault (core dumped)

Which means a core file (with a reminiscence snapshot from the time of
the crash) has been created with the identify “core”. If you happen to’re not getting
a core file (that’s, it solely says “Segmentation fault” and no core file
is created), you might need your ulimit set too low; attempt typing ulimit -c limitless at your shell
immediate.

You may hearth up gdb with the -c choice to specify a core file:

$ gdb -tui -c core foo

And, if in TUI mode, you may be greeted with a display screen of data,
telling you why this system exited (“sign 11, Segmentation fault”),
and the spotlight will likely be on the offending line. (In dumb terminal
mode, the offending line is printed out.)

On this instance, I print the variable that is inflicting the issue.
Certainly it’s NULL:

Even when you do not have all of the supply code, it is typically helpful to get
a backtrace from the purpose this system
crashed.


Window Capabilities

In TUI mode, you may get an inventory of present home windows with the data win command. You may then change which
window has focus with the focus (or fs) command. focus takes
both a window identify, or “prev” or “subsequent” as an argument. Legitimate window
names are “SRC” (supply window), “CMD” (command window), “REGS”
(registers window), and “ASM” (meeting window). See the subsequent part
for the best way to use these different home windows.

Be aware that when the SRC window has focus, the arrow keys will transfer the
supply code, however when the CMD window has focus, the arrow keys will
choose the earlier and subsequent instructions within the command historical past. (For the
file, the instructions to maneuver the SRC window single traces and single
pages are +, , <, and >.)

(gdb) data win
        SRC     (36 traces)  <has focus>
        CMD     (18 traces)
(gdb) fs subsequent
Focus set to CMD window.
(gdb) data win
        SRC     (36 traces)
        CMD     (18 traces)  <has focus>
(gdb) fs SRC
Focus set to SRC window.
(gdb)

(Window names are case in-sensitive.)

The winheight (or wh) command units the peak of a selected
window, however I’ve had dangerous luck with this working nicely.


Show Registers and Meeting

In TUI mode, the format command controls
which home windows you see. Moreover, the tui
reg
permits management of the register window, and can open it if it is
not already open.

>The instructions are:

format src Customary format—supply on high, command window on the
backside
format asm Similar to the “src” format, besides it is an meeting window
on high
format cut up Three home windows: supply on high, meeting within the center, and
command on the backside
format reg Opens the register window on high of both supply or
meeting, whichever was opened final
tui reg basic Present the overall registers
tui reg float Present the floating level registers
tui reg system Present the “system” registers
tui reg subsequent Present the subsequent web page of registers—that is vital
as a result of there may be pages of registers that are not within the “basic”,
“float”, or “system” units

This is a nifty screenshot to whet your urge for food, exhibiting supply and
meeting in “cut up” mode:

Meeting code is available in two flavors on Intel machines: Intel and
AT&T. You may set which one seems within the disassembly window with
set disassembly-flavor. Legitimate values are
“intel” and “att”. If you have already got the meeting window open, you may
have to shut it and reopen it (format src
adopted by format cut up, for instance.)

To show registers in dumb terminal mode, sort data registers for the integer registers, or data all-registers for all the pieces.


Writing a Entrance-Finish

You are pondering, “Wow, that is fairly cool, however I might write a
killer front-end for this factor that labored so a lot better! How do I do
it?”

GDB helps what it calls the “machine interface interpreter”, or
GDB/MI. The interpreter is chosen on the gdb
command line with the –interpreter change.

Mainly you may launch gdb and skim instructions
and outcomes to and from it (in all probability utilizing pipes). Fairly
easy.

See the GDB
documentation for all the details
.


Fast Reference

Command parameters are in italics. Elective parameters are in sq.
brackets. All instructions may be abbreviated till they develop into ambiguous.

This record may be very very incomplete, and solely exhibits issues talked
about on this tutorial!


assist
command
Get assistance on a sure command
apropos
key phrase
Search assist for a selected
key phrase
gdb [-tui] [-c core] [exename] (Unix Command)
Begin gdb on an executable or standalone; specify
“-tui” to start out the TUI GUI; specify “-c” with a corefile identify to see
the place a crash occurred
run [arg1] [arg2] […] Run the at the moment loaded program with
the given command line arguments
give up Exit the debugger
file
exename
Load an executable file by
identify
break
location
Set a breakpoint at a location,
line quantity, or file (e.g. “fundamental”, “5”, or “hiya.c:23”)
watch
expression
Break when a variable is
written to
rwatch
expression
Break when a variable is
learn from
awatch
expression
Break when a variable is
written to or learn from
data break Show breakpoint and watchpoint info and numbers
data watch Similar as data break
clear
location
Clear a breakpoint from a
location
delete num Delete a breakpoint or watchpoint by quantity
subsequent Run to the subsequent line of this perform
step Step into the perform on this line, if attainable
stepi Step a single meeting instruction
proceed Hold operating from right here
CTRL-C Cease operating, wherever you might be
end Run till the tip of the present perform
advance
location
Advance to a location,
line quantity, or file (e.g. “somefunction”, “5”, or “hiya.c:23”)
bounce location Similar to proceed, besides bounce to
a selected location first.
show
expression
Show the worth of a
variable or expression each step of this system—the expression
should make sense within the present scope
data show Present an inventory of expressions at the moment being displayed and
their numbers
undisplay
num
Cease exhibiting an expression
recognized by its quantity (see data show)
print
expression
Print the worth of a variable
or expression
printf formatstr expressionlist Do some
formatted output with printf() e.g. printf "i = %d, p = %sn", i, p
set variable
expression
Set a variable to worth, e.g.
set variable x=20
set
(expression)
Works like set variable
data win Exhibits present window data
focus
winname
Set focus to a selected window
bby identify (“SRC”, “CMD”, “ASM”, or “REG”) or by place (“subsequent” or
“prev”)
fs Alias for focus
format sort Set the window format (“src”, “asm”, “cut up”, or “reg”)
tui reg sort Set the register window format (“basic”, “float”,
“system”, or “subsequent”)
winheight val Set the window peak (both an absolute worth, or a
relative worth prefaced with “+” or “-“)
wh Alias for winheight
set disassembly-flavor taste Set the look-and-feel of the disassembly. On Intel
machines, legitimate flavors are intel and att
RETURN Hit RETURN to repeat the final command
backtrace Present the present stack
bt Alias for backtrace
connect pid Connect to an already-running course of by its PID
data registers Dump integer registers to display screen
data all-registers Dump all registers to display screen


Copyright 2009 Brian “Beej Jorgensen” Corridor
<beej@beej.us>

Source Link

What's Your Reaction?
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
View Comments (0)

Leave a Reply

Your email address will not be published.

2022 Blinking Robots.
WordPress by Doejo

Scroll To Top