GDB: sync breakpoints with modified code - gdb

Some breakpoints are set during debugging, then saved with save breakpoints bps.
Code is modified by adding a few lines in the middle on the file.
When gdb is started again and source bps is done, those breakpoints, which are above first occurrence of code modification are ok, rest of them are relatively moved.
Is there a way to do some smart synchronization of breakpoints with modified file?

Is there a way to do some smart synchronization of breakpoints with
modified file?
This depends on how you are setting breakpoints. You can try to set them independently of line numbers, for example at function name:
(gdb) b main
This way breakpoint location is independent on line numbers and synchronizes automatically with modified file.

You can add the breakpoints in the source code by doing int 3:
#include <stdio.h>
#define __DEBUG
#ifdef __DEBUG
#define __breakpoint__() __asm__ __volatile__("int $3\n")
#else
#define __breakpoint__()
#endif
int main(int argc, char **argv) {
const char *p = "Hello world!";
__breakpoint__();
printf("'%s'\n", p);
return 0;
}

Related

How to view Macro definition value in executable

Been years since I've coded in C/C++ so sorry about the newbie'ish question. I have codebase that compiles differently based upon configurations that are defined via #defines, which can be provided as args to the makefile. Is there a way to encode these #defines so I can look at an executable and see what the define was - e.g.
int main() {
#ifdef CONFIG_A
init_config_a();
#endif
#ifdef CONFIG_B
init_config_b();
#endif
}
#ifdef CONFIG_A
void init_config_a() {
// do something
}
#endif
#ifdef CONFIG_B
void init_config_b() {
// do something for B
}
#endif
How can I tell if a given executable was created with config A or config B. One hack is to look for symbols that are only compiled based upon the definitions (e.g. init_config_a) but that's pretty ugly.
EDIT: Sorry I neglected an important piece of info: the program is actually compiled to run on an embedded system so I can't easily just add a switch or some other mechanism to run the program locally.
Well, your question is not really precise on how you really want to get the information once you have the binary. As solution that does not involved disassembly would be having a struct with that information and initialize it when you want to print that information. Perhaps something as trivial as this:
#include <stdio.h>
#include <string.h>
struct buildinfo {
int CONFIG_A;
int CONFIG_B;
};
void get_build_info(struct buildinfo *info)
{
if(info == NULL)
return;
memset(info, 0, sizeof *info);
#ifdef CONFIG_A
info->CONFIG_A = 1;
#endif
#ifdef CONFIG_B
info->CONFIG_B = 1;
#endif
}
int main(int argc, char **argv)
{
if(argc == 2 && strcmp(argv[1], "-v") == 0)
{
struct buildinfo info;
get_build_info(&info);
printf("build info: CONFIG_A: %s, CONFIG_B: %s\n",
info->CONFIG_A ? "yes" : "no",
info->CONFIG_B ? "yes" ; "no");
return 0;
}
...
return 0;
}
I you don't want to analyse the binary, then you can execute ./yourprogram -v and see the information printed on screen.
The best way will be to name the binary based upon the define used.
If you want to tell whether the binary was build with CONFIG_A or CONFIG_B just by inspection. On possible approach could be the following.
Put a signature depending on the configuration at a specific address (will work at any address too). e.g.
int main() {
#ifdef CONFIG_A
// this sign can be put at specific address with #pragma
const char sign[]="CONFIG_A";
init_config_a();
#elif defined(CONFIG_B) // only one shall be defined at a time
// this sign can be put at specific address with #pragma
const char sign[]="CONFIG_B";
init_config_b();
#endif
}
When you open the binary in a text editor you will be able to see the sign in ASCII view.

Kernel module periodically calling user space program

