Verify function pointer equality with Cmockery - c

I am writing Unit test and wondering how would I test function pointers with Cmockery.
A.c
void (*FunctionPtr)(void) = &funcA;
void funcA()
{
// calls func B
funcB();
}
TestA.c
void Test_A( void ** state )
{
// test for FunA; working as expected
}
void Test_FunctionPtr( void** state )
{
// how to check here that FunctionPtr holds memory location of funcA?
// I tried something like below:
assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) );
}
During runtime I am getting error and I have no clue how to resolve that. May be I using wrong API to assert but don't know which one to call.
Below is my error:
error during runtime:
Test_FunctionPtr: Starting test
No entries for symbol funcB.

funcA() calls the function. You want a pointer to the function, which is funcA or &funcA (does not make a difference which one you use: read here).
Also you want to compare the value saved in FunctionPtr with the address of funcA. You do not want to compare the memory where FunctionPtr points to with the function.
So instead of assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) ); I would use assert(FunctionPtr == funcA);
You wrote in your comment that you are using assert_int_equal now. Note that both values are not int, so if the macro uses printf with %d (or similar) in an error case you are invoking undefined behaviour.

Related

Allocated memory in multiple cmocka unit tests

I'm trying to unit test some source code using cmocka. Basically the (relevant) source code looks similar to Source.c.
The unit test calls each function separately. When testing the Add() function this function will eventually call util_malloc() (this function normally checks for 0 size before malloc) which is wrapped by the unit test. In the wrapped function __wrap_util_malloc(), in Wrappers.c, first the size is checked for expected after which malloc is used to allocate memory.
Next the Remove() function is tested in which the previously allocated memory gets freed.
When running the test cmocka returns with the following failures:
<failure><![CDATA[Blocks allocated... project_path/wrappers.c:46: note: block 00341e58 allocated here ERROR: Add_Test leaked 1 block(s) ]]></failure>
and
<failure><![CDATA[EXCEPTION_ACCESS_VIOLATION occurred at 004060af.
To debug in Visual Studio... [...]
]]></failure>
For now I've added a Remove() call at the end of the Add_Test() function (and an Add() at the beginning of Remove_Test()). This seems to fix the issue. Judging from this, one should free all allocated memory in each separate unit test.
Now my questions:
Is it possible to use allocated memory in multiple unit test?
What would be the best way to solve this?
Source.c:
static ST_SOME_STRUCT GlobStruct;
void Add()
{
GlobStruct = util_malloc(sizeof(ST_SOME_STRUCT));
}
void Remove()
{
util_free(&GlobStruct);
}
void DoStuff()
{
//Do stuff using the global structure GlobStruct
}
Unit_test.c:
int main( int argc, char **argv )
{
const struct CMUnitTest Test[] =
{
cmocka_unit_test(Add_Test),
cmocka_unit_test(Remove_Test),
};
cmocka_set_message_output( CM_OUTPUT_XML );
return cmocka_run_group_tests( Test, NULL, NULL );
}
static void Add_Test (void** state)
{
expect_value(__wrap_util_malloc, size, sizeof(ST_SOME_STRUCT ));
Add();
}
static void Remove_Test (void** state)
{
expect_not_value(__wrap_util_free, memory, cast_ptr_to_largest_integral_type(NULL));
Remove();
}
Wrappers.c:
void *__wrap_util_malloc(int size)
{
check_expected(size);
return malloc(size);
}
void __wrap_util_free(void *memory)
{
check_expected_ptr(memory);
free(memory);
}
When running tests using cmocka_run_group_tests, cmocka will still run individual setup or teardown functions for each test, along with its internal functions which check if you forgot to free blocks (hence the message Add_Test leaked 1 block(s)). After each test, cmocka will also free any blocks allocated inside that test before running the next one.
Common approach is that each of your tests should perform cleanup of anything allocated within that single test. If you want to initialize shared state at the beginning of the group test, specify group setup/teardown functions to initialize shared state (which will be passed to each unit test as a parameter), or use test setup/teardown functions to be called before each test.
As always, it's a bad idea (and makes testing harder) to have global shared variables. Your Add and Remove functions (and all other dealing with this object) should accept a pointer to the struct containing the data.

Function callback from C to Swift

