I decided to find out how our C/C+ *nix practitioners use the gdb debugger.
Here is what I typically use:
b - break filename.c:line #, function, filename.cpp:function, className::Member
n, c, s -- next continue step
gdb program name => set breakpoints ==> run [parameter list] (I do this to set break points before the program starts)
l - to list the surrounding source code.
attach processID
6 break [location]
gdb programName corefile.core (to examine why app crashed)
I also sometimes set breakpoint at exit function (break exit) to examine program stacks
info b to examine all the breakpoints
clear [breakpoints list ]
How do you use it?
Besides things that have already been posted i also use:
a .gdbinit file for STL containers
signal SIGNAL noprint nostop for some custom signals that are of no real interest when debugging
C-Casts to dereference pointers
catchpoints (catch throw, catch catch)
condition for conditional break- and watchpoints
rarely gdbserver for remote debugging
gdb program coredump, for those embarassing segfaults ;)
PS: One reason i personally love gdb btw. is that it supports tab-completion for nearly everything (gdb commands, symbols in the symbol table, functions, memberfunctions etc.). This is a fairly good productivity boost in my opinion.
Scripting is a nice GDB feature.
First you set a breakpoint, like: b someFunction\n.
Then you run command: commands\n. GDB will ask for commands for that breakpoint.
Common scenario is to print some value and then continue, so you will enter: p someVar\n continue\n.
To end the script press: Ctrl-D
After running program you will see your script executed occasionally when the breakpoint occurs.
Most useful gdb commands in my opinion (aside from all already listed):
info threads - information about threads
thread N - switch to thread N
catch throw - break on any thrown exception. Useful when you caught the bug only after the stack unwound.
printf,print - examine any and all expressions, printf accepts C-style formatting specifiers
Finally, if debugging over a slow link, the text UI might be of use. To use it, start gdb with the --tui command-line switch.
gdb is not my speciality, but here is what i use:
bt list a stack
up, down moving in a stack
until continue until a line with greater number than current is reached -- for exiting loops
watch [expr] break the program when expr changes
... but mostly i use ddd as a frontend to gdb
Type Ctrl-X Ctrl-A to open a simple window with source preview.
Some time ago I found cgdb:
http://cgdb.sourceforge.net/
This is a curses (color console) based frontend for gdb that made my life a lot happier when I was restricted to debugging in a console window.
See the user guide at http://sources.redhat.com/gdb/current/onlinedocs/gdb_toc.html.
There are also a couple of uses that are not directly connected with debugging. For example it
can be used for C expression evaluation:
(gdb) printf "%lu\n", (unsigned long)(-3L)
4294967293
i use the gdb -tui switch for a great 'text user interface' (a kind of gui in text mode). It supports multiple windows and is generally much more friendly than using the 'list' command (since it shows the source in a sep window)
Beginners using gdb will feel it as tough. But there GUI based tool DDD(Data Display Debugger) which is same as gdb. u have a console in the bottom to run gdb commands and top 3/4th portion would be the code. U ll have the option to learn and understand the commands and the flow excatly
Related
I'm currently debugging syslinux (a boot loader) through the gdb stub of qemu.
Recently, I wrote some gdb commands that (un)load the debug symbols everytime a module is dynamically (un)loaded. In order not to disrupt the execution, I ended the commands with continue.
break com32/lib/sys/module/elf_module.c:282
commands
silent
python
name = gdb.parse_and_eval("module->name").string()
addr = int(str(gdb.parse_and_eval("module->base_addr")), 0)
gdb.execute("load-syslinux-module %s 0x%08x" % (name, addr))
end
continue
end
However, when stepping through the code line by line, if the next or step command makes the execution hit the breakpoint, the breakpoints takes precedence, the commands are executed, including the continue. And the execution continue irrespectively of the line-by-line debugging I was doign. This also happen if I try to step over the function that has this breakpoint.
How can I keep (un)loading the debug symbols on the fly while not interfering with the debugging?
Is there an alternative to the continue command? Maybe using breakpoints isn't the right way? I'd take any solution.
This can't be done from the gdb CLI. However, it is easy to do from Python.
In Python the simplest way is to define one's own gdb.Breakpoint subclass, and define the stop method on it. This method can do the work you like, then return False to tell gdb to continue.
The stop facility was designed to avoid the problems with cont in commands. See the documentation for more details.
So I am relatively new to coding so please forgive improper vocab. What I am basically trying to do is create a script for, or perhaps enter commands into, GDB so that it can run my code with the input file of a test case over and over. Basically, I am working on a project right now that makes heavy usage of semaphores and mutexes, and somewhere, every once in a blue moon, my code breaks due to race conditions. If I could have gdb run my test case continuously until my code reached a seg fault, this would be ideal.
PS- Please be specific as to what I must do, I am not great at dissecting answers that have heavy technical answers.
Thank You!
The simplest solution is expect script. Expect is a program to automate interactions with programs that expose a text terminal interface.
Examples are available at http://en.wikipedia.org/wiki/Expect
The script should be like
#!/usr/bin/expect
# start gdb
spawn gdb yourprogram
while {1} {
# wait for gdb to start, expect the (gdb) to appear
expect "(gdb)"
# send command to run your program
send "run your_args\n"
expect {
"Program exited normally." {continue} # just run again
"(Some error message)" {interact} # start to debug
}
}
You can use GDB scripts in order to automate your GDB sessions.The GDB macro coding language consists of gdb commands along with basic looping statements and conditional statements.
You can find information about it here
http://www.adacore.com/adaanswers/gems/gem-119-gdb-scripting-part-1/
What are the best ways to automate a GDB debugging session?
I was just debugging a program in gdb and somehow I found a new feature I've never seen or even heard of before, a split view where I can see and browse the code in addition to giving commands:
What is this? What did I do, or, more specifically, how can I get this split-screen mode again? Is there a name for this mode, or somewhere I can read about how to use it?
It's called the TUI (no kidding). Start for example with gdbtui or gdb -tui ...
Please also see this answer by Ciro Santilli. It wasn't available in 2012 to the best of my knowledge, but definitely worth a look.
You can trigger it dynamically by push ctrl+x and ctrl+a.
There are two variants of it.
to only see code Press
Press CTRL X together and then 1
To see both source and assembly
Press 'CTRL' 'X' together and then '2'
http://www.cs.fsu.edu/~baker/ada/gnat/html/gdb_23.html
A screen shot of the view with code and assembly.
Also check out this amazing Github project.
GDB Dashboard
https://github.com/cyrus-and/gdb-dashboard
GDB dashboard uses the official GDB Python API and prints the information that you want when GDB stops e.g. after a next, like the native display command.
Vs TUI:
more robust, as it just prints to stdout instead of putting the shell on a more magic curses state, e.g.:
vi mode in .inputrc causes problems: https://superuser.com/questions/180512/how-to-turn-off-gdb-tui/927728#927728
program stdout / stderr breaks your interface: GDB in TUI mode: how to deal with stderr's interaction with the ui
highly configurable from Python: you can select what you want to output and how big each section is depending on what you are debugging.
The most useful views are already implemented: source, assembly, registers, stack, memory, threads, expressions... but it should be easy to extend it with any information that is exposed on the GDB Python API.
TUI only allows showing two of source, assembly and registers and that is it. Unless you want to modify it's C source code of course ;-)
I believe that GDB should ship with a setup like that out of the box and turned on by default, it would attract much more users that way.
Oh, and the main developer, Andrea Cardaci, has been very responsive and awesome. Big kudos.
See also: How to highlight and color gdb output during interactive debugging?
You can also start it from the gdb shell using the command "-" (dash). Not sure how to dynamically turn it off though.
Type layout as a command in gdb and the split window will be shown.
When GDB is in the standard mode, using win will automatically switch in the TUI mode.
Other command for TUI mode:
info win
List and give the size of all displayed windows.
focus next | prev | src | asm | regs | split
Set the focus to the named window. This command allows to change the active window so that scrolling keys can be affected to another window.
Read here form more help.
There is also interface tool for GDB called cgdb. Even with some color highlighting.
"ESC" to switch to code view, "i" to switch back to gdb
tui mode was clearly inspired by emacs -- I discovered it by accident when I hit ^X-o, which switches among split windows in emacs -- I sometimes hit that absent-mindedly when what I should be doing is switching to a different program. Anyway, that leads to another feature not mentioned yet, that you can move the cursor from the code window (where you can scroll) to the command line, or vice versa, with ^X-o.
I am using emacs and autotools, to write and compile c/c++ sources on linux.
I am using gdb via GUD in emacs.
I have defined for convenience: F7:compile, F10:gud-next, F11:gud-step, F5:gud-cont, F9:gud-tbreak, F8:gud-until, F4:gud-print.
I am mainly interested in debugging c/c++ source code on linux from emacs and I would like to get the most gdb can give.
Unfortunately I am using only F4 which prints the variable under cursor.
So my question is how do you guys debug the source code ?
What programs do you use ?
What key bindings (functionality) do you use mostly ?
What do you need the debugger to do for you ?
If you do weird stuff it doesn't matter. I would like to know everything to boost my speed a bit here.
Thanks in advance.
Mihai
I use the M-x gdb... commands to select the windows I need, then I use the gdb prompt.
I often set break points with C-x SPC on the source line once gdb is underway,
You'll get the most out of gdb by using the command line instead of key bindings. The most useful commands that I use:
bt - prints a backtrace; helpful to know full context of where you are
s, n, cont - step, next, continue
run - very useful for starting over within the same session
watch - sets a watchpoint; useful for catching when a value changes
call - invoke a function
display - Print a value every time the program stops.
valgrind is perfect for detecting memory errors. Most of the times you are given the exact location of where the error is.
gdb is nice too, but doesn't have great interface, so it is best to be used with some kind of gui like ddd or Eclipse for instance (yes, I am using gdb with Eclipse, it has built in support for it).
I only use the debugger to get a backtrace on a segmentation fault. For everything else I use printf debugging.
How do I stop a GDB execution without a breakpoint?
Just use a regular interrupt Ctrl-c will work just fine. GDB just forwards the SIGINT to the debugging process which then dies. GDB will catch the non-standard exit and break the process there, so you can still examine all the threads, their stacks and current values of variables. This works fine, though you would be better off using break points. The only time I find myself doing this is, if I think I've gotten into some sort of infinite loop.
GUI applications don't react to ^C and ^Break the way console applications do. Since these days most non-trivial projects tend to be GUI applications or libraries primarily used in GUI applications, you have two options:
Send SIGSTOP to the application from a separate terminal. This is cumbersome.
If you press ^C or ^Break on the GDB prompt, GDB will terminate but the application will remain running. You can then run GDB again to attach to it using the -p command-line switch. This loses debugger state.
In both cases, you might find this helpful: tasklist | grepProcessName| sed -e 's/ProcessName*\([0-9]*\).*/gdbModuleName-pid=\1/' > rungdb.sh You can modify this for use in shell scripts, makefiles or to send a signal instead of attaching GDB.
info threads will help you figure out which thread you want to look at. Then use threadThreadNumber to switch to it.
Start a shell, find the process ID using ps and send it SIGSTOP or SIGINT by using the kill command (e.g. kill -INT pid).
Just type BREAK without any arguments.
Break, when called without any arguments, break sets a breakpoint at the next instruction to be executed in the selected stack frame
Ctrl + Z seems to work for me (but only in some cases - I'm not sure why).