Cmocka: checking a structure passed as a parameter - c

Let's say that I declare a C struct called foo, which has an int field called bar and a char * called baz.
How do I use the Cmocka expect_ and check_expected macros to check that the structure passed was correct and both fields have the expected values? If there is an example in the documentation, I missed it.
[Update] Perhaps I can use expect_check()? But I can't find an example :-(

Use expect_memory(...) and check_expected(...):
Example:
I assume you have a function under test fut which calls a subfunction subfunc. Your struct looks like this:
typedef struct foo_s {
int bar;
int baz;
} foo;
And your test driving function could look like this:
void test(void **state) {
foo myfoo = {
.bar = 42,
.baz = 13,
};
expect_memory(subfunc, param, &myfoo, sizeof(foo));
fut();
}
And the subfunctions could look like this:
void subfunc(foo *param){
check_expected(param);
}

Comparing the memory of the struct might work in most cases, however if your compiler puts some filler bytes in there, you have some bytes which you have no controll over and might have random values. This means that your test might not alway yield the same result, which can lead to very annoying debugging session.
For example if you have a struct like this:
typedef struct {
uint8_t c;
uint32_t i;
} tSomeStruct
You might think that the c and i are put right next to each other and sizeof( tSomeStruct ) returns 5. However if you try this out you would be surprised that it is more likely that sizeof( tSomeStruct ) actually returns 8. This is because of the mentioned filler bytes. You do not know what the values of these other bytes are. You can work around this by memsetting your structs to 0 before using them, however this is a little bit hacky and does not work in every case.
To compare structs in a clean way cmocka you can use expect_check( ... ) and check_expected( ... ). This gives you the possibility to write your own comparisson function.
Here is an example on how to use this ( Modified this example: Cmocka Gitlab )
typedef struct {
char c;
int i;
} tSomeStruct;
void mock_function( tSomeStruct* param )
{
check_expected(param)
}
/* return 1 = true, return 0 = false */
int my_int_equal_check(const LargestIntegralType value,
const LargestIntegralType check_value_data)
{
tSomeStruct* cast_value = ( tSomeStruct* ) value;
tSomeStruct* cast_check_value_data = ( tSomeStruct* ) check_value_data;
if ( ( cast_value->c == cast_check_value_data->c )
&& ( cast_value->i == cast_check_value_data->i ) ) {
return 1;
}
return 0;
}
void mytest(void **state)
{
tSomeStruct struct = {
.c = 'c',
.i = 'i',
}
expect_check(mock_function, param, my_int_equal_check, &struct);
}
I am not sure however if this is possible, if you do not pass your struct as a pointer to your function, as the check function only takes LargestIntegralType.

I recently found out that you can use the struct members inside the check_expected and expect_value:
typedef struct
{
int a;
float b;
} SomeStruct_t;
void mocked_function(SomeStruct_t* s)
{
check_expected(s->a);
check_expected(s->b);
}
void someTest(void **state)
{
expect_value(mocked_function, s->a, 3);
expect_value(mocked_function, s->b, 7.2);
// ...
}

Related

Inline functions, macros and other solutions to allocate on caller's stack