I have this C function that simply calls back another function passed as a parameter
void call_my_function(void (*callback_function)())
{
callback_function();
}
This is C test code:
void func_to_call() // a simple test function passed in as a callback
{
printf("function correctly called");
}
void test() // entry point
{
void (*foo)();
foo = &func_to_call;
call_my_function(foo); // pass the address of "func_to_call()" to "call_my_function()"
}
Essentially, from test(), I call call_my_function() passing in the address of func_to_call(), and then call_my_function() calls back func_to_call().
From swift I see correctly the functions test() and func_to_call(), but it seems that
void call_my_function(void (*callback_function)())
is not recognized (use of unresolved identifier)
If I remove the parameter void (*callback_function)() then the function is recognized again.
What can I do to pass a Swift function address to C and have it called back? Is it possible?
Thanks
Apple confirmed me, on the dev forum, that it is not supported now, and requested me to fill a new request on the bugreporter.
Moreover, I give to the readers another detail:
It seems that in the compiled binary the symbols for all swift functions are already available and bridged to be accessible from C (even in a swift-only app)
I made an app called FunctionTest, iPhone App with this function in a swift file
func thisIsATestFunction()
{
println("test")
}
compiled, and then from Terminal:
nc /Users/xxx/Library/Developer/Xcode/DerivedData/FunctionTest-hhrbtzsuyrdoftfnbakosvenaiak/Build/Products/Debug-iphonesimulator/FunctionTest.app/FunctionTest
U _NSStringFromClass
U _OBJC_CLASS_$_NSString
U _OBJC_CLASS_$_UIResponder
U _OBJC_CLASS_$_UIViewController
U _OBJC_CLASS_$_UIWindow
000088c8 S _OBJC_CLASS_$__TtC12FunctionTest11AppDelegate
00008888 S _OBJC_CLASS_$__TtC12FunctionTest14ViewController
.........
.........
00003840 T __TF12FunctionTest19thisIsATestFunctionFT_T_ <--- this is my test function
Calling from c the address 00003840 executed the function
void (* func)() = 0x00003840;
func(); // the swift function is executed
So I think that this is already work-in-progress...hoping that they will implement this functionality in the next releases :-)

How to invoke invalid handler function like gets_s() does?

I used the following code to invoke an invalid parameter handler if the user enters more than 4 characters.Actually it's the gets_s() function which invokes the handler.
...
char arr[5];
_invalid_parameter_handler newHandler;
newHandler = myInvalidParameterHandler;
_set_invalid_parameter_handler(newHandler);
gets_s(arr,4);
...
}
void myInvalidParameterHandler(const wchar_t* expression,const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved)
{
...
}
Now, my question is how gets_s() calls/invokes the handler internally?I am asking this because I want to do something similar in my program.For eg. lets say I have a function declared like-
EDIT:
If when running the above code the user enters more than 4 characters then the handler is invoked.If I comment out the invalid handler related code then my program will crash.The same I want to achieve.
If some one uses my function he should get same behavior as I get when using gets_s.Please don't suggest this is good or bad.I just want to learn it.gets_s doesn't know which handler func I am gonna set.Similarly my function doesn't know which invalid handler func the user will set.I think there might be some C runtime global variable of type _invalid_parameter_handler which the '_set_invalid_parameter_handler()' func sets which gets_s uses.
In my opinion 1 and 3 are the same, and yes you could do it like that. Have all your functions call a function pointer in some global struct and you're set.
Set up a global object that contains a function pointer and some bookkeeping dat
When a function detects something wrong it can call the handler
But don't do it. It's way better to return an error status than to automatically call a function when something "feels" wrong. Then you can check the return status and act on it, instead of some automatic handler taking over.
EDIT
From your comment I believe you don't know about function pointers.
/* here is the handling function */
void handler(char *msg)
{
fprintf(stderr, "%s\n", msg);
}
void (*err_handler)
void some_function_like_gets(void *arg)
{
if (NULL == arg) {
(*err_handler)("Oh noes! You passed a NULL pointer :(");
return;
}
}
int main()
{
/* ... */
/* setting up handler */
err_handler = handler;
/* calling function */
some_function_like_gets(NULL);
/* ... */
}
EDIT 2
The sad part is that you downvoted this even though the MSDN page says:
[in] pNew The function pointer
to the new invalid parameter handler.

I need to call the functions by directly by giving function base address to PC with parameters......how?

