Linux function redirect - c

Hey, I'm trying to wrap a function in my program without using LD_PRELOAD.
I have two functions with the same signature:
void someFunc () {
puts ("someFunc");
}
void someFunc_wrapper () {
puts ("someFunc_wrapper");
}
And I want to redirect any function call to someFunc with a call to the wrapper function.
Of course I could do that with defining macros or put the wrapper function into a shared library and then call the program like this:
LD_PRELOAD=./mylib.so my_program
However, I want to redirect the function calls at runtime, without modifying the program call.
As I understand, it should be possible to redirect these calls by modifying the executable's symbol table at runtime.
Any help will be appreciated :)

ld has the option --wrap=symbol that should do what you want. The manual page has an example how it works.

Even if it is doable, modifying your program's symbol table might not be enough in the general case - think about the compiler inlining your function.
You could do this without dirty tricks by using an indirect function call though (always call that function via a pointer-to-function, update that pointer when you want to switch implementations).
Note that this has some runtime overhead (one more indirection). Whether that's important or not depends on the use case. And it can be turned off at compile time with macro tricks if that's just a debug feature you're implementing.
#include <stdio.h>
void foo(void) {
printf("Hello from foo\n");
}
void bar(void) {
printf("Hello from bar\n");
}
#ifdef INTERCEPT
typedef void(*myfunptr)(void);
myfunptr thingy = foo;
void turnonbar(void)
{
thingy = bar;
}
#else
#define turnonbar()
#define thingy foo
#endif
int main(void) {
thingy();
turnonbar();
thingy();
return 0;
}

Related

Is it possible to point several different function declarations into a single function definition

Say, I have several declarations of functions which should perform similar action across several library files:
// file0.h
void delay_ms0(unsigned int);
// file1.h
void delay_ms1(int);
// file2.h
extern void delay_ms2(int);
// file3.h
int delay_ms3(unsigned int);
// file4.h
void delay_ms4(unsigned char);
// file5.h
void delay_us(unsigned long long);
// file6.h
void delay_ms6(const int *);
// file7.h
// (in some cases, structs used to pass several functions)
typedef void (*const delay_fptr_t)(int);
extern delay_fptr_t delay_ms7;
And in my main app I have actual definition with platform-specific implementation:
// main.c
void delay_ms(unsigned int time_ms) { platform_shutdown(time_ms*128); };
So, the question is: is it somehow possible to point some or all of them to the same implementation without using additional instructions in the compiled program, i.e. somehow instruct compiler or linker where to send function calls. Particularly speaking of GCC.
If it is, it would be more convenient to develop and integrate libraries...
Currently, standard solutions usually look something like that:
// main.c
// these are extra function calls, and not always optimized out. Consumes both RAM and ROM.
void delay_ms0(unsigned int val) { delay_ms(val); };
void delay_ms1(int val) { delay_ms((unsigned int) val); };
// Somehow not always linked properly, so when called at runtime, causes hardfaults, or just nothing happens
inline void delay2(int val) { delay_ms((unsigned int) val); };
// most probably there is no way around that, as we have to return something
int delay_ms3(unsigned int) { delay_ms((unsigned int) val); return 0; };
// most probably there is no way around that, as 'c_val' has to be expanded
void delay_ms4(unsigned char c_val) { delay_ms((unsigned int) c_val); };
// most probably there is no way around that, as 'll_val' has to be processed before passing further
void delay_us(unsigned long long ll_val) { delay_ms((unsigned int) ll_val/1000); };
// most probably there is no way around that, as 'p_val' has to be dereferenced
void delay_ms6(const int *p_val) { delay_ms((unsigned int) *p_val); };
// this is my favorite so far, as it does not use extra RAM and allows some slack, when function definitions do not exactly match, but it certainly does use ROM to store pointers
delay_fptr_t delay_ms7 = (delay_fptr_t)delay_ms;
// I would like to see something like that^, but for standard declarations
// I.e. are there any alternatives to:
void (*delay2_ms)(int) = delay_ms; // gcc error: 'delay2_ms' redeclared as different kind of symbol
Yes it is possible. The straightforward way is to use the alias attribute (see the GCC docs). A tiny example:
int some(int x) {
return 2*x;
}
int more(int y) __attribute__((alias("some")));
Now, some and more are the same function.
But note that you will have to make sure the calling convention is the same. That should be pretty much obvious as otherwise, there would have to be some conversion code (still, in many cases the wrapper boils down to a few instructions ending with a JMP [or equivalent; unless you adjust return value or likewise], that shouldn’t add much to the trampolines used for linking libraries together).
However, if you really care of performance, you may consider using link-time optimization. It is now supported by GCC; search for -flto in the docs. (in a nutshell: pass -flto to GCC both while compiling and linking)