I have a lot of code that looks like this:
int bufferSize = fooBufferSize(); // hate having to do this; this logic should be in `foo`
char buffer[bufferSize];
foo(buffer);
bar(buffer);
It happens all the time for me. In the wild, I see something similar a lot:
int bufferSize = snprintf(NULL, 0, format, ...); // exact same issue as above
char buffer[bufferSize+1];
sprintf(buffer, format, ...);
Besides the fact that the above are tedious for the user to write, they also probably redo a lot of computations, which is not only inefficient, but it isn't DRY. I know that I could just malloc the buffer within foo, but there's a lot of issues with that: memory fragmentation, remembering to call free, overhead of malloc/free.
char *foo() {
char *buffer = malloc(...);
// process the data in the buffer
return buffer;
}
main() {
char *buffer = foo();
bar(buffer);
}
There are a lot of cases where I probably would use malloc (or a buffer pool) for things that are constantly removed and deleted (e.g. projectile objects in a game). However, the case that comes up a lot for me is that I want to allocate an object on the stack and then dispose of it when my function returns. The issue is that the object is generally allocated in a stack frame further down from the stack frame I want the object to live in. I'd prefer if I could just build on-top of the stack that foo uses. Like, what if I did this instead:
void foo(char **bufferPtr) {
char buffer[...];
// process buffer
*bufferPtr = buffer;
jmp __builtin_return_address(0); // pseudocode to jump to return address
}
main() {
char *buffer = NULL;
foo(&buffer);
bar(buffer);
}
I don't even know the exact syntax to make this approach work, but it is both GCC-specific and extremely hacky. In addition, if the jump isn't understood by the compiler, local variable states might not be restored properly. I guess, what I really want is for foo to behave like a macro, e.g. like this:
#define foo(buffer) \
char buffer[4]; \
strcpy(buffer, "hey");
int main() {
foo(buffer)
bar(buffer);
}
However, I really don't like using macros (terrible error messages, bad IDE support, slippery slope, etc.)
The macro above looks nice, but in my current usecase, I'm building a computation graph (similar to TensorFlow), and some of the node constructors would look really awkward using macros.
typedef struct {
float *data; // buffer to store output data of computation
int order; // number of dimensions
int *dimensions; // e.g. [3,4] for a 3x4 matrix
} Node;
typedef struct {
Node super; // it's still a node, so just pass a ref to this whenever you need a Node*
Node *A;
Node *B;
} MatMulNode;
void printMatrix(const char *name, Node *node) {
assert(node->order == 2);
printf("%s: [%d x %d]\n", name, node->dimensions[0], node->dimensions[1]);
}
// look at all these backslashes
// also, `return -1` might not make sense in the context this macro is used.
#define matmul(node, left, right) \
if (left.order != 2 || right.order != 2) {\
return -1;\
}\
if (left.dimensions[1] != right.dimensions[0]) {\
return -1;\
}\
int dimensions[2];\
dimensions[0] = left.dimensions[0];\
dimensions[1] = right.dimensions[1];\
float data[dimensions[0] * dimensions[1]];\
MatMulNode node = {\
.super = {\
.data = data,\
.order = 2,\
.dimensions = dimensions,\
},\
.A = &left,\
.B = &right,\
};
int main() {
Node A = {
NULL,
2,
(int[]) {1, 2}
};
Node B = {
NULL,
2,
(int[]) {2, 3}
};
matmul(C, A, B);
printMatrix("A", &A);
printMatrix("B", &B);
printMatrix("C", &C.super);
}
I'm honestly surprised by how well this works, but I also hate the fact that I have to use macros for it and refuse to believe that this is the best API I can make which avoids malloc.
I tried using inline functions, but inline is just a suggestion unless I'm using the always_inline attribute (but that's GCC only), and AFAICT, it doesn't seem to work with alloca. I'm not even sure if the below code has defined behavior, or if I'm just getting lucky:
static inline __attribute__((always_inline)) Node *matmul(Node *left, Node *right) {
if (left->order != 2 || right->order != 2) {
return NULL;
}
if (left->dimensions[1] != right->dimensions[0]) {
return NULL;
}
int dimensions[2];
dimensions[0] = left->dimensions[0];
dimensions[1] = right->dimensions[1];
float data[dimensions[0] * dimensions[1]];
MatMulNode node = {
.super = {
.data = data,
.order = 2,
.dimensions = dimensions,
},
.A = left,
.B = right,
};
return &node.super;
}
The final approach I know of is to use continuation-passing style, e.g.
void matmul(Node *A, Node *B, void callback(void *, Node *C), void *context) {
MatMulNode C = ...;
callback(context, &C.super);
}
The obvious tail-call optimization of this approach is nice, and the fact that the stack is obviously preserved would make it much less hacky than things like jmp, but the API that it presents to the user is really ugly. For example, what if I want to do matmul(A, matmul(B, C))? The code I'd have to write is extremely counter-intuitive, especially because I have to pass in a context variable to the callbacks, when they should Ideally just have access to the entire stack and choose whatever variables they need from there.
void callbackABC(void *context, Node *ABC) {
assert(ABC->order == 2);
printf("A(BC) is [%d x %d]\n", ABC->dimensions[0], ABC->dimensions[1]);
}
void callbackBC(void *context, Node *BC) {
Node *A = context;
matmul(A, BC, callbackABC, NULL);
}
int main() {
Node A = {
NULL,
2,
(int[]) {1, 2}
};
Node B = {
NULL,
2,
(int[]) {2, 3}
};
Node C = {
NULL,
2,
(int[]) {3, 4}
};
matmul(&B, &C, callbackBC, &A);
}
Overall, I think that inline functions are the closest thing to what I want, but rather than ask "How do I force a function to always inline?" I figured I'd ask with the full context of what I want to achieve and why none of my solutions work.
I'm not recommending it, but also you may want to take a look at the __attribute__ cleanup(freefunc) feature in gcc. Basically handles cleanup when the associated variable leaves scope.