I want to call a user space program from a kernel module periodically.But the kernel program is freezing the system, while I try to load it.
following is the program,
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
#include <linux/jiffies.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
#include <linux/hrtimer.h>
#include <linux/sched.h>
#include <linux/delay.h>
#define TIME_PERIOD 50000
static struct hrtimer hr_timer;
static ktime_t ktime_period_ns;
static enum hrtimer_restart timer_callback(struct hrtimer *timer){
char userprog[] = "test.sh";
char *argv[] = {userprog, "2", NULL };
char *envp[] = {"HOME=/", "PATH=/sbin:/usr/sbin:/bin:/usr/bin", NULL };
printk("\n Timer is running");
hrtimer_forward_now(&hr_timer, ktime_period_ns);
printk("callmodule: %s\n", userprog);
call_usermodehelper(userprog, argv, envp, UMH_WAIT_PROC);
return HRTIMER_RESTART;
}
static int __init timer_init() {
ktime_period_ns= ktime_set( 0, TIME_PERIOD);
hrtimer_init ( &hr_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL );
hr_timer.function = timer_callback;
hrtimer_start( &hr_timer, ktime_period_ns, HRTIMER_MODE_REL );
return 0;
}
static int __exit timer_exit(){
int cancelled = hrtimer_cancel(&hr_timer);
if (cancelled)
printk(KERN_ERR "Timer is still running\n");
else
printk(KERN_ERR "Timer is cancelled\n");
}
module_init(timer_init);
module_exit(timer_exit);
MODULE_LICENSE("GPL");
test.sh is a script which just echoes a comment.
I have tested the call_usermodehelper part and timer part individually and it is working fine. But while I am combining the two codes, the system hangs.
Can anybody please help me to solve the problem.
Quick look around strongly suggests that hrtimer callbacks are executed from an irq context, which is expected - how else are you going to get high resoluton?
But this also means you must no block, while your callback can block due to call_usermodehelper regardless of NOWAIT passed.
So it seems you are testing your module on a kernel with debugging disabled, which is fundamentally wrong.
But this is less relevant as the thing you are trying to achieve in the first place looks fundamentally wrong.
I can only recommend you elaborate what is the actual problem. There is absolutely now way that forking + execing has anything to do with something requiring a high resolution timer.

GDB does not break on some lines of code when using multiple source files

