how to make GCC print helpful RUNTIME error messages? - c++

#defineing _GLIBCXX_DEBUG forces GCC to catch a large class of runtime errors in C++, such as out-of-bounds STL access, invalid iterators, etc.
Unfortunately, when the error happens, the message printed is not very helpful. I know how to print a backtrace with a function, and __FILE__ and __LINE__ with a macro myself.
Is there an easy way to convince GCC to do that, or to specify a function/macro for it to call when the kind of errors that _GLIBCXX_DEBUG catches actually occur?

I assume you mean you want messages that print the context of use in your code, rather than the filename and line number of some internal header file used by GCC.
There appears to be a single macro in .../debug/macros.h that all the checking code uses called _GLIBCXX_DEBUG_VERIFY. You could modify it to suit your needs.
Edit: Jonathan Wakely points out that all checks are fatal.

When a Debug Mode check fails it calls abort(), so it dumps a core file which you can easily examine with a debugger to see where it failed. If you run the program in a debugger it will stop when it aborts and you can print the stack trace with backtrace.
To make that automatic you would need to change the call to abort() (in libstdc++-v3/src/c++11/debug.cc). I think you could change it to call std::terminate() and then install your own terminate_handler with set_terminate to make it print a backtrace.

Related

while debugging using GDB No output after calling a user defined function in C

While debugging using gdb, I am calling the nc_print function as
(gdb)call nc_print() but there is no output and no warning.
void nc_print()
{
printf("ramanuj\n");
}
I am finding that gdb fails to call the nc_print. I am not getting why is it happening. May i know the possible reason.
I am finding that gdb fails to call the nc_print.
Your conclusion that GDB did not call nc_print is likely wrong. If you add a call to abort() to nc_print, does your program abort? If so, your conclusion is wrong.
I am not getting why is it happening
What is most likely happening is that your inferior (being debugged) program has its stdout redirected to a file (or a pipe), and thus fully buffered.
Things will likely work as you expect them if you add fflush(stdout), or use fprintf(stderr, "ramanuj\n").

How to debug "This application has requested the Runtime to terminate it in an unusual way." when I can't even step in the code?

I have a C++ program that is giving this error as soon as the process starts - apparently before any user code executes. It only happens when inlining is enabled. Even with debug symbols built in, I can't step in the code. As soon as I press F10 in Visual Studio I get the error and the program stops. I checked all exceptions/checks in "Debug/Exceptions" but still don't get a break.
Normally I would expect something like this to be due to a missing runtime dependency but I'm quite positive that's not the case here (verified with Dependency Walker).
edit: I used Steve Townsend's recommendation of CDB and now I'm able to step through the pre-user-code parts of the program. The final stack trace is:
Child-SP RetAddr Call Site
00000000`0008e308 00000000`7541601a ntdll!ZwTerminateProcess+0xa
00000000`0008e310 00000000`7540cf87 wow64!Wow64EmulateAtlThunk+0x86ba
00000000`0008e340 00000000`7539276d wow64!Wow64SystemServiceEx+0xd7
00000000`0008ec00 00000000`7540d07e wow64cpu!TurboDispatchJumpAddressEnd+0x24
00000000`0008ecc0 00000000`7540c549 wow64!Wow64SystemServiceEx+0x1ce
00000000`0008ed10 00000000`7776ae27 wow64!Wow64LdrpInitialize+0x429
00000000`0008f260 00000000`777672f8 ntdll!LdrGetKnownDllSectionHandle+0x1a7
00000000`0008f760 00000000`77752ace ntdll!RtlInitCodePageTable+0xe8
00000000`0008f7d0 00000000`00000000 ntdll!LdrInitializeThunk+0xe
You could try setting up Process Dumper and configure it for your EXE to create a dump on any process exit. Then start the process from the command line to rule out any artifacts of the IDE.
This ought to give you a dump for post-mortem debugging, and maybe a callstack fromm the exiting thread that could be useful.
It probably has to do with the order that your globals are being initialized. In C++, the order between modules is unspecified. So if a global's initializer depends on a global in another module already being initialized, you're in trouble.
It's possible to put a break point in the CRT initialization code that runs before calling main (or wmain, or WinMain, or whatever you're using). You can step through that code and see what's causing the problem.
Another possible cause is a DllMain function is returning an error or throwing an exception during DLL_PROCESS_ATTACH.