Using a switch to map function pointers to strings

I'm working on a network service that based on commands it receives over the network, it has workers perform different jobs. I want to have a log entry for every time a certain worker is tasked with doing some job.
I have a function (say function_caller) which, among other things, calls another function which it receives its pointer as an argument. I'd like to have my logger notify what kind of function function_caller calls.
Originally I wanted the function_caller to receive some enum instead of a function pointer, provide the enum to the logger, and then use a helper function which returns a suitable pointer based on the enum. However, function_caller is already deeply tangled in the codebase I'm working on, and it looks like it would be a lot of work to refactor all the functions that call function_caller to choose the right enum and use a new argument.
So my next idea was having a switch that for every function pointer will have some string representation of, but I've never stumbled upon something like that (and struggled to find anyone even mentioning such an idea on Google), so I have a feeling I might be missing some serious downsides to this option.
The only significant problem I see is that every developer that decides to pass a new kind of function pointer to function_caller will have to somehow know to update the switch, otherwise it will fail.
Am I missing anything else? Or maybe there's some other approach I should consider?
How about something like this? Instead of a switch, store a table of functions and their name strings. The table can even be kept dynamically updated, unlike a switch case. You will not need to walk along the edge of the standard as well!
#include <stdio.h>
typedef void (*callback_t) (void);
void first (void) { printf("%d", 1); };
void second (void) { printf("%d", 2); };
void third (void) { printf("%d", 3); };
typedef struct fntable_t
{
callback_t fn;
char *name;
} fntable_t;
fntable_t fntable[] =
{
{ first, "first" },
{ second, "second" },
{ third, "third" }
};
char* log_str(callback_t c)
{
for(int i = 0; i < sizeof(fntable) / sizeof(fntable_t); i++)
{
if(fntable[i].fn == c)
return fntable[i].name;
}
return "unknown";
}
void function_caller(callback_t c)
{
printf("%s",log_str(c));
c();
}
int main(void)
{
function_caller(first);
function_caller(second);
function_caller(third);
return 0;
}
You could replace function_caller with a wrapper macro of the same name that calls the renamed function function_caller_internal which gets an additional string argument. The wrapper macro can then pass an additional stringified function name.
This works only if function_caller is always called with a function name, not a function pointer variable.
Example:
#include <stdio.h>
static void funcA(void)
{
printf("This is funcA\n");
}
static void funcB(void)
{
printf("This is funcB\n");
}
/* renamed function gets an additional string argument */
static void function_caller_internal(void (*func)(void), const char *name)
{
printf("calling %s\n", name);
func();
}
/* wrapper macro stringifies the function name to pass it the additional argument */
#define function_caller(func) function_caller_internal(func, #func)
int main(void)
{
/* unchanged calls */
function_caller(funcA);
function_caller(funcB);
return 0;
}
This prints
calling funcA
This is funcA
calling funcB
This is funcB
If you can change the API of the functions, then consider using __func__ to get the textual name of each function. If you can have a function pointer type along the lines of this:
typedef void func_t (const char** name);
Then you can have each function return its name to the caller.
void foo (const char** name)
{
/* do foo stuff here */
*name = __func__;
}
void bar (const char** name)
{
/* do bar stuff here */
*name = __func__;
}
Example:
#include <stdio.h>
typedef void func_t (const char** name);
void foo (const char** name)
{
/* do foo stuff here */
*name = __func__;
}
void bar (const char** name)
{
/* do bar stuff here */
*name = __func__;
}
const char* function_caller (func_t* func, const char** name)
{
func(name);
return *name;
}
int main(void)
{
static func_t*const func [] =
{
foo,
bar,
};
const char* name;
for(size_t i=0; i<sizeof func/sizeof *func; i++)
{
puts( function_caller(func[i], &name) );
}
}
Assuming your codebase has sane variable names and function names, you can add a char * argument to your function caller:
void function_caller(char *name, int fpnt());
and then provide a macro:
#define function_caller_autoname(fpnt) function_caller(#fpnt, fpnt)
(Or, for spaghetti code, you can provide a macro with the same name as the function).
The #fpnt will be expanded by the proceprocessor to a string literal with the function name.
Then when your codebase called:
function_caller(some_function)
refactor it to:
function_caller_autoname(some_function)
# will be expanded to by the processor:
# function_caller("some_function", some_function)
or refactor it manually to provide the name/identificator/description of the function:
function_caller("Some function: ", some_function)
That way you can pass a custom string that describes the function along with the pointer. Also, each developer can pass a custom description string.