I have a program that I'd like to debug by setting a breakpoint in a non-default constructor, but the breakpoint I set is never hit. Below is an example program where this problem comes up. There is no problem hitting breakpoints set in the main function, but any breakpoints set in the Domain.cpp file are ignored:
Main.cpp:
#include <iostream>
#include "Domain.h"
int main()
{
Domain y;
std::cout << y.x << std::endl; // <- No problem setting breakpoint here
return 0;
}
Domain.cpp:
#include "Domain.h"
Domain::Domain()
{
x = 4; // <- A breakpoint here is skipped
}
Domain.h:
#ifndef DOMAIN_H_
#define DOMAIN_H_
class Domain
{
public:
int x;
public:
Domain();
};
#endif /* DOMAIN_H_ */
However, the problem does not exist if I put everything into a single file:
Main2.cpp:
#include <iostream>
int main()
{
class Domain
{
public:
int x;
Domain()
{
x = 4; // <- No problem setting breakpoint here now!
};
};
Domain y;
std::cout << y.x << std::endl;
return 0;
}
Why is this the case? How can I change this so that I'm able to set breakpoints when I use multiple files?
I can confirm that the breakpoints aren't working both when I run the debugger manually in a terminal and when I run it through Eclipse CDT, where I get the same error discussed in this question which was apparently never answered:
Why does Eclipse CDT ignore breakpoints?
I am using:
Eclipse Kepler
Mac OSX 10.8.4
gdb 6.3.5 (Apple version)
gcc 4.2.1 with -O0 and -g3 flags
Please be patient with me. I'm still learning the ropes.
You are likely hitting this GDB bug.
This bug has long been fixed, but your version of GDB is very old (and Apple is unlikely to update it).
This is a very interesting anomaly that I would like to explore further, but I suspect it's related to Eclipse's default GCC settings. Many super basic functions like these get optimized out when they hit the compiler. (one time I tried to track a simple for loop, but the viable was removed entirely on GCC's highest optimization settings)

Function Call Stack in C++

I have tried the following links, from StackOverflow and other sites,[I tried, but it didn't helped me, so i can't avoid duplicating]
StackWalk64 on Windows - Get symbol name
How do you make StackWalk64() work successfully on x64?
http://www.codeproject.com/KB/threads/StackWalker.aspx
http://jpassing.com/2008/03/12/walking-the-stack-of-the-current-thread/
How to Log Stack Frames with Windows x64
...
But none of the Code worked for me.I'm new to Windows C++ environment and i can't get any of the above code to work.
I'm looking for a call stack format like,
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__ ...
Just function name and line numbers.
My Environment:
Visual Studio 2010
SDK : v7.1
Windows 7 Pro SP1
It would be a lot simple if anyone post a header file,[there seems to be few available,but not working] which we can include in our cpp file and print the call stack with a call like 'PrintFunctionCallStack();' . BTW in Linux/Mac, it was a whole lot easier,i was able to get the call stack from backtrace and it was so simple that i did it myself in few mins. In Windows i've have been trying past two days, but no surprise at all.
Linux/Mac Stack Trace Code, i haven't yet demangled the symbol names.
#ifndef _STACKTRACE_H_
#define _STACKTRACE_H_
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <iostream>
static inline void PrintStackTrace()
{
cout<<"##############################################\n";
unsigned int maxStackCount = 63;
void* addressList[maxStackCount+1];
int addrLen = backtrace(addressList, sizeof(addressList) / sizeof(void*));
if (addrLen == 0) {
cout<<"Empty Stack, Probably Corrupted it seems ###\n";
return;
}
char** symbolList = backtrace_symbols(addressList, addrLen);
for (int i = 1; i < addrLen; i++) // Skipped First, 'i' begins with '1'
{
cout<<"###: "<<symbolList[i]<<":###\n";
}
free(symbolList);
cout<<"##############################################\n";
}
#endif
If your environment is Visual Studio, you can insert a Tracepoint and input
$CALLSTACK
in its edit box, after checking Print a message.
To do it, right-click on the line you want and select Breakpoint > Insert Breakpoint (or alternatively, insert a breakpoint clicking on the left of the editor line you want, then select When Hit).
Then you will see a detailed report in the Output window, having file name, line number and function name. It served me to successfully discovered some memory leaks.

how do I set a debug mode in c++

I would like to set a debug mode so that it prints the log statements only if the debug mode is on. For example if I have code like this
printf("something \n");
.
.
.
perror("something \n");
It only works if the debug flag is on.. I don't want to use "if" statements.
I think there is a clever way to do this using #define or something..
Thank is advance..
#ifdef _DEBUG // or #ifndef NDEBUG
#define LOG_MSG(...) printf(__VA_ARGS__) // Or simply LOG_MSG(msg) printf(msg)
#else
#define LOG_MSG(...) // Or LOG_MSG(msg)
#endif
On non-Debug built LOG_MSG would yeild to nothing. Instead of defining it with raw printf, you can have your custom logging-function, or class-method to be called.
Without going in to specific libraries or solutions, generally people make a logger class or function, and a single debug flag. The debug function checks this flag before calling printf or cout. Then in the rest of your code you simply call your debug function / method.
Here's an example:
class MyDebugger
{
private:
bool m_debug;
public:
MyDebugger();
void setDebug(bool debug);
void debug(const char* message);
};
MyDebugger::MyDebugger()
{
m_debug = false;
}
void MyDebugger::setDebug(bool debug)
{
m_debug = debug;
}
void MyDebugger::debug(const char* message)
{
if(m_debug)
{
cout << message << endl;
}
}
int main(int argc, char** argv)
{
MyDebugger debugger;
debugger.debug("This won't be shown");
debugger.setDebug(true);
debugger.debug("But this will");
return 0;
}
of course this is an incredibly naive implementation. In real logger classes there are many levels for finer-grained control of how much detail gets printed (levels like error, warning, info, and debug to differentiate the importance of the message). They might also let you log to files as well as stdout. Still this should give you a general idea.
In GCC, something like
#define debugprint(...) printf(__VA_ARGS__)
You can do a simple C-style macro definition (especially if you compiler is modern enough to do variable arguments macros, i.e. gcc or VS2005+) doing printf with a check of the debug level which can be a static global variable.
If you go with C++-style class similar to what #Chris suggests, I would make the logging function inline to ensure that when logging is disabled you are not wasting time on calling functions.