How can I use a declared but undefined function in C regardless?

So what I want to do is I want to create a kind of framework for myself in the future but I realized I can't do something. It goes like this:
void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
whenPressedQ();
printf("Q was pressed");
}
...
void whenPressedW(){
doThings();
}
Later I will define these functions and choose which of them to use.
Problem is I can't do this for the other functions if I haven't defined them below. I get an "undefined function" error. Is there any way I can solve this? I've tried using pointers to functions and check if it's null but it's the same thing.
You can pass pointers to callback functions, or wrap them in structures, then have the library pass back a pointer to a function that matches the signature later, even one that you will write in the future. This was how the first C++ compilers implemented virtual methods of objects.
If you just want the code to compile while you’re getting around to the unimplemented functions, you can create dummy stub functions to shut the linker up.
Update
Here are some examples of what I mean. Your question is somewhat ambiguous. If what you are asking is how you can declare functions that you intend to implement later, and still be able to compile the program, the answer is to provide stubs. Here’s a MCVE of your interface:
#include <stdio.h>
#include <stdlib.h>
/* In older versions of C, a declaration like void doThings() would turn
* type-checking of function arguments off, like for printf().
*/
void whenPressedQ(void);
void whenPressedW(void);
void doThings(void); // Added this declaration.
void checkPressQ()
{
whenPressedQ();
printf("Q was pressed.\n"); // Don't forget the newline!
}
void whenPressedW()
{
doThings();
}
// Stub implementations:
void whenPressedQ(void)
// FIXME: Print an error message and abort the program.
{
fflush(stdout); // Don't mix the streams!
fprintf( stderr, "Unimplemented function whenPressedQ() called.\n" );
exit(EXIT_FAILURE);
}
void doThings(void)
// Is nothing a thing?
{}
// Test driver:
int main(void)
{
whenPressedW();
whenPressedQ(); // fails;
// Not reached.
return EXIT_SUCCESS;
}
If you want to let the program dynamically select which function to call, that is more complicated, but you can do it with callbacks. Here’s a simple example.
#include <stdio.h>
#include <stdlib.h>
// This would ordinarily go in a .h file:
typedef const char*(*callback_t)(void); // The type of a callback function.
extern callback_t get_the_answer(void);
// This would ordinarily go in a .c file:
int main(void)
{
callback_t ask_the_question = get_the_answer();
printf( "The answer to life, the Universe and Everything is %s.\n",
ask_the_question()
);
return EXIT_SUCCESS;
}
// This would ordinarily go in another .c file:
static const char* the_answer_is(void)
{
return "42";
}
callback_t get_the_answer(void)
{
return &the_answer_is;
}
The error you are getting a linker error. If you are not trying to build an executable, then you can just compile and do not link. On Linux / OS X, you can pass the -c flag to clang or gcc. On Windows, you can pass the /c flag to cl.exe when compiling.
You can then link the object files directly later, or build a static or dynamic library out of them.

How to use REAL function once it is declared as WEAK function in C?

