Run GDB 'commands' command from terminal? - gdb

According to this page, it is possible to have specific commands executed in GDB on breakpoint. Example from the linked page:
break foo if x>0
commands
silent
printf "x is %d\n",x
cont
end
What the above means is break on function foo if x>0, print the value of x and continue with the execution.
Is there a way to specify commands...end from the terminal line? Something like:
gdb -ex=r -ex=bt -ex='b foo commands silent... end' --args myprog
Googling for the term gdb commands leads to a lot of ambiguity and I am not able to find a working example. Thank you.

Related

Obtain a trace of all function invocations? [duplicate]

How can we list all the functions being called in an application. I tried using GDB but its backtrace list only upto the main function call.
I need deeper list i.e list of all the functions being called by the main function and the function being called from these called functions and so on.
Is there a way to get this in gdb? Or could you give me suggestions on how to get this?
How can we list all the functions being called in an application
For any realistically sized application, this list will have thousands of entries, which will probably make it useless.
You can find out all functions defined (but not necessarily called) in an application with the nm command, e.g.
nm /path/to/a.out | egrep ' [TW] '
You can also use GDB to set a breakpoint on each function:
(gdb) set logging on # collect trace in gdb.txt
(gdb) set confirm off # you wouldn't want to confirm every one of them
(gdb) rbreak . # set a breakpoint on each function
Once you continue, you'll hit a breakpoint for each function called. Use the disable and continue commands to move forward. I don't believe there is an easy way to automate that, unless you want to use Python scripting.
Already mentioned gprof is another good option.
You want a call graph. The tool that you want to use is not gdb, it's gprof. You compile your program with -pg and then run it. When it runs a file gmon.out will be produced. You then process this file with gprof and enjoy the output.
record function-call-history
https://sourceware.org/gdb/onlinedocs/gdb/Process-Record-and-Replay.html
This should be a great hardware accelerated possibility if you are one of the few people (2015) with a CPU that supports Intel Processor Tracing (Intel PT, intel_pt in /proc/cpuinfo).
GDB docs claim that it can produce output like:
(gdb) list 1, 10
1 void foo (void)
2 {
3 }
4
5 void bar (void)
6 {
7 ...
8 foo ();
9 ...
10 }
(gdb) record function-call-history /ilc
1 bar inst 1,4 at foo.c:6,8
2 foo inst 5,10 at foo.c:2,3
3 bar inst 11,13 at foo.c:9,10
Before using it you need to run:
start
record btrace
which is where a non capable CPU fails with:
Target does not support branch tracing.
CPU support is further discussed at: How to run record instruction-history and function-call-history in GDB?
Related threads:
how to trace function call in C?
Is there a compiler feature to inject custom function entry and exit code?
For embedded, you also consider JTAG and supporting hardware like ARM's DSTREAM, but x86 support does not seem very good: debugging x86 kernel using a hardware debugger
This question might need clarification to decide between what are currently 2 answers. Depends on what you need:
1) You need to know how many times each function is being called in straight list/graph format of functions matched with # of calls. This could lead to ambiguous/inconclusive results if your code is not procedural (i.e. functions calling other functions in a branch out structure without ambiguity of what is calling what). This is basic gprof functionality which requires recompilation with -pg flag.
2) You need a list of functions in the order in which they were called, this depends on your program which is the best/feasible option:
a) IF your program runs and terminates without runtime errors you can use gprof for this purpose.
b) ELSE option above using dbg with logging and break points is the left over option that I learned upon reading this.
3) You need to know not only the order but, for example, the function arguments for each call as well. My current work is simulations in physics of particle transport, so this would ABSOLUTELY be useful in tracking down where anomalous results are coming from... i.e. when the arguments getting passed around stop making sense. I imagine one way to do this is would be a variation on what Employed Russian did except using the following:
(gdb) info args
Logging the results of this command with every break point (set at every function call) gives the args of the current function.
With gdb, if you can find the most child function, you can list its all ancestors like this:
gdb <your-binary>
(gdb) b theMostChildFunction ## put breakpoint on the desired function
(gdb) r ## run the program
(gdb) bt ## backtrace starting from the breakpoint
Otherwise, on linux, you can use perf tool to trace programs and their function calls. The advantage of this, it is tracing all processes including child processes and also it shows usage percentages of the functions in the program.
You can install perf like this:
sudo apt install linux-tools-generic
sudo apt install linux-cloud-tools-generic
Before using perf you may also need to remove some kernel restrictions temporarily:
sudo sh -c 'echo 0 >/proc/sys/kernel/kptr_restrict'
sudo sh -c 'echo 0 >/proc/sys/kernel/perf_event_paranoid'
sudo sh -c 'echo 0 >/proc/sys/kernel/yama/ptrace_scope'
After this, you can run your program binary with perf like this:
perf record -g -s -a <your-binary-and-its-flags>
Then either you can look the output on terminal like this:
perf report
or on text file like this:
perf report -i perf.data > output.txt
vim output.txt
when you are recording the function calls with perf also you may want to filter kernel calls with --all-user flag:
perf record -g -s -a --all-user <your-binary-and-its-flags>
For further information you can look here: https://perf.wiki.kernel.org/index.php/Tutorial

