I have some C++ code like this that I'm stepping through with GDB:
void foo(int num) { ... }
void main() {
Baz baz;
foo (baz.get());
}
When I'm in main(), I want to step into foo(), but I want to step over baz.get().
The GDB docs say that "the step command only enters a function if there is line number information for the function", so I'd be happy if I could remove the line number information for baz.get() from my executable. But ideally, I'd be able to tell GDB "never step into any function in the Baz class".
Does anyone know how to do this?
Starting with GDB 7.4, skip can be used.
Run info skip, or check out the manual for details: https://sourceware.org/gdb/onlinedocs/gdb/Skipping-Over-Functions-and-Files.html
Instead of choosing to "step", you can use the "until" command to usually behave in the way that you desire:
(gdb) until foo
I don't know of any way to permanently configure gdb to skip certain symbols (aside from eliding their debugging information).
Edit: actually, the GDB documentation states that you can't use until to jump to locations that aren't in the same frame. I don't think this is true, but in the event that it is, you can use advance for the same purpose:
(gdb) advance foo
Page 85 of the GDB manual defines what can be used as "location" arguments for commands that take them. Just putting "foo" will make it look for a function named foo, so as long as it can find it, you should be fine. Alternatively you're stuck typing things like the filename:linenum for foo, in which case you might just be better off setting a breakpoint on foo and using continue to advance to it.
(I think this might be better suited as a comment rather than an answer, but I don't have enough reputation to add a comment yet.)
So I've also been wanting to ignore STL, Boost, et al (collectively '3rd Party') files when debugging for a while. Yesterday I finally decided to look for a solution and it seems the nearest capability is the 'skip' command in GDB.
I found the 'skip' ability in GDB to be helpful, but it's still a nuisance for me because my program uses a lot of STL and other "3rd Party" template code. In this case I have to mark a bunch of files as skip. After the 2nd time doing so I realized it would be more helpful to be able to skip an entire directory--and most helpful to skip a directory and all subdirectories. That way I can skip, for example, /usr since none of my code lives there and I typically have no interest in debugging through 3rd party code. So I extended the 'skip' command in gdb to support a new type 'dir'. I can now do this in gdb:
skip dir /usr
and then I'm never stopped in any of my 3rd party headers.
Here's a webpage w/ this info + the patch if it helps anyone: info & patch to skip directories in GDB
It appears that this isn't possible in GDB. I've filed a bug.
Meanwhile, gdb has the skip function command. Just execute it when you are inside the uninteresting function and it will not bother you again.
skip file is also very useful to get rid of the STL internals.
As Justin has said, it has been added in gdb 7.4. For more details, take a look at the documentation.
Related
struct Foo{
Bar get(){
}
}
auto f = Foo();
f.get();
For example you decide that get was a very poor choice for a name but you have already used it in many different files and manually changing ever occurrence is very annoying.
You also can't really make a global substitution because other types may also have a method called get.
Is there anything for D to help refactor names for types, functions, variables etc?
Here's how I do it:
Change the name in the definition
Recompile
Go to the first error line reported and replace old with new
Goto 2
That's semi-manual, but I find it to be pretty easy and it goes quickly because the compiler error message will bring you right to where you need to be, and most editors can read those error messages well enough to dump you on the correct line, then it is a simple matter of telling it to repeat the last replacement again. (In my vim setup with my hotkeys, I hit F4 for next error message, then dot for repeat last change until it is done. Even a function with a hundred uses can be changed reliably* in a couple minutes.)
You could probably write a script that handles 90% of cases automatically too by just looking for ": Error: " in the compiler's output, extracting the file/line number, and running a plain text replace there. If the word shows up only once and outside a string literal, you can automatically replace it, and if not, ask the user to handle the remaining 10% of cases manually.
But I think it is easy enough to do with my editor hotkeys that I've never bothered trying to script it.
The one case this doesn't catch is if there's another function with the same name that might still compile. That should never happen if you do this change in isolation, because an ambiguous name wouldn't compile without it.
In that case, you could probably do a three-step compiler-assisted change:
Make sure your code compiles before. Then add #disable to the thing you want to rename.
Compile. Every place it complains about it being unusable for being disabled, do the find/replace.
Remove #disable and rename the definition. Recompile again to make sure there's nothing you missed like child classes (the compiler will then complain "method foo does not override any function" so they stand right out too.
So yeah, it isn't fully automated, but just changing it and having the compiler errors help find what's left is good enough for me.
Some limited refactoring support can be found in major IDE plugins like Mono-D or VisualD. I remember that Brian Schott had plans to add similar functionality to his dfix tool by adding dependency on dsymbol but it doesn't seem implemented yet.
Not, however, that all such options are indeed of a very limited robustness right now. This is because figuring out the fully qualified name of any given symbol is very complex task in D, one that requires full semantics analysis to be done 100% correctly. Think about local imports, templates, function overloading, mixins and how it all affects identifying the symbol.
In the long run it is quite certain that we need to wait before reference D compiler frontend becomes available as a library to implement such refactoring tool in clean and truly reliable way.
A good find all feature can be better than a bad refactoring which, as mentioned previously, requires semantic.
Personally I have a find all feature in Coedit which displays the context of a match and works on all the project sources.
It's fast to process the results.
For example:
dprintf main,"hello\n"
run
Generates the same output as:
break main
commands
silent
printf "hello\n"
continue
end
run
Is there a significant advantage to using dprintf over commands, e.g. it is considerably faster (if so why?), or has some different functionality?
I imagine that dprinf could be in theory faster as it could in theory compile and inject code with a mechanism analogous to the compile code GDB command.
Or is it mostly a convenience command?
Source
In the 7.9.1 source, breakpoint.c:dprintf_command, which defines dprintf, calls create_breakpoint which is also what break_command calls, so they both seem to use the same underlying mechanism.
The main difference is that dprintf passes the dprintf_breakpoint_ops structure, which has different callbacks and gets initialized at initialize_breakpoint_ops.
dprintf stores list of command strings much like that of commands command, depending on the settings. They are:
set at update_dprintf_command_list
which gets called on after a type == bp_dprintf check inside init_breakpoint_sal
which gets called by create_breakpoint.
When a breakpoint is reached:
bpstat_stop_status gets called and invokes b->ops->after_condition_true (bs); for the breakpoint reached
after_condition_true for dprintf is dprintf_after_condition_true
bpstat_do_actions_1 runs the commands
There are two main differences.
First, dprintf has some additional output modes that can be used to make it work in other ways. See help set dprintf-channel, or the manual, for more information. I think these modes are the reason that dprintf was added as a separate entity; though at the same time they are fairly specialized and unlikely to be of general interest.
More usefully, though, dprintf doesn't interfere with next. If you write a breakpoint and use commands, and then next over such a breakpoint, gdb will forget about the next and act as if you had typed continue. This is a longstanding oddity in the gdb scripting language. dprintf doesn't suffer from this problem. (If you need similar functionality from an ordinary breakpoint, you can do this from Python.)
What I want is a mix of what can be obtained by a static code analysis like Doxygen and the stackframe you can see when using GDB. I know which problematic function I'm debugging and I want to see the neighbourhood of the function calls that guided the execution to this function call. For instance, running a simple HelloWorld! would output something like:
main:
Greeter::Greeter()
Greeter::printHello()
Greeter::printWorld()
denoting that from the main function, the constructor was called and then the printHello and printWorld functions where called. Notice that in GDB if I break at printWorld I won't be able to see in the stackframe that printHello was called.
Any ideas about how to trace function calls without going through the pain of inserting log messages in a myriad of source files?
Thanks!!
The -finstrument-functions option to gcc instructs the compiler to call a user-provided profiling function at every function entry and exit.
You could use this to write a function that just logs every function entry and exit.
From reading the question I understand that you want a list of all relevant functions executed in order as they're executed.
Unfortunately there is no application to generate this list automatically, but there are helper macros to save you a lot of time. Define a single macro called LOGFUNCTION or whatever you want and define it as:
#define LOGFUNCTION printf("In %s (%s:%d)\n", __PRETTY_FUNCTION__, __FILE__, __LINE__);
Now you do have to paste the line LOGFUNCTION wherever you want a trace to be added.
wherever you see fit.
see http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html and http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
GDB features a stack trace, it does what you ask for.
What he wants is to obtain tha info (for example, backtrace from gdb) but printed in a 'nicer' format than gdb do.
I think you can't. I mean, maybe there is some type of app that trace your application and do something like that, but I never hear about something like that.
The best thing you can do is use GDB, maybe create some type of bash script that use gdb to obtain the info and print it out in the way you like.
Of course, your application MUST be compiled with debug symbols (-g param to gcc).
I'm not entirely sure what the problem is with gdb's backtrace, but maybe a profiler is closer to what you want? For example, using valgrind:
valgrind --tool cachegrind ./myprogram
kcachegrind callgrind.out.NNNN
Have you tried to use gprof to generate a call graph? You can also convert gprof output to something easier on the eye with gprof2dot for example.
I have a 3rd party source code that I have to investigate. I want to see in what order the functions are called but I don't want to waste my time typing:
printf("Entered into %s", __FUNCTION__)
and
printf("Exited from %s", __FUNCTION__)
for each function, nor do I want to touch any source file.
Do you have any suggestions? Is there a compiler flag that automagically does this for me?
Clarifications to the comments:
I will cross-compile the source to run it on ARM.
I will compile it with gcc.
I don't want to analyze the static code. I want to trace the runtime. So doxygen will not make my life easier.
I have the source and I can compile it.
I don't want to use Aspect Oriented Programming.
EDIT:
I found that 'frame' command in the gdb prompt prints the current frame (or, function name, you could say) at that point in time. Perhaps, it is possible (using gdb scripts) to call 'frame' command everytime a function is called. What do you think?
Besides the usual debugger and aspect-oriented programming techniques, you can also inject your own instrumentation functions using gcc's -finstrument-functions command line options. You'll have to implement your own __cyg_profile_func_enter() and __cyg_profile_func_exit() functions (declare these as extern "C" in C++).
They provide a means to track what function was called from where. However, the interface is a bit difficult to use since the address of the function being called and its call site are passed instead of a function name, for example. You could log the addresses, and then pull the corresponding names from the symbol table using something like objdump --syms or nm, assuming of course the symbols haven't been stripped from the binaries in question.
It may just be easier to use gdb. YMMV. :)
You said "nor do I want to touch any source file"... fair game if you let a script do it for you?
Run this on all your .cpp files
sed 's/^{/{ENTRY/'
So that it transforms them into this:
void foo()
{ENTRY
// code here
}
Put this in a header that can be #included by every unit:
#define ENTRY EntryRaiiObject obj ## __LINE__ (__FUNCTION__);
struct EntryRaiiObject {
EntryRaiiObject(const char *f) : f_(f) { printf("Entered into %s", f_); }
~EntryRaiiObject() { printf("Exited from %s", f_); }
const char *f_;
};
You may have to get fancier with the sed script. You can also put the ENTRY macro anywhere else you want to probe, like some deeply nested inner scope of a function.
Use /Gh (Enable _penter Hook Function) and /GH (Enable _pexit Hook Function) compiler switches (if you can compile the sources ofcourse)
NOTE: you won't be able to use those macro's. See here ("you will need to get the function address (in EIP register) and compare it against addresses in the map file that can be generated by the linker (assuming no rebasing has occurred). It'll be very slow though.")
If you're using gcc, the magic compiler flag is -g. Compile with debugging symbols, run the program under gdb, and generate stack traces. You could also use ptrace, but it's probably a lot easier to just use gdb.
Agree with William, use gdb to see the run time flow.
There are some static code analyzer which can tell which functions call which and can give you some call flow graph. One tool is "Understand C++" (support C/C++) but thats not free i guess. But you can find similar tools.
and I would like to know if there is any way to stop a program when is using a function from a certain file. Ideally what I am looking for is something like:
GDB Stop when use a function from file foo.cpp
The reason to do this is because I am debugging a code that is not mine and I do not know exactly what functions are been called and what functions are not. Is there a function in GDB to do what I am looking for, or any other recommended way to do something similar?.
Thanks
Step 1: construct a list of all functions defined in foo.cpp
The simplest way I can think of (assuming you have binutils and GNU grep):
nm a.out | grep ' T ' | addr2line -fe a.out |
grep -B1 'foo\.cpp' | grep -v 'foo\.cpp' > funclist
Step 2: construct a GDB script which will set a break point on each of the above functions:
sed 's/^/break /' funclist > stop-in-foo.gdb
[Obviously, steps 1 and 2 could be combined ;-]
Step 3: actually set the breakpoints:
gdb a.out
(gdb) source stop-in-foo.gdb
Looking at this answer, an even simpler (if you are on Fedora Linux) way to find out which foo.cpp functions are called:
ftrace -sym='foo.cpp#*' ./a.out
Too bad ftrace man page says this isn't implemented yet.
rbreak regex
Set breakpoints on all functions matching the regular expression regex. This command sets an unconditional breakpoint on all matches, printing a list of all breakpoints it set. Once these breakpoints are set, they are treated just like the breakpoints set with the break command. You can delete them, disable them, or make them conditional the same way as any other breakpoint.
The syntax of the regular expression is the standard one used with tools like `grep'. Note that this is different from the syntax used by shells, so for instance foo* matches all functions that include an fo followed by zero or more os. There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
When debugging C++ programs, rbreak is useful for setting breakpoints on overloaded functions that are not members of any special classes.
rbreak foo.cpp:.
Here . matches anything, and so breaks on all functions of file foo.cpp.
Employed Russian's answer looks very good, but since you say:
I do not know exactly what functions
are been called and what functions are
not.
Would a report of which functions are hit, generated by a code coverage tool such as gcov or something involving Valgrind be a good solution to your problem?
You can use command:
break foo.cpp:function-name
gdb breakpoints have a couple of syntax... See here.
It won't break on any function in the file though....
Edit: You could do something stupid like making all function call a dummy function void foo(void), and breakpoint inside. At least you would break inside the file, and should be trivial to find which function in side of file X is being called.