I have a problem when using WEAK reference in C. Make assumption, I have the src code structure as follows:
//Eclipse C project structure
drv
| dummy
| | dummy_Test.h
| | dummy_TestWeakAttribute.h
| src
| | source_sample.c
| test
| | myModules
| strong_test_case.c
| weak_test_case.c
test_program.c
And:
//test_program.c
#include "drv/dummy/dummy_TestWeakAttribute.h"
#include "drv/dummy/dummy_Test.h"
int main() {
printf("===================\n");
printf(" Welcome to main \n");
printf("===================\n");
// Expectation
test(); //-->real function
function(); //-->real function
test_function_strong(); //-->real function
test_function_weak(); //-->weak function
return 0;
}
//source_sample.c
#include "../dummy/dummy_TestWeakAttribute.h"
#include "../dummy/dummy_Test.h"
static void test(void) {
printf("NOT overridden!\n");
}
static void function(void){
int a =1;
a++;
test();
}
//dummy_Test.h
#ifndef DRV_DUMMY_DUMMY_TEST_H_
#define DRV_DUMMY_DUMMY_TEST_H_
#define static
//definitions
//struct definitions
//dummy functions
static void test(void);
static void function(void);
//global variable definitions
#endif /* DRV_DUMMY_DUMMY_TEST_H_ */
//dummy_TestWeakAttribute.h
#define static //disable static keyword
static void __attribute__((weak)) test(void);
//weak_test_case.c
#include "../../dummy/dummy_TestWeakAttribute.h"
#include "../../dummy/dummy_Test.h"
static void test(void){
printf("overridden successfully!\n");
}
void test_function_weak(void){
function();
}
//strong_test_case.c
#include "../../dummy/dummy_Test.h"
void test_function_strong(void){
function();
}
I got the result on the screen:
===================
Welcome to main
===================
overridden successfully!
overridden successfully!
overridden successfully!
overridden successfully!
I can't use the REAL function anymore. All my making calls to the real test function is impossible because it was declared as __attribute__((weak)) before. So, Is there anybody having idea on this case ? The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
First off, be aware that weak linkage is not a C concept. It is an ELF concept, at least for our purposes, and GCC (and other compiler) support for it is a C extension. Therefore, little of what I have to say is based on the C standard. With that said ...
Your program has two functions test(), both with weak linkage. If there were an alternative with strong linkage then that would override both. Since there is not, it is unspecified which of the two is linked to any given reference (call), but it follows from the mechanism of ELF dynamic linking that the same one would would be linked to every reference in any given dynamic object.
Other than system libraries, you have only one dynamic object in play -- the program -- so it stands to reason that the same implementation of test() is called at every point. It's unclear to me why you suppose it would be otherwise. Note in particular that the weird games you are playing with the static keyword are strictly obfuscatory. You have no actual static declarations anywhere in the code you present.
You indeed could declare a static function test in some file, and in that case you would expect calls to test() from within that file to be linked to the internal static version. To the best of my knowledge, however, a static function cannot also be weak. That wouldn't make any sense.
The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
So you want to provide for overriding some references to the function but not others? Are you nuts? What a nightmare that would be to build, and I don't even want to think about maintaining it.
If you want to provide a default implementation that you can always call then you cannot make that the weak function. Doing so is inconsistent with always being able to call it. You can, however, make it a separate, ordinary function that the weak one calls, and any other function also can call:
test.h:
#ifndef TEST_H
#define TEST_H
void test(void) __attribute__((weak));
void test_default(void);
#endif
test.c:
#include "test.h"
void test_default(void) {
printf("I am the default implementation");
}
void test(void) {
test_default();
}
Anyone with access to test_default() can then call it, but whether it gets called as a result of calling test() depends on what version of test() is linked to the call -- it is weak, so a different version could be provided.
Note also that depending on the scope you want test_default() to have, it might be both possible and sensible to make it static, whereas test() must not be static as long as it is weak.

Executing code before main()

