Break on all calls to an external module/DLL - c

Is there any way to set a break point at the module level in Visual Studio so any calls to any functions defined in that particular DLL (3rd party, no source, no symbols) will trigger a break point before calling into the function?
I know you can break on a function name however I need all functions in a module (I could even make do with a wildcard as most of the API calls have a similar prefix)
Edit: If that's not possible can a callers graph be generated so I can find all the calls to the API used by my application?

I can't answer your original question, but this might help with what you ask in your edit.
Here's a trick I've used in the past to print all function calls and where they get called from. Since you don't have the 3rd party source, it won't be as clean, but you could move the logging statement to the macro and replace function calls with the macro using find/replace to get the same result.
#ifdef ENABLE_DEBUG
#define OriginalFunction(arg) OriginalFunctionDebug(arg, __FILE__, __LINE__)
void OriginalFunctionDebug(int originalArg, char* file, int line) {
[copy/paste variable declarations since they have to be at the top]
printf("%s called by %s:%d with arg %d", __FUNCTION__, file, line, arg); // use logging of your choice here
#else
void OriginalFunction(int originalArg) {
#endif
[rest of function]

Related

C pre-processor or C++ magic to automatically make an object per file?

I have a function whose behavior may need to be modified based on the file it is called from (e.g., to increase debugging trace output). This modification would need to be done without recompiling (e.g., by editing a configuration file or changing an environment variable).
Just as an example that would fill this need, I could write Function() as:
FunctionModifiable( const char* pszFile, int i );
Then make a macro thusly:
#define Function( i ) FunctionModifiable( __FILE__, (i) )
And FunctionModifiable() would have the duty to check pszFile in say an unordered_set<> that was populated during initialization to see if special functionality need be activated.
However, the overhead of that search is a minus (this is high-performance software and the function is called a huge number of times), and there is some per-file data that would need to be cached in this situation. We can eliminate the search, and have get storage for the cached info, by passing in not __FILE__ but a pointer to a helper object. This object needs the filename so that, when it undergoes one-off initialization, it can consult config or environment variables or what have you to know whether it needs special handling.
FunctionHelperObject fho( __FILE__ );
#define Function( i ) FunctionModifiable( &fho, (i) ) // C-style solution
#define Function( i ) fho.MethodModifiable( (i) ) // C++-style solution
OK, now say I want to avoid users having to define that fho in every file. (Inter alia, we can't re-write all existing files calling Function(), though say we're willing to recompile them).
The idea I had was the unusual step of putting a variable definition in the header file, so that any program including the header for Function() would get a FunctionHelperObject fho( __FILE__ ) for free. (Such definition would be #pragma once or guarded by a preprocessor variable.
The problem is that __FILE__ at that point would be the name of the header, not of the top-level compilation unit. If there was a __CFILE__ symbol, that would be the solution, but there's not.
Ultimately the best I can think of has shortcomings: 1) the "modifiable" aspect would only be available in source code explicitly written to use it, and 2) you'd have to do that explicit writing, and 3) starting to get a little complicated. In code you want to add the ability to modify behavior to you'd write USE_MODIFIABLE_FUNCTION somewhere after including the header in question. That'd be a macro that creates the FunctionHelperObject above, this time in the right "file" so __FILE__ would have the required value, and furthermore defines a macro as seen above that would mask the non-customizable function Function() with one of the two macros seen above. In short: the previous example, plus
#define USE_MODIFIABLE_FUNCTION FunctionHelperObject fho( __FILE__ );\n#define Function( i ) fho.MethodModifiable( (i) )
Code written without USE_MODIFIABLE_FUNCTION would simply call the uncustomizable Function() the normal way.
But surely this is some other accepted, portable way to provide this behavior? Although I've talked exclusively about the C preprocessor, is there perhaps any C++ template magic or any other approach that would work?
Cache the result.
// in the header with Function macro
static FunctionHelperObject functionhelper;
static inline void FunctionModifiableInterface(const char *file, int i) {
static initialized = 0;
if (initialized == 0) {
initialized = 1;
functionhelper = FunctionHelperObject(file);
}
FunctionModifiable(&functionhelper, i);
}
#define Function(i) FunctionModifiableInterface(__FILE__, (i))
You can't predict where the user would want to call you Function(i), so you can't predict the value of __FILE__. Just initialize it on the first call, which also is great, because you will not initialize it if Function is not called. You could do the same initialized check inside FunctionHelperObject constructor.
The really cool and hard to do trick is to modify your build system to allow you to pass a macro with the filename of compiled C file. Because build systems compile one C file at a time, it is possible (and it's a shame compilers doesn't do that by themselves). If you are using cmake with make backend (or really just make by itself), you could do something like this:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__MY_FILE__='\"$(notdir $(abspath $<))\"'")
And then use FunctionHelperObject fho(__MY_FILE__) like you wanted to, because __MY_FILE__ depends only on the output filename from make.
One option is something like this (rough example, keeping the C++ syntax from the OP) :
#define Function(i) do { \
static FunctionHelperObject obj(__FILE__); \
FunctionModifiable(&obj, (i)); \
} while (0)
Note the above will have to be modified to accommodate for a return value if the function has one.
Also : an alternative to __FILE__ might be __func__ if that fits better with your needs.