Static array initialization in C

Consider the following statements
typedef struct {
int member1;
int member2;
}Custom_t;
void ISR(void)
{
static Custom_t struct1[SOME_CONSTANT];
......
......
}
How can I initialize all member2 variable to a single value in C programming?
If I iniatilize the structure like the one shown below, then there is chance of somebody changing the "SOME_CONSTANT" in a header file and forgetting to update the list.
Another solution would be to give the structure a global scope for the current file. But the only function which uses the structure is the ISR().
void ISR(void)
{
static Custom_t struct1[SOME_CONSTANT] = {
{0, 3},
{0, 3},
......
......
};
......
......
}
Is there any method to solve this problem in C?
You can use Designated Initializers and do it in this way:
#include <stdio.h>
#define SOME_CONSTANT 30
typedef struct {
int member1;
int member2;
} Custom_t;
int main(void)
{
static Custom_t struct1[SOME_CONSTANT] =
{
[0 ... SOME_CONSTANT - 1].member2 = 30
};
printf("%d\n", struct1[25].member2);
printf("%d\n", struct1[19].member2);
printf("%d\n", struct1[0].member2);
return 0;
}
How about to add hard-coded compiling time checking against SOME_CONSTANT in the .c file (e.g. right before the initializer)?
#if SOME_CONSTANT != <some_hard_code_value>
#error "SOME_CONSTANT is not equal to <some_hard_code_value>"
#endif
The rational of this "hard-code" is whenever the SOME_CONSTANT is changed, the initializer need be updated, as well as the compiling time checking.
You don't need to specify the array size in advance, you can compute it later:
static Custom_t struct1[] = {
{0, 3},
{0, 3},
{13,3},
};
#define SOME_CONSTANT (sizeof struct1 /sizeof struct1[0])
or: use __LINE__ to compute the number of elements.
I've had to do something like this with projects with a configurable number of sensors :
[custom_t.h]
typedef struct {
int member1;
int member2;
}Custom_t;
#define MAX_CUSTOM_T 4
Custom_t *new_Custom_t (int member1, int member2);
[custom_t.c]
#include "custom_t.h"
static Custom_t g_Customt[MAX_CUSTOM_T];
static uint8 g_numCustom_t = 0;
Custom_t *new_Custom_t (int member1, int member2)
{
if ( g_numCustom_t < MAX_CUSTOM_T )
{
Custom_t *new_obj = &g_Customt[g_numCustom_t++];
new_obj->member1 = member1;
new_obj->member1 = member2;
return new_obj;
}
else
{
// throw exception?
// or go into while(1)?
// or software breakpoint if debug?
// or just...
return NULL;
}
}
[main.c]
#include "custom_t.h"
Custom_t *myCustom1;
Custom_t *myCustom2;
Custom_t *myCustom3;
somefunc()
{
myCustom1 = new_Custom_t (0,3);
myCustom2 = new_Custom_t (1,3);
myCustom3 = new_Custom_t (2,3);
// do stuff
}
It means if you want to create a new one, you may or may not need to update MAX_CUSTOM_T depending on its size already, but will just have to add a new line call to new_Custom_t(int,int). A Disadvantage though is it is slightly complex for what you might need, and if you ever want to add more members to initialize, you'll need to update the parameters passed into the new_ function to suit. This can be done instead with a sending a single separate structure for parameters rather than multiple parameters (a bit like MPLAB harmony).

C accessing structures in different files with pointers - dereferencing pointer to incomplete type