In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code you want.
Is there any way to do this in C? I don't have any specific problem I'm trying to solve, I'm just curious. One thing this might be useful for is automatically initializing a library.
You can do it with __attribute__ ((constructor)). I've tested the following example with both gcc and clang. That being said, it's not part of the language.
#include <stdio.h>
void __attribute__ ((constructor)) premain()
{
printf("premain()\n");
}
int main(int argc, char *argv[])
{
printf("main()\n");
return 0;
}
It does the following:
$ ./test
premain()
main()
GCC documents it at: https://gcc.gnu.org/onlinedocs/gcc-8.3.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes
There are ways using __attribute__ but those are very specific to your compiler and code that is written using these are not really portable. On the other hand, the C language does not provide any start-up modules/libraries.
In C, logically main() is the first function called by the OS. But before calling main(), the OS calls another function called start-up module to setup various environment variables, initialize (un-initialized) static variables, build a stack frame (activation record) and initialize the stack pointer to the start of the stack area and other tasks that have to be done before calling main().
Say if you are writing code for embedded systems where there is no-or-minimal OS to do the above mentioned work, then you should explore these options which are compiler dependent. Other than GCC, Turbo-C and Microsoft C compilers provides facilities to add code in a particular hardware machine (f.e. 8086 machines).
In other words, the start-up modules are not meant for the programmers.
With gcc, you can do so by using the constructor function attribute, e.g.
__attribute__ ((__constructor__))
void foo(void) {
...
}
This will invoke foo before main.
Note: This is probably not portable to other compilers.
You can initialize global variables but not call functions within these initializations.
If your compiler can compile cpp files you can add a file with a class that call in the costructor your initialization code. The class must be allocated statically. For example:
#include "ext.h"
class cext
{
public:
cext()
{
ExtInit();
}
~cext(){};
};
cext g_cext;
The ExtInit() function must be defined as extern "C" in file ext.h.
#ifdef __cplusplus
extern "C" {
#endif
void ExtInit (void);
#ifdef __cplusplus
}
#endif

Getting the name of the calling function in C (without using the preprocessor)

I was wondering if there is a way of finding which function called the current function (at runtime) in C.
I know you could use __FUNCTION__ in gcc, but is there a way without using the C preprocessor?
Probably not.
Cheers
No, there isn't. C isn't a particularly introspective language - things like the name of a function (or pieces of your call stack) simply aren't available at runtime in any sane fashion.
If, for some reason, you are looking for a lot of work for very little benefit, then you can build your programs with debug symbols, and you can write stack-walking and debug symbol lookup code. Then you might be able to find this out on the fly. But be careful, because the symbols you'll see in the debug info will be decorated with type info if you've got any C++ involved.
You've tagged this post gcc, so the relevant details ARE available, however this falls into the 'not recommended' and 'not guaranteed to be the same between compiler versions' territory.
Assuming you have a function f() from which you want to know the caller.
Rename that function to f_func() and define a macro f() that prints __func__ and then calls f_func(). Example:
void
f_func()
{
do something;
}
#define f() \
do { \
printf("f called from %s\n", __func__); \
f_func(); \
} while (0)
void
a()
{
f();
}
void
b()
{
f();
}
int
main(int argc, char **argv)
{
a();
b();
return(0);
}
There's no way to get a function name in the runtime. The only way is the preprocessor but it's very limited in its capabilities.
In case you have debug information available, you could walk the stack and get the function names from the debugging information. This is, however, neither a robust nor a portable solution.
There are couple of GNU functions that allow you to get function addresses and names from backtrace - backtrace() and backtrace_symbols(), but you need to compile your binary with -rdynamic flag
NO
The short answer is NO
but with preprocessor it can be done like this
Getting the name of the calling function in C (using the preprocessor)
Assuming you have a function f() from which you want to know the caller only for debugging purpose.
Rename that function to f_func() and define a macro f() that calls a version of f that prints func and then calls f_func() when DEBUG is defined.
In the final release the information is removed by calling the real function f_func()
Example
#ifdef DEBUG
#define f(a,b,c) f_debug(a,b,c, __func__)
#else
#define f(a,b,c) f_func(a,b,c)
#endif
bool f_func(int par1, int par2, int par3)
{
do_somthing();
}
bool f_debug((int par1, int par2, int par3, const char calling_func_name[])
{
printf("f called from %s\n", calling_func_name);
f_func();
}
void a()
{
f();
}
void b()
{
f();
}
int main(int argc, char **argv)
{
a();
b();
return(0);
}
Result is:
when DEBUG is defined
f called from a
f called from b
Use the __func__ identifier. The standard (section 6.4.2.2) requires that it be present for precisely this purpose:
The identifier __func__ shall be implicitly declared by the translator 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.
As Steve Jessop notes in a comment, this isn't part of the preprocessor as such, but an intrinsic part of the compiler.
There may well be ways of finding out this name by walking the stack and looking at debugging symbols. Cute, but insane.

Resources