C preprocessor: Is there any way to expand the name of a macro inside itself

I would like to have a macro that prints it's own name (among other things), but I can't find a way to expand the macros' name in the macro itself. Basically, I want the equivalent of __FUNCTION__ for a macro name.
For example:
#define F(a, b, c) do { \
printf("%s: %s,%s,%s\n", __MACRO__, #a, #b, #c); \
c = a+b; b=a; \
} while(0)
F(x,y,z);
I would like this to print "F: x,y,z" when called.
This is indeed an XY problem.
Here is really what I'm trying to do: Soft linking symbols from a library using dlopen and dlsyms.
In order to do so the typical way i know of is:
1) Include the headers from the library.
2) Declare a variable of the type of the function you are trying to import
3) Initialize said variable with a call to dlsym
4) The call the actual function through that variable instead of calling the symbol directly.
When you have many such function to soft link, it becomes very repetitive, so macro can help.
For an full fledge example of that, see here: https://github.com/WebKit/webkit/blob/master/Source/WebCore/platform/mac/SoftLinking.h
The problem in that example and others is that you still need to manually copy the parameters list for each the functions you want to soft link.
I'm trying to improve on that, and was experimenting with macro tricks, one of which would have been helped by being able to answer my initial question.
--
Beside my soft linking issues, there are other situation where this could be useful. For example for debugging purpose, one might want to print some diagnostic information before or after every call to certain functions. One could do so by overriding functions names with macros:
#define funcA(...) \
printf("Before call to %s:%d - %d\n", #funcA, __LINE__, g_count); \
funcA(__VA_ARGS__) \
printf("After call to %s:%d - %d\n", #funcA, __LINE__, g_count);
This works well enough but if I want to do this for a bunch of function, I have to copy that macro and change funcA to funcB 4 times for each new macro. I'd rather copy it and just change the name of the macros, without having to change what's inside.
I can optimize the above by defining an internal macro p, similar to what Basile suggested:
#define funcA(...) WRAP(funcA, __VA_ARGS__)
But that's still means I need to change funcA to the new function name twice every time I copy the macro for another function.
Read more about the C preprocessor. Read the documentation of GNU cpp. Notice its stringification and concatenation abilities.
Perhaps going thru some extra internal macro might help you, so you might have a public macro like
#define FOO(X,Y,Z) PRIVATE_FOO(FOO,X,Y,Z)
with another PRIVATE_FOO macro doing stringification tricks on its first argument, maybe
#define PRIVATE_FOO(Mac,X,Y,Z) do { \
printf("%s: %s,%s,%s\n", #Mac, #X, #Y, #Z); \
Z = X+Y; Y=X; \
} while(0)
Perhaps the C preprocessor is not adequate for your task. You could generate some C code with some other tool (perhaps the GPP preprocessor, or perhaps a simple awk or python script, or perhaps some real program; you'll need to change your build process, e.g. your Makefile, to handle that). You could customize your GCC compiler with MELT if you need that. Since we don't know your actual motivations, we cannot help more.
I cannot help more, unless you motivate and clarify your question.
Your soft linking issue needs simply to use some weak symbols. It is probably unrelated to C preprocessing.

Tracing of function calls in C

I'm developing some modules for an automation system written in C and I need to perform lots of work with hardware. And I see no simple way (like traditional) to debugging things instead of trace logs. So I'm looking for a good practice to log function calls. At least the sequence of calls and return values.
The way it is performed in application is quite straightforward and actually pollutes the code with irrelevant constructions like
int function (int param){
if(trace_level & LOG_FCALLS){
writelog("Entering function()");
}
/* something useful */
if(trace_level & LOG_FCALLS){
writelog("Exit from function()=%d", ret);
}
}
I decided to use a macro that will do all the dirty work. Now it looks like this
#define LOG_E(fn) const char *__fname=fn; printf("LOG: Entry to %s\n",__fname)
#define return(ret) printf("LOG: Exit from %s()=%d\n",__fname,ret)
int testFunc(){
LOG_E("testFunc");
/*do useful things */
return(ret);
}
I see the problems with this code
I'm overriding return statement, and it is requires to write return(ret) all the time instead of return ret. It is easy to forget this issue.
I'm defining string variable within my macro. I'm aware that __func__ macro exists in C99, but my compiler, unfortunately, doesn't support this macro or any other relevant macros.
How to log the values of function arguments?
I'm pretty sure that it is not a new problem and I'm not the first one who faced with it. I'm also aware about AOP thing, but the code instrumentation is not acceptable solution for my system and I haven't found any possibility to do it with my compiler.
So I'm looking for a good ideas how to implement tracing in the most elegant way.
My environment:
Legacy code, C, Watcom 10.x, real-time OS
The super-serious, professional way to do this is to make a separate debug/test project, which is separate from the production code entirely. It goes like this:
Make sure to have a backup/commit on the production code.
Make a hard-copy of the production code on the hard drive. This will become your test project.
Create a .txt log file where you write the full signature of each function you want to log, for example:
int function (int param)
float function2 (void)
...
Create a little PC program/script that takes the above .txt file as input, then searches through the source code for matching lines of function definitions. The PC program will then generate a new .c file based on the original code, where it inserts the debug logging code inside the desired functions, after { and before }. It will take a few hours of your time to make such a program.
Link your test project by using the modified source code created by your script.
The above method is how I do it myself on mission-critical software, where you have requirements from safety standards (MISRA, code coverage etc) saying that no code which is not executed in the final product is allowed.
This method ensures the integrity of the production code and guarantees that no accidental bugs are added to the program by the test/debug code. It also leaves the clutter of compile switches etc out of the production code. And you won't have any old debug code remains in your project that you forgot to delete (otherwise I always forget some snippet of debug code somewhere in my programs).
#if defined(DEBUG_BUILD)
# define START_FUNCTION if(trace_level & LOG_FCALLS){writelog("+++ %s()", __func__)
}
# define END_FUNCTION if(trace_level & LOG_FCALLS){writelog("--- %s()", __func__)
#elif defined (TIMING_BUILD)
# define START_FUNCTION WRITE_TIMED_LOG("+++")
# define END_FUNCTION WRITE_TIMED_LOG("---")
#else
# define START_FUNCTION
# define END_FUNCTION
#endif
int function (int param){
START_FUNCTION;
...
if(error_occurred) {
END_FUNCTION;
return errror_code;
}
...
END_FUNCTION;
return 42;
}
You might customize your compiler to handle that. You could use MELT (to customize your gcc compiler) if you are compiling with GCC.
Maybe you might customize openwatcom (or pay some OpenWatcom expert to do that)...
This works in MS Visual C. You will need different versions of the return macro for different data types (or none).
#include <stdio.h>
#define TRACING
#ifdef TRACING
#define LOG_E printf("Func: %s\n", __FUNCTION__);
#define LOG_R printf("Exit: %s\n", __FUNCTION__);
#define LOG_I(ival) printf("Exit: %s %d\n", __FUNCTION__, ival);
#else
#define LOG_E
#define LOG_R
#define LOG_I(ival)
#endif
int main(void){
int retval = 0;
LOG_E
printf("Hello world!\n");
LOG_I(retval)
return retval;
}
Output:
Func: main
Hello world!
Exit: main 0

How to write a logging function or macro that can append caller's name to the logging output in C

I need a logging function or macro in C language, which should works in Linux, that can accept a format string and a list of arguments, and can append the caller's function name to the output string.
Here is an example. Suppose the logging function (macro) is called smart_log. It looks like:
smart_log(const char *fmt, ...)
The first argument fmt is a format string, just like the format string in printf.
Following fmt is a list of additional arguments to feed fmt.
Suppose a function called example_function calls smart_log in this way:
void example_function() {
smart_log("try to output number %d\n", 1);
}
Then the logging string looks like:
[example_function]: try to output number 1
So the key point is that smart_log append the caller's function to the format string.
I am not sure how to achieve this in C. I think it may be possible to use macro to achieve this.
There is no portable way for a function to know its caller in C. But you’re right, a macro works:
#define smart_log(...) ( printf("[%s]: ", __func__) , printf(__VA_ARGS__) )
__func__ is defined (C99/C11 6.4.2.2 p.1)
as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function.
Thanks to Hagen von Eitzen for improving my original attempt!
This is very system/compiler dependent as the exact incantation to get the function name depends very much on the compiler. For Visual C++, you'd use the macro __FUNCTION__ to get the current function name at compile time.
In order to make sure you get the correct function name logged without putting the macro into every invocation of smart_log, you can invoke your logging function via a macro so the macro that gets you the function name is evaluated in the correct context - if you simple add the macro to the function name, you'll always get the name of your logging function...
So instead of calling this:
smart_log("log message");
You call:
SMART_LOG("log message");
Which in turn is defined to:
#define SMART_LOG(message) smart_log(__FUNCTION__, message)
This is under the assumption that your log function takes the function name as the first parameter, so tweak to suit.
If you don't want to use macros you can use the stack for that. The smart_log function will be just on top of the function that called it.
See How can one grab a stack trace in C?
Define a macro - SMART_LOG - which passes __FILE__, __FUNCTION__, and __LINE__ to smart_log as arguments. Then whenever you use SMART_LOG, it automatically provides smart_log with the code location of the caller. Note however that __FUNCTION__ is non-standard, but is available in GCC (and Visual C so I'm lead to believe) see: https://stackoverflow.com/a/597081/191492 ).

Automatically running code at the start of every C function

I have an almost identical question as How to add code at the entry of every function? but for C:
As I'm maintaining someone else's large undocumented project, I wish to have code similar to
static C0UNT_identifier_not_used_anywhere_else = 0;
printf("%s%s:%d#%d", __func__, strrchr(__FILE__,'/'), __LINE__, ++C0UNT_identifier_not_used_anywhere_else);
to run on entry of every function, so that I
have a log of what calls what, and
can tell, on which nth call to a function it breaks.
The existing code comprises hundreds of source files, so it is unfeasible to put a macro e.g.
#define ENTRY_CODE ...
...
int function() {
ENTRY_CODE
...
}
in every function. I am also not using DevStudio, Visual Studio or other compiler providing __cyg_profile_func_enter or such extensions.
Optionally, I'd like to printf the return value of each function on exit in a similar style. Can I do that too?
Since you have tagged with gcc it has the -finstrument-functions option:
Generate instrumentation calls for entry and exit to functions. ...

Resources