I can't find a solution with the following C code
I have 3 files as follows:
1) story1.c
where
struct Example1
{
int first_element;
int second_element;
...
};
int function1(Example1 *m, ...)
{
...
m->first_element = m->second_element;
m->second_element = /* changing int data */;
return /* other integer */;
}
2) story1.h
where
typedef struct Example1 Example1;
3) story2.c
where
typedef struct Example2 {
Example1 *ptr;
int res2;
...
} Example2;
[...]
static void mother_function(Example2 *s)
{
int res;
res = function1(s->ptr, ...);
}
static void last_function(Example2 *s)
{
if ( ( &(s->ptr)->first_element == 10 ) &&
( (((*s).ptr).second_element) == 44 ) &&
/* other conditions */ )
s->res2 = /* new value */;
}
mother_function calls function1 which sets m->first_element and m->second_element, e.g. 10 and 44
now I would like last_function to access these new born [in function1 of another file] values starting from pointer s to evaluate the if [conceptually speaking I would like to do something like:
if( (s->ptr->first_element==10) && (s->ptr->second_element==44) ) then...
I tried to write in 3 ways to get it done:
1) s->ptr->first_element
2) ( &(s->ptr)->first_element == 10 )
3) ( (((*s).ptr).second_element) == 44 )
and compiler gave me the following errors:
1) error: dereferencing pointer to incomplete type
2) error: dereferencing pointer to incomplete type
3) error: request for member ‘second_element’ in something not a structure or union
What is the reason of these messages and how can I practically fix this issue?
Thanks in advance to those who will try to help
You need to move the struct Example1 { ... }; lines from story1.c to story1.h (and make sure story2.c includes story1.h) so that story2.c will have access to the definition of struct Example1. Then writing s->ptr->first_element should work.
Just add some explanation to Jwodder's solution: s->ptr->first_element is trying to access the member of struct Example1, however, struct Example1 is defined in story1.c so it's invisible to story2.c.
See http://en.cppreference.com/w/c/language/scope

Setting struct variables - C

I have some code in the following kind of layout, I believe that the topExample/botExample aren't being set properly when I call addTopBotExample. I think this is due to the top bot variables being on the functions stack and so being cleared when the function ends? I have a feeling that perhaps I need to malloc the memory first, but am not sure how I would go about doing this are even if its the right approach.
typedef struct Example Example;
struct Example {
/* normal variables ...*/
Example *topExample;
Example *botExample;
};
....
void addTopBotExample(Example **example, int someVariable) {
Example top = createTopExample(int someVariable); //(createTopExample returns a
//type Example based on some input)
Example bot = createBotExample(int someVariable);
(*example)->topExample = &top;
(*example)->botExample = &bot;
return;
}
If createTopExample isn't allocating memory, this is going to cause problems the moment it's called more than once. Rewrite createTopExample and createBotExample to use malloc and return an Example*. Something like this:
Example* createTopExample(stuff)
{
Example *example = malloc(sizeof(Example));
// ... stuff you do
return example;
}
Then your addTopBotExample would look like this:
void addTopBotExample(Example **example, int someVariable) {
if ((*example)->topExample)
free((*example)->topExample)
if ((*example)->botExample)
free((*example)->botExample)
(*example)->topExample = createTopExample(int someVariable);
(*example)->botExample = createBotExample(int someVariable);
return;
}
Note that this addTopBotExample will free the allocated memory before calling malloc again but before your program ends, you need to call free on any lingering Examples that used this addTopBotExample function:
free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.topExample);
free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.botExample);
You have already everything together. Allocate the Example in createTopExample or createTopExample
Example *createTopExample(int someVariable)
{
Example *x = malloc(sizeof(Example));
/* initialize x */
return x;
}
and in addTopBotExample
void addTopBotExample(Example *example, int someVariable) {
Example *top = createTopExample(int someVariable); //(createTopExample returns a
//type Example based on some input)
Example *bot = createBotExample(int someVariable);
example->topExample = top;
example->botExample = bot;
return;
}
Ooooo, this is bad. The expression "Example top" in the addTopBotExample() function allocated that object on the stack. It'll be trashed after exiting from the function. (Same for "Example bot" on the following line.) Something like this will work better:
void addTopBotExample(Example **example, int someVariable) {
Example *top = createTopExample(someVariable); // NOTE THE *
Example *bot = createBotExample(someVariable); // NOTE THE *
(*example)->topExample = top; // NOT &top !!
(*example)->botExample = bot; // NOT &bot !!
return;
}
And you'll want to write createTopExample and createBotExample so they return pointers:
#include <stdlib.h> // For malloc!
Example *createTopExample(stuff) // Note *. It's returning a pointer.
{
Example *example = malloc(sizeof(Example)); // Allocate on the HEAP. Lives after this function call.
// Fill in the fields of example.
example->field1 = 25; // Note the "->": you're dereferencing a pointer.
example->title = "Example title";
return example;
}

Resources