C float reset to 0 after passing it to a function - c

In the code below,the variable "tmpRes" is correct before the call of "BuildCMD"
but inside this function,it loose his correct value and sets to 0,why it just doesn't keep the correct value even inside the BuildCMD function?
Calling code:
//tmpRead just an array of integer
float tmpRes=0;
Evaluate(tmpRead[3],tmpRead[4],tmpRead[5],&tmpRes);
printf("PRE : %f\n",tmpRes); //correct result
char *dataBuff=BuildCMD(RES,tmpData,tmpRes);
Evaluate code:
int Evaluate(int num1,int op,int num2,float *Res)
{
float tmpRes=0;
switch(op)
{
case(int)'+':{tmpRes=num1+num2;break;} //same with *Res=....
case(int)'-':{tmpRes=num1-num2;break;}
//etc...
}
*Res=tmpRes;
return 0;
}
BuildCMD:
char* BuildCMD(enum CMD cmd,int *values,float result)
{
//here the result is ALWAYS 0
//even if it was corrent before the call of BuildCMD
printf("IN: %f\n,result);
fflush(stdout);
//...rest of the code
}
Thanks in advance.
Yes,the application is multi threaded,i create n instances of mainClient from the server.
Links to the sourcecode (the one i wrote above is simplified).
mainClient.c
Utilities.c

It sounds like the code that calls BuildCMD does not have a proper prototype for that function.
You need this prototype either in main.c or in a .h file that main.c includes:
char* BuildCMD(enum CMD cmd,int *values,float result);

You have float tmpRes=0; inside Evaluate(). So in fact the Evaluate() doesn't use the global tmpRes. The global tmpRes remain 0 even though you pass it into Evaluate().

Related

Counting the number of function calls in an executable

I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:
//file1.c
int main(){
foo1();
return 0;
}
and other C files like:
//file2.c
void foo1(){
foo2();
...
foo2();
}
and
//file3.c
void foo2(){
foo3();
foo3();
foo3();
}
Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
BTW, I am compiling and running my project on Linux.
You can use 2 global variables (put extern at the places that access the variable outside the file you declare them) :
int foo1_active = 0;
int foo3_counter = 0;
then each time foo1 is called you increment it variable and before the return you decrement it:
void foo1() {
foo1_active++;
...
foo1_active--;
return
}
when foo3 is called you check if foo1 active and if it does you increment the counter:
void foo3() {
if foo1_active > 0 {
foo3_counter++;
}
...
}
You have an ubuntu flag, so I assume you are using gcc. I'd strongly consider adding -pg to your CFLAGS and trying out gprof.
Profiling works by changing how every function in your program is
compiled so that when it is called, it will stash away some
information about where it was called from. From this, the profiler
can figure out what function called it, and can count how many times
it was called. This change is made by the compiler when your program
is compiled with the `-pg' option, which causes every function to call
mcount (or _mcount, or __mcount, depending on the OS and compiler) as
one of its first operations.
You can count function calls using a static variable instead of global variable.
int inc(){
static int counter = 1;
counter++;
return counter;
}
int main(){
int i;
for (i = 0; i < 10; i++)
printf("%d\n", inc());
return 0;
}

Assign a value to external variable from function

I've been reading here a lot but never posted until now.
My problem is that I'm stuck with some code. What I'm trying to do is receive a value through UART from Matlab and assign to a single variable that is gonna stick through the entire program.
This is the test code I'm running:
void start_comm(){
//Stuck in loop untill Matlab gives signal
// Spams character 'A' while waiting
while (!uart_is_rx_ready (CONF_UART)){
printf("%c\n",'A');
delay_ms(100);
}
// Start reading data sent from Matlab
// P,I,D & samplingstime data
uint8_t p_char, i_char, d_char, samp_char1, samp_char2;
while (!uart_is_rx_ready (CONF_UART)){};
uart_read(CONF_UART, &p_char);
// Print out everything out again for testing
printf("%c\n", p_char);
}
This code works, everything prints out fine. What I need is to be able to use the value in p_char in other functions and I need it to be the same value as the one sent from Matlab i.e. if it's 5 then I could printf in another function and it would print a 5.
I've tried return p_char to a different variable but it would just revert to 0 at the start of the loop. I've also tried the following test code where I try to set the variable as static:
**file1.h**
extern int a;
**file1.c**
#include file1.h
void function(){
static int a;
scanf("%i", &a);
}
**main.c**
#include file1.h
int main() {
function();
while(1){
printf("%i", a);
}
}
Looking over the code, I'm pretty sure I'm doing something wrong with the static and extern, but I'm lost.
EDIT: Figured out the problem, it was indeed Matlab code. I needed to add a delay to it to account for the time it took to communicate with the microcontroller.
Update your file1.c to read:
#include file1.h
int a;
void function(){
scanf("%i", &a);
}
This puts a in the global scope. If you keep extern int a in your .h file, C files that include that header will know about it.

Is it possible to exchange a C function implementation at run time?

I have implemented a facade pattern that uses C functions underneath and I would like to test it properly.
I do not really have control over these C functions. They are implemented in a header. Right now I #ifdef to use the real headers in production and my mock headers in tests. Is there a way in C to exchange the C functions at runtime by overwriting the C function address or something? I would like to get rid of the #ifdef in my code.
To expand on Bart's answer, consider the following trivial example.
#include <stdio.h>
#include <stdlib.h>
int (*functionPtr)(const char *format, ...);
int myPrintf(const char *fmt, ...)
{
char *tmpFmt = strdup(fmt);
int i;
for (i=0; i<strlen(tmpFmt); i++)
tmpFmt[i] = toupper(tmpFmt[i]);
// notice - we only print an upper case version of the format
// we totally disregard all but the first parameter to the function
printf(tmpFmt);
free(tmpFmt);
}
int main()
{
functionPtr = printf;
functionPtr("Hello world! - %d\n", 2013);
functionPtr = myPrintf;
functionPtr("Hello world! - %d\n", 2013);
return 0;
}
Output
Hello World! - 2013
HELLO WORLD! - %D
It is strange that you even need an ifdef-selected header. The code-to-test and your mocks should have the exact same function signatures in order to be a correct mock of the module-to-test. The only thing that then changes between a production-compilation and a test-compilation would be which .o files you give to the linker.
It is possible With Typemock Isolator++ without creating unnecessary new levels of indirection. It can be done inside the test without altering your production code. Consider the following example:
You have the Sum function in your code:
int Sum(int a, int b)
{
return a+b;
}
And you want to replace it with Sigma for your test:
int Sigma(int a, int b)
{
int sum = 0;
for( ; 0<a ; a--)
{
sum += b;
}
return sum;
}
In your test, mock Sum before using it:
WHEN_CALLED: call the method you want to fake.
ANY_VAL: specify the args values for which the mock will apply. in this case any 2 integers.
*DoStaticOrGlobalInstead: The alternative behavior you want for Sum.
In this example we call Sigma instead.
TEST_CLASS(C_Function_Tests)
{
public:
TEST_METHOD(Exchange_a_C_function_implementation_at_run_time_is_Possible)
{
void* context = NULL; //since Sum global it has no context
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).DoStaticOrGlobalInstead(Sigma, context);
Assert::AreEqual(2, Sum(1,2));
}
};
*DoStaticOrGlobalInstead
It is possible to set other types of behaviors instead of calling an alternative method. You can throw an exception, return a value, ignore the method etc...
For instance:
TEST_METHOD(Alter_C_Function_Return_Value)
{
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).Return(10);
Assert::AreEqual(10, Sum(1,2));
}
I don't think it's a good idea to overwrite functions at runtime. For one thing, the executable segment may be set as read-only and even if it wasn't you could end up stepping on another function's code if your assembly is too large.
I think you should create something like a function pointer collection for the one and the other set of implementations you want to use. Every time you want to call a function, you'll be calling from the selected function pointer collection. Having done that, you may also have proxy functions (that simply call from the selected set) to hide the function pointer syntax.

Generate two functions with C Preprocessor

I have a project, and a case where I have a few often-changed preprocessor #defines that control how it works--ex:
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
#ifdef FEATURE_X
feature_x(content);
#endif
}
This works fine, although it does have to be recompiled each time, so it's in the "stuff that has to be recompiled each time" file. I would like to push it into a [static] library instead. I'm ok with changing how it's called (already have a function pointer for picking myFunction), so I'd like that to turn into
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
}
void myfunction_featureX(int num, mystruct* content) {
doSomethingTo(content);
//...
feature_x(content);
}
I need to do this in a couple places, so using a separate library (one with and one without -D FEATURE_X) for each isn't an acceptable option. I could do it with copy/paste, but that results in code reuse that carries a risk of fixing a bug in one copy but not the other.
Have the featureX versions of functions call the mainline functions. In your example myfunction_featureX would call myfunction and then do its own thing.
Surely, this is the point at which you change the activation of Feature X from a compile time issue into a run-time issue:
void myfunction(int num, mystruct* content)
{
doSomethingTo(content);
//...
if (FeatureX_Enabled())
feature_x(content);
}
The FeatureX_Enabled() test might be a full function, or it might be simply test an appropriately scoped variable that is defined outside the function — a static variable in the file, or an external variable. This avoids having to futz with the function pointers; it's the same function called as now. Changing a table of function pointers is equivalent to changing a single variable — it involves changing the value of something stored outside the function to change the behaviour of the function.
Would it help if you put myfeature_x in a function table instead?
#include <stdio.h>
#include <string.h>
typedef struct {
int x,y;
} mystruct;
typedef void (*fn_ptr)(mystruct* content);
fn_ptr vtable[10];
#define FEATURE_X_INDEX 0
void feature_x(mystruct *content)
{
printf("y: %d\n", content->y);
}
void myfunction(int num, mystruct* content) {
printf("x: %d\n", content->x);
//...
if (vtable[FEATURE_X_INDEX]) {
vtable[FEATURE_X_INDEX](content);
}
}
int main(void)
{
bzero(vtable, sizeof(vtable));
mystruct s;
s.x = 1;
s.y = 2;
myfunction(0, &s);
if (1) {
//Of course you'd use a more sensible condition.
vtable[FEATURE_X_INDEX] = feature_x;
}
myfunction(0, &s);
return 0;
}
Output:
x: 1
x: 1
y: 2
Then all you need to do is populate the virtual function table with NULLs if that feature is not to be used, and with function pointers if it is to be used. This you can do from wherever you want - your static library for example.. or you can compile feature_x into a dynamic library, load it at runtime and if the loading succeeded populate the function table, and clear the table when the dynamically linked library is unloaded.
I think the only benefit this really gives you over Jonathan Leffler's method is that the code for feature_x doesn't actually need to be linked into the same binary as your other code. If all you need is a runtime switch to turn the feature on or off, a simple if statement should do the trick, as Jonathan Leffler suggested. (Incidentally, there's an if here, too - it checks the function table's content :) )

How can I invoke buffer overflow?

I got a homework assignment asking me to invoke a function without explicitly calling it, using buffer overflow. The code is basically this:
#include <stdio.h>
#include <stdlib.h>
void g()
{
printf("now inside g()!\n");
}
void f()
{
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
}
int main (int argc, char *argv[])
{
f();
return 0;
}
Though I'm not sure how to proceed. I thought about changing the return address for the program counter so that it'll proceed directly to the address of g(), but I'm not sure how to access it. Anyway, tips will be great.
The basic idea is to alter the function's return address so that when the function returns is continues to execute at a new hacked address. As done by Nils in one of the answers, you can declare a piece of memory (usually array) and overflow it in such a way that the return address is overwritten as well.
I would suggest you to not blindly take any of the programs given here without actually understanding how they work. This article is very well written and you'll find it very useful:
A step-by-step on the buffer overflow vulnerablity
That is compiler dependent, so no single answer can be given.
The following code will do what you want for gcc 4.4.1. Compile with optimizations disabled (important!)
#include <stdio.h>
#include <stdlib.h>
void g()
{
printf("now inside g()!\n");
}
void f()
{
int i;
void * buffer[1];
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
// place the address of g all over the stack:
for (i=0; i<10; i++)
buffer[i] = (void*) g;
// and goodbye..
}
int main (int argc, char *argv[])
{
f();
return 0;
}
Output:
nils#doofnase:~$ gcc overflow.c
nils#doofnase:~$ ./a.out
now inside f()!
now inside g()!
now inside g()!
now inside g()!
now inside g()!
now inside g()!
now inside g()!
Segmentation fault
Since this is homework, I would like to echo codeaddict's suggestion of understanding how a buffer overflow actually works.
I learned the technique by reading the excellent (if a bit dated) article/tutorial on exploiting buffer overflow vulnerabilities Smashing The Stack For Fun And Profit.
Try this one:
void f()
{
void *x[1];
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
x[-1]=&g;
}
or this one:
void f()
{
void *x[1];
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
x[1]=&g;
}
While this solution doesn't use an overflow technique to overwrite the function's return address on the stack, it still causes g() to get called from f() on its way back to main() by only modifying f() and not calling g() directly.
Function epilogue-like inline assembly is added to f() to modify the value of the return address on the stack so that f() will return through g().
#include <stdio.h>
void g()
{
printf("now inside g()!\n");
}
void f()
{
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
/* x86 function epilogue-like inline assembly */
/* Causes f() to return to g() on its way back to main() */
asm(
"mov %%ebp,%%esp;"
"pop %%ebp;"
"push %0;"
"ret"
: /* no output registers */
: "r" (&g)
: "%ebp", "%esp"
);
}
int main (int argc, char *argv[])
{
f();
return 0;
}
Understanding how this code works can lead to a better understanding of how a function's stack frame is setup for a particular architecture which forms the basis of buffer overflow techniques.

Resources