Is there a way to access debug symbols at run time?

耗尽温柔 提交于 2020-01-04 02:26:09

问题


Here's some example code to give an idea of what I want.

int regular_function(void)
{
     int x,y,z;
     /** do some stuff **/
     my_api_call();
     return x;
}
...
void my_api_call(void)
{
    char* caller = get_caller_file();
    int line = get_caller_line();
    printf("I was called from %s:%d\n", caller, line);
}

Is there a way to implement the get_caller_file() and get_caller_line()? I've seen/used tricks like #defineing my_api_call as a function call passing in the __FILE__ and __LINE__ macros. I was wondering if there was a way to access that information (assuming it's present) at run time instead of compile time? Wouldn't something like Valgrind have to do something like this in order to get the information it returns?


回答1:


If you have compiled your binary with debug symbols, you may access it using special libraries, like libdwarf for DWARF debug format.




回答2:


This is highly environment-specific. In most Windows and Linux implementations where debug symbols are provided, the tool vendor provides or documents a way of doing that. For a better answer, provide implementation specifics.




回答3:


Debugging symbols, if available, need to be stored somewhere so the debugger can get at them. They may or may not be stored in the executable file itself.

You may or may not know the executable file name (argv[0] is not required to have the full path of the program name, or indeed have any useful information in it - see here for details).

Even if you could locate the debugging symbols, you would have to decode them to try and figure out where you were called from.

And your code may be optimised to the point where the information is useless.

That's the long answer. The short answer is that you should probably rely on passing in __FILE__ and __LINE__ as you have been. It's far more portable an reliable.



来源:https://stackoverflow.com/questions/3772742/is-there-a-way-to-access-debug-symbols-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!