void fun1(int x)
{
display(x);
display(x+1);
display(2*x);
}
void fun2(int x)
{
display(x*3);
display(x+3);
display(x-1);
}
void fun3(int x)
{
display(x+2);
display(x+5);
}
.
.
.
.
function_ptr[]={fun1,fun2,fun3,.......fun20};
int st=0;// to indicate the function count
int main()
{
GLCD_init();
//comment here
}
comment is as
after GLCD initialisation i have to call above functions.So, now my problem is...take a condition..if st=3 then i have to execute fun2,fun3,fun4,fun5 ..with condition statements i can..but with the help of st value i have call those functions directly..for that i am using assembly language so that we can give our function address to PC directly...here i am facing a problem with passing parameters..once we made a call to function by giving the base address of that perticular function to PC...how can i pass the parameters to those functions with along with the direct call...
This depends completely on your system: some system pass the parameters register only, some in stack, some mix (e.g. only small or first values in regs).
See as reference Arm Procedure Call Standard
If you are unsure how your system handle it, just dissassemble a procedure call to one of your functions, to see how it is done.

Is this a good way for unconditional jump?

I have a function f( ) in a file func.c and functions f1( ), f2( ), f3() , f4( ) in another file funcs.h. (Assume that all the functions receive/return values without any loss of generality).
Function f( ) calls f4( )
f4( ) calls f1( ), f2( ), f3( ) in some arbitrary order, among themselves
At some point of time during the execution, f3() detects the completion of the algorithm and it has to "terminate" the execution of the algorithm. In a standalone case, it should exit out of the program after printing the solutions.But here, I need f3( ) to return to f( ).
This is my solution:
In this scenario, I cannot simply return to f4() (the original function called by f(), since there is already a function call stack of f1(), f2(), f3(),f4(), waiting to be "popped"). So, what I did is:
I did a setjmp( ) in f() before calling f4( )
And then, I did a longjmp( ) in f3( ) when I detected the completion of the algorithm
My question is: Is this the correct way to achieve this in this scenario?
TBH I personally find its better to return a bool from the function and if the return is true then return true from the function below and so on until it gets back to the original function. This unwinds the stack correctly, which im not sure setjmp/longjmp does.
In general though if you aren't going to go on and do stuff after the f() function returns it should work anyway. I'd just argue its not a very good way to do things as someone reading the code will not find it as obvious as the functions returning bool back up the stack.
You can use getcontext/setcontext. They may be viewed as an advanced version of setjmp/longjmp; whereas the latter allows only a single non-local jump up the stack, setcontext allows the creation of multiple cooperative threads of control, each with its own stack.
Also refer to other related calls such as makecontext(), swapcontext().
Here is one sample code to show how to use these functions (Sorry for bad coding). Hope this helps you.
#include <stdio.h>
#include <ucontext.h>
void func(void);
int x = 0;
ucontext_t context, *cp = &context;
int main(void) {
getcontext(cp);
if (!x) {
printf("getcontext has been called\n");
func();
}
else {
printf("setcontext has been called\n");
}
}
void func(void) {
x++;
setcontext(cp);
}
Output:
getcontext has been called
setcontext has been called
f4( ) calls f1( ), f2( ), f3( ) in some arbitrary order, among themselves
What do you mean by "arbitrary order"? Unless you're writing a multi-threaded program, the order in which 1,2, and 3 are called should be deterministic; functions are executed synchronously in C.
You didn't mention what you are doing or what algorithm are you implementing but...
You could use a global structure with function pointers which f1,f2,f3,f4 knows it existence and from f4() you call f1() doing something like:
global.functionPointers[0]("parameters.for.f1");
Don't you still need a flag to know that you shouldn't call f4 again the second time?
int solution_found=0;
f(){
setjmp();
if (!solution_found)
f4();
/* continue here... */
}
Apart from that, setjmp/longjmp may be expensive calls. They also have a price in terms of readability of your program. I would certainly consider having f1,... pop themselves out of the stack the normal way instead, if I was you.
I would do it something like this:
struct solution { ... }
solution *f() {
solution *result;
if (something) {
result = f3();
if (result != NULL)
return result;
}
else {
result = f3();
if (result != NULL)
return result;
}
return f();
}
Or whatever your algorithm might be.

Resources