Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get GDB to stop on an assertion failure?

Tags:

gdb

gcc4

I'm working on a project which includes many assertions (as it should). Problem is, I can't get GDB to break on an assertion failure; it just prints a nice assertion failure message and aborts the program. Based on earlier posts I've added, to no avail, the following breakpoints:

break g_log if log_level == G_LOG_LEVEL_CRITICAL
break g_log if log_level == G_LOG_LEVEL_WARNING
break __assert
break _assert
break abort
break exit
break __assert_fail

GDB accepts and lists all these as active breakpoints. Regardless, no break, just a nice "assertion failed..." message and the program stops... Thanks in advance, Best Regards, Dave

like image 347
Dave Nadler Avatar asked Feb 14 '16 00:02

Dave Nadler


1 Answers

Problem is, I can't get GDB to break on an assertion failure

Normally, you don't have to do anything: abort sends SIGABRT to the process, which GDB catches by default. You should be able to confirm this by compiling this test case:

#include <assert.h>
int main() { assert(0 == 1); return 0; }

and running it under GDB.

The most likely cause of your problem is that you are debugging the wrong process, not the one that actually aborts. Perhaps it's the child process that actually fails the assertion?

The GDB set follow-fork-mode may help here.

Another way you can debug this is by replacing the standard __assert_fail with:

#include <stdio.h>
int foo;
void __assert_fail(const char *assertion, const char *file, int line,
                   const char *function)
{
  fprintf(stderr, "MY assertion failed: %s in %s, %s:%d\n",
          assertion, function, file, line);
  while (foo == 0) /*spin*/;
}

(Simply link above code into your main executable, and it should "preempt" the libc.so copy of __assert_fail.)

Now when the assertion fails, the process will spin forever instead of dying with SIGABRT, and that would allow you to find it (in e.g. top) and attach to it with GDB.

like image 152
Employed Russian Avatar answered Sep 28 '22 05:09

Employed Russian