Is there a "watch window" like GDB function?

In gdb, when it hits a breakpoint, I need to manually investigate the variable values, one by one, with print or print/x functions.
Is there any easier way to list all selected variable's values whenever it hits a breakpoint, commonly known as a "watch window" of a GUI debugger?
Commands can be executed on breakpoints.
From docs:
break foo
commands
printf "x is %d\n",x
end
Or add commands to some existing breakpoint (breakpoint number 3 in this case):
commands 3
print x
print y
end
Or make a command that adds prints to a breakpoint:
define addwatch
commands $arg0
print x
print y
end
end
Then use:
addwatch 3
Or make a command that sets a breakpoint and adds prints to it.
Scripts can be stored in .gdbinit, so they'll load automatically. The language is either this GDB syntax or Python.
P.S. Some people do tracing with this by adding continue at the end of the command list: that way the variables are printed, but the application doesn't stop on the breakpoint.

How can I use a variable name instead of addresses when debugging valgrind runs with gdb?

Let's say I'm debugging with valgrind and gdb by doing:
$ valgrind --vgdb-error=0 ./magic
...and then in a second terminal:
$ gdb ./magic
...
(gdb) target remote | /usr/lib/valgrind/../../bin/vgdb
If I want to examine the defined-ness of some memory, I can use:
(gdb) p &batman
$1 = (float *) 0xffeffe20c
(gdb) p sizeof(batman)
$2 = 4
(gdb) monitor get_vbits 0xffeffe20c 4
ffffffff
Using three commands to do one thing is kind of annoying, especially since I usually want to do this a few times for many different variables in the same stack frame. But if I try the obvious thing, I get:
(gdb) monitor get_vbits &batman sizeof(batman)
missing or malformed address
Is it possible to get gdb to evaluate &batman and sizeof(batman) on the same line as my monitor command?
But if I try the obvious thing, I get: missing or malformed address
This is from GDB doc (http://sourceware.org/gdb/onlinedocs/gdb/Connecting.html#index-monitor-1210) for the monitor cmd:
monitor cmd
This command allows you to send arbitrary commands
directly to the remote monitor. Since gdb doesn't care about the
commands it sends like this, this command is the way to extend gdb—you
can add new commands that only the external monitor will understand
and implement.
As you can see "gdb doesn't care about the commands it sends like this". It probably means that the command after monitor is not processed in any way and sent AS IS.
What you can do to evaluate your variable on the same line is to use user defined commands in gdb (http://sourceware.org/gdb/onlinedocs/gdb/Define.html). Define your own comand and use the eval gdb command to prepare your command with necessary values (http://sourceware.org/gdb/current/onlinedocs/gdb/Output.html#index-eval-1744):
define monitor_var
eval "monitor get_vbits %p %d", &$arg0, sizeof($arg0)
end
And then use it like this:
(gdb) monitor_var batman

How to do a specific action when ANY Unknown Breakpoint gets Hit in GDB

I have read the following SO question:
Do specific action when certain breakpoint hits in gdb
Here, we use 'command' to decide what to do when the SPECIFIED Breakboint Gets Hit.
My Question is:
Suppose I put Breakpoints on ALL the Functions matching a given pattern:
gdb$rbreak func_
=> 100 Breakpoints (say)
When I execute this Code, I want to do the SAME Action - on hitting Each of these functions.
Hence, I cannot define something like:
command break_point_number
// since I don't know how many breakpoints will be there
Can somebody please suggest me:
How can I do a specific action-set when ANY Breakpoint gets Hit in GDB?
Thanks.
With a new enough version of gdb you can use a range:
(gdb) rbreak whatever
... gdb creates breakpoints N, N+1, ..., M
(gdb) commands N-M
> stuff
> end
I forget exactly when this feature went in.
With an older version of gdb, I'm not sure it can easily be done.
It can be done with difficulty: use set logging to write output to a file, then "info break", then "shell" to run scripts to edit the file into gdb commands, then "source". This is very painful.

help for gdb's stepi command

I need to trace all instrutions of a program using gdb.
After every execution of a instruction, I want gdb invokes a specified function.
Is it a possiable work? How to achieve this?
I searched internet and found "stepi arg" command in gdb could step arg instructions.
But how to find total number of instructions?
After every instruction, how to make gdb to invoke my function automately?
cat t.c
int main() { int x=1; int y=2; int z=x+y; printf("%d",z); return 0; }
gcc t.c
gdb -q ./a.out
break main
run
(no debugging symbols found)...
Breakpoint 1, 0x0000000000400488 in main ()
set logging on
while 1
>stepi
>info registers
end
quit
Now examine gdb.log: it should contain the info you are seeking.
P.S. This isn't a discussion forum. Please don't append questions as "answers". Instead edit your original question to clarify it, or use comments.
GDB always prints "---Type to continue, or q to quit---" during execution because of the height or pagination parameter.
In order to avoid or disable this you have to give the following command either in gdb prompt or .gdbinit file
set height 0 or set pagination off