How do I get a print of the functions called in a C++ program under Linux?

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.

Determine the line of code that causes a segmentation fault?

How does one determine where the mistake is in the code that causes a segmentation fault?
Can my compiler (gcc) show the location of the fault in the program?
GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:
gcc program.c -g
Then use gdb:
$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>
Here is a nice tutorial to get you started with GDB.
Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.
Also, you can give valgrind a try: if you install valgrind and run
valgrind --leak-check=full <program>
then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.
You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g flag.
Whenever you get the message:
Segmentation fault (core dumped)
a core file is written into your current directory. And you can examine it with the command
gdb your_program core_file
The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software.
Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:
ulimit -c unlimited
Careful though! that core dumps can become huge.
There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).
Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.
According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:
int main() {
volatile int *ptr = (int*)0;
*ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
#0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
#1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
#2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING
The output is slightly more complicated than what gdb would output but there are upsides:
There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.
ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.
¹ That is Clang 3.1+ and GCC 4.8+.
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED # %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
Lucas's answer about core dumps is good. In my .cshrc I have:
alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'
to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.
Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.
This is a crude way to find the exact line after which there was the segmentation fault.
Define line logging function
#include \<iostream>
void log(int line) {
std::cout << line << std::endl;
}
find and replace all the semicolon after the log function with "; log(_LINE_);"
Make sure that the semicolons replaced with functions in the for (;;) loops are removed
If you have a reproducible exception like segmentation fault, you can use a tool like a debugger to reproduce the error.
I used to find source code location for even non-reproducible error. It's based on the Microsoft compiler tool chain. But it's based on a idea.
Save the MAP file for each binary (DLL,EXE) before you give it to the customer.
If an exception occurs, lookup the address in the MAP file and determine the function whose start address is just below the exception address. As a result you know the function, where the exception occurred.
Subtract the function start address from the exception address. The result is the offset in the function.
Recompile the source file containing the function with assembly listing enabled. Extract the function's assembly listing.
The assembly includes the offset of each instruction in the function. Lookup the source code line, that matches the offset in the function.
Evaluate the assembler code for the specific source code line. The offset points exactly the assembler instruction that caused the thrown exception. Evaluate the code of this single source code line. With a bit of experience with the compiler output you can say what caused the exception.
Be aware the reason for the exception might be at a totally different location. e.g. the code dereferenced a NULL pointer, but the actual reason, why the pointer is NULL can be somewhere else.
The steps 6. and 7. are beneficial since you asked only for the line of code. But I recommend that you should be aware of it.
I hope you get a similar environment with the GCC compiler for your platform. If you don't have a usable MAP file, use the tool chain tools to get the addresses of the the function. I am sure the ELF file format supports this.
In case any of you (like me!) were looking for this same question but with gfortran, not gcc, the compiler is much more powerful these days and before resorting to the use of the debugger, you can also try out these compile options. For me, this identified exactly the line of code where the error occurred and which variable I was accessing out of bounds to cause the segmentation fault error.
-O0 -g -Wall -fcheck=all -fbacktrace

How to debug a segmentation fault while the gdb stack trace is full of '??'?

My executable contains symbol table. But it seems that the stack trace is overwrited.
How to get more information out of that core please? For instance, is there a way to inspect the heap ? See the objects instances populating the heap to get some clues. Whatever, any idea is appreciated.
I am a C++ programmer for a living and I have encountered this issue more times than i like to admit. Your application is smashing HUGE part of the stack. Chances are the function that is corrupting the stack is also crashing on return. The reason why is because the return address has been overwritten, and this is why GDB's stack trace is messed up.
This is how I debug this issue:
1)Step though the application until it crashes. (Look for a function that is crashing on return).
2)Once you have identified the function, declare a variable at the VERY FIRST LINE of the function:
int canary=0;
(The reason why it must be the first line is that this value must be at the very top of the stack. This "canary" will be overwritten before the function's return address.)
3) Put a variable watch on canary, step though the function and when canary!=0, then you have found your buffer overflow! Another possibility it to put a variable breakpoint for when canary!=0 and just run the program normally, this is a little easier but not all IDE's support variable breakpoints.
EDIT: I have talked to a senior programmer at my office and in order to understand the core dump you need to resolve the memory addresses it has. One way to figure out these addresses is to look at the MAP file for the binary, which is human readable. Here is an example of generating a MAP file using gcc:
gcc -o foo -Wl,-Map,foo.map foo.c
This is a piece of the puzzle, but it will still be very difficult to obtain the address of function that is crashing. If you are running this application on a modern platform then ASLR will probably make the addresses in the core dump useless. Some implementation of ASLR will randomize the function addresses of your binary which makes the core dump absolutely worthless.
You have to use some debugger to detect, valgrind is ok
while you are compiling your code make sure you add -Wall option, it makes compiler will tell you if there are some mistakes or not (make sure you done have any warning in your code).
ex: gcc -Wall -g -c -o oke.o oke.c
3. Make sure you also have -g option to produce debugging information. You can call debugging information using some macros. The following macros are very useful for me:
__LINE__ : tells you the line
__FILE__ : tells you the source file
__func__ : tells yout the function
Using the debugger is not enough I think, you should get used to to maximize compiler ablity.
Hope this would help
TL;DR: extremely large local variable declarations in functions are allocated on the stack, which, on certain platform and compiler combinations, can overrun and corrupt the stack.
Just to add another potential cause to this issue. I was recently debugging a very similar issue. Running gdb with the application and core file would produce results such as:
Core was generated by `myExecutable myArguments'.
Program terminated with signal 6, Aborted.
#0 0x00002b075174ba45 in ?? ()
(gdb)
That was extremely unhelpful and disappointing. After hours of scouring the internet, I found a forum that talked about how the particular compiler we were using (Intel compiler) had a smaller default stack size than other compilers, and that large local variables could overrun and corrupt the stack. Looking at our code, I found the culprit:
void MyClass::MyMethod {
...
char charBuffer[MAX_BUFFER_SIZE];
...
}
Bingo! I found MAX_BUFFER_SIZE was set to 10000000, thus a 10MB local variable was being allocated on the stack! After changing the implementation to use a shared_ptr and create the buffer dynamically, suddenly the program started working perfectly.
Try running with Valgrind memory debugger.
To confirm, was your executable compiled in release mode, i.e. no debug symbols....that could explain why there's ?? Try recompiling with -g switch which 'includes debugging information and embedding it into the executable'..Other than that, I am out of ideas as to why you have '??'...
Not really. Sure you can dig around in memory and look at things. But without a stack trace you don't know how you got to where you are or what the parameter values were.
However, the very fact that your stack is corrupt tells you that you need to look for code that writes into the stack.
Overwriting a stack array. This can be done the obvious way or by calling a function or system call with bad size arguments or pointers of the wrong type.
Using a pointer or reference to a function's local stack variables after that function has returned.
Casting a pointer to a stack value to a pointer of the wrong size and using it.
If you have a Unix system, "valgrind" is a good tool for finding some of these problems.
I assume that since you say "My executable contains symbol table" that you compiled and linked with -g, and that your binary wasn't stripped.
We can just confirm this:
strings -a |grep function_name_you_know_should_exist
Also try using pstack on the core ans see if it does a better job of picking up the callstack. In that case it sounds like your gdb is out of date compared to your gcc/g++ version.
Sounds like you're not using the identical glibc version on your machine as the corefile was when it crashed on production. Get the files output by "ldd ./appname" and load them onto your machine, then tell gdb where to look;
set solib-absolute-prefix /path/to/libs