Rewriting an already compiled function at runtime - c

In a system with a precompiled binary similar to this:
int foo(int bar) {
// do something wrong
return ...;
}
Is there a method I can use to, during runtime, change the effect of calling that function to:
int foo(int bar) {
return fixedFoo(bar);
}
Without changing other binaries? I.e. is there some memory hackery I can do to change the functionality of calling foo?
Sadly I cannot pre-patch the binary since the correct behaviour of foo is dependent on the result of runtime startup.

If you have access to the source code, you could make foo a function pointer and then set foo to the routine you want after "runtime startup".
#include <stdio.h>
int (*foo)(int);
int bar(int a) { printf("bar %d\n", a); return 0; }
int baz(int a) { printf("baz %d\n", a); return 0; }
int main(void) {
// do start up here
foo = bar;
foo(23);
return 0;
}
prints
bar 23

Related

Need an explanation about stack frames - why value of this local variable isn't removed?

I've got a question about this code:
#include <stdio.h>
void bar(void)
{
int a = 22;
}
void foo(void)
{
int a;
printf("%d\n", a);
}
int main(void)
{
bar();
foo();
}
Why is it displaying 22 like it was assigned in bar function and not the garbage data?
Shouldn't stack frame of bar function be removed from call stack (so do "a" variable) after bar function was terminated? I cannot find any decent explanation (probably, I just don't search hard enough) how call stack/stack frame really works. Can you please help me understand?

Calling a function within another function (except main())

Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}

Calling from one function to other functions within the same C program

I'm trying to call other adjacent functions (delay() and delay_ex()) from a function (bitcheck()) as shown below and as expected, the compiler has thrown an error that delay() and delay_ex() functions weren't declared in the scope and I understood that we can't call functions other than from the main. So, I declared these delay() and delay_ex() functions in a header file and called from this program by including the header file, it worked well. So, is there any other such way to make this work?
void bitcheck()
{
int i;
for(i=0;i<NELEMS(array); i++)
{
delay();
AP_CMU->DIVIDER = freq_def[0];
encryption(array,i);
delay();
// LCD_DisplayUint32(i,0,array[i]);
AP_CMU->DIVIDER = freq_def[6];
delay_ex(10);
decryption(intr_array,i);
delay_ex(10);
// LCD_DisplayUint32(i,10,array[i]);
}
}
void delay()
{
int i;
for (i = 0; i < 100000; i++) {
__NOP();
}
}
void delay_ex(int j)
{
for(int s=0; s < j; s++)
{
for ( int i = 0; i < 10000; i++) {
__NOP();
}
}
}
You can write your functions above the code that calls them like:
void foo() {
}
void bar() {
}
int main () {
foo();
bar();
}
You can also forward declare functions like:
void foo();
void bar();
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Or you can put them in a header file and include it
file.h:
void foo();
void bar();
file.c:
#include "file.h"
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
The compiler works in a single pass, as such when bitcheck() is parsed, the signatures of delay() and delay_ex() are not known, so the compiler cannot verify the call is type-correct.
The rule is declare or define before use; there are two possible solutions:
Define bitcheck() after the definition of delay() and delay_ex()
Forward-declare delay() and delay_ex().
By declaring the functions in a header and including it before defining bitcheck(), you used the second of these solutions, but use of an include file was not essential - #include does noting more than insert the file content into the translation-unit prior to compilation. This is useful when the symbols will be called from a different translation-unit than that in which they are defined; if that is not intended the declarations may be written directly rather then #include'd, and should also be declared static to avoid external-linkage and potential name clashes with other translation-units.
You need to define delay and delay_ex before bitcheck. Simply moving those two functions above bitcheck should suffice.

Can I apply const qualifier to global variable for selective functions?

Consider following source file:
#include <stdio.h>
int g_var_1;
int g_var_2;
// ...
void f1(void);
void f2(void);
// ...
int main(void)
{
f1();
f2();
return 0;
}
void f1(void)
{
// set the value of g_var_1
g_var_1 = 100;
}
void f2(void)
{
// read the value of g_var_1
printf("%d\n", g_var_1);
}
// ...
Is it possible to "apply promise" for some functions (within the same translation unit) that g_var_1 should be considered as read-only global variable for them? I have tried with something like:
void f2(void)
{
extern const int g_var_1;
// read the value of g_var_1
printf("%d\n", g_var_1);
}
but this yields into:
error: conflicting type qualifiers for ‘g_var_1’ extern const int
g_var_1;
Essentially I would like to restrict possibility of unintended modification of global variable in more complex code (values for real are known compile-time), still without "hooking" them as functions' paramaters, like as:
void f2(const int g_some)
{
printf("%d\n", g_some);
}
The appropriate way to do that is by separating your code into modules, and defining those globals as static, which will make them only module visible and will not export their symbol outside. You can then add a getter function to expose their value, without exposing them to modifications from outside the module.

Undefined reference to "function"

So I have this very simple program but I can't seem to get rid of a simple error.
I have a Header file with this
#ifndef FUNCTIONLOOKUP_H_INCLUDED
#define FUNCTIONLOOKUP_H_INCLUDED
enum functions
{
foo,
bar
};
//predefined function list
int lookUpFunction(enum functions);
#endif // FUNCTIONLOOKUP_H_INCLUDED
And in the src file i have the definition of lookUpFunction
Now when I call the lookUpFunction() from my main where I included the header file it gives me a undefined reference to it. The other awnsered questions where of no help.
#include <stdio.h>
#include <stdlib.h>
#include "FunctionLookUp.h"
int main()
{
lookUpFunction(foo); <---
return 0;
}
Function implementation
#include <stdio.h>
#include "FunctionLookUp.h"
typedef void (*FunctionCallback)(int);
FunctionCallback functionList[] = {&foo, &bar};
void foo(int i)
{
printf("foo: %d", i);
}
void bar(int i)
{
printf("bar: %d", i);
}
int lookUpFunction(enum functions)
{
int test = 2;
//check if function ID is valid
if( functions >= sizeof(functionList))
{
printf("Invalid function id"); // error handling
return 0;
}
//call function
functionList[functions](test);
return 1;
}
I can't seem to figure out where this error comes from.
You must have some file similar to:
/* FunctionLookUp.c */
#include "FunctionLookUp.h"
int lookUpFunction(enum functions)
{
/* code ... */
return x;
}
somewhere in order to solve your problem
You never show code that implements the function.
So it's most likely that what you're seeing is a linker error, the call itself is fine but the linker cannot find the code to call, so it throws an error.
Just declaring a function can't magically make it appear from somewhere, you must write the actual function too.

Resources