GDB test script - gdb

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?

Related

Debugging multiprocess project with GDB

I'd like to to debug a multiprocess C++ project with GDB, specifically I'd like to know if there is a way to achieve the following
Attach multiple processes to a single instance of GDB while letting all the processes run
Setting up a breakpoint in the source code of one of the processes stops all the attached processes
The ideal solution would be something similar to what is offered by the Visual Studio debugger as described here.
At the moment I'm able to attach multiple processes to a GDB instance but then only the current selected inferior is executed while the others are stopped and waiting for a continue command.
In order to be able to run inferiors in the background, one needs to issue this gdb command
set target-async on
after start up and before running anything. With this option in effect, one ca issue
continue&
(or just c&) and this will send the inferior to the background, giving an opportunity to switch to run another one.
Stopping all inferiors at once is a bit more difficult. There is no built-in command for that. Fortunately gdb is scriptable and it is possible to attach a script to a breakpoint. Once the breakpoint is hit, the commands are executed. Put inferior n and interrupt commands in the script for each inferior. It is probably more convenient to do that from a Python script, something like
(gdb) python
>inf = gdb.inferiors()
>for i in inf:
> gdb.execute("inferior %d" % i.num)
> gdb.execute("interrupt")

gdb: A "continue" that doesn't interfer with "next" or "step"

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.

GDB's commands handling

im using GDB to debug a C code in eclipse, and i wanted to ask a question about the GDB handling multiple commands.
if i send the GDB multiple commands through an external software for example:
im sending 'bt', and 'p counter', and than 'help'.
is it possible that the 'bt' command is taking too long to process and return an answer that the GDB will suspend the 'bt' command handling and will try to handle the next command?
it doe'snt make sense to me if it did, but it is important for me to know if it is possible.
i checked in google and i have read the gdb tutorial but never found explanation about the GDB handling commands that are sent to it.
thanks.
Check GDB Internals which talks about many important GDB operations and algorithms. If you have time it is good to dig deeper by looking at GDB source code to understand well.

How do you use gdb?

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

How do I stop execution in GDB without a breakpoint?

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).