简体   繁体   中英

Stopping debugger at an optimized out line of code

If I want to stop in an empty block of code it's always a problem.

if (...)
{ // I want the debugger to stop here!
}

If I add an arbitrary line of code which does not affect program behaviour it is likely to be optimized out, depending on the line

if (...)
{ 
   int a;
   a = a; // won't work
}
if (...)
{ 
   int a;
   int b = a; // will work
}

So the 2 questions arise here:

1) What is the simplest one-line code which will NOT be optimized out (but will really do nothing!), which I can use to stop the debugger? 2) Is there a way to switch all of optimizations so that to be able to stop at an arbitrary line of code? Compiler flag -O0 doesn't work.

A good enough one-line code could be some useful and interesting assert statement with a condition which would not be constant-folded by the compiler. Often some meaningful and useful assert (p!=NULL) or assert(i>0) where p is some existing pointer variable or formal, or i is some existing signed integer variable or formal, is enough.

BTW, you are in the debugging phase of your project, so adding good enough meaningful assert statements is helpful. Of course you want the <cassert> header to be included.

Don't forget that assert(3) statements are skipped if you compile with the -DNDEBUG flag.

You could also use (on Linux/x86) asm volatile ("nop") . Notice that the debugger needs some code to put a breakpoint at. You don't want an empty code.

What about using a static breakpoint ?

#include <sys/sdt.h>

if (condition)
  DTRACE_PROBE(myapp, foo);

Now you can set a breakpoint in GDB:

break -probe-stap myapp:foo

You can even use:

DTRACE_PROBE1(myapp, foo, condition);

with:

break -probe-stap myapp:foo if $_probe_arg0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM