[cocci] Adding an attribute to struct pointer in function parameter
Pierrick Philippe <[email protected]> Wed, 17 Jun 2026 09:29:52 +0200
| Newsgroups | fr.inria.cocci |
|---|---|
| Message-ID | <[email protected]> |
Hi everyone,
I recently send some mail on this mailing list, and my goal was to use
Coccinelle to automatically annotate some variables or parameters for
our analyzer.
Just to recall, our attribute have an optional parameter corresponding
to a field of interest when the annotated object is a structure.
That parameter should also be a string.
There was some limitations due to character escaping with Coccinelle to
apply the following patch:
```cocci
+struct foo f = {42, 42};
-struct foo __attribute__((myattr("x"))) f = {42, 42}
```
A workaround was to go through a python script to build the string
holding the whole attribute (including the optional parameter between
quotes).
Unfortunately, I can't find a way to apply the same logic to a
function's parameter.
Here is the test code:
```C
#include <string.h>
struct foo {
int x;
int kdiedexko;
int y;
};
int foo(struct foo *ptr, int y) {
int z = memcmp(&ptr->x, &y, sizeof(int));
return z;
}
```
And here is my patch:
```cocci
@searching_struct_param_begin@
expression E1, E2;
identifier F, X;
type T, T1;
identifier S;
parameter list[n = { 0 ... 7 }] p;
@@
T1 F(T *S, p)
{
...
(
memcmp(&F->X, E1, E2)
|
memcmp(E1, &F->X, E2)
)
...
}
@script:python generation_struct_param_begin@
s << searching_struct_param_begin.S;
x << searching_struct_param_begin.X;
content;
@@
coccinelle.content = cocci.make_ident("__attribute__((myattr(\"" + x +
"\"))) *" + s)
@replacement_struct_param_begin@
expression searching_struct_param_begin.E1, searching_struct_param_begin.E2;
identifier searching_struct_param_begin.F,
searching_struct_param_begin.X, generation_struct_param_begin.content;
parameter list[n = { 0 ... 7 }] searching_struct_param_begin.p;
type searching_struct_param_begin.T, searching_struct_param_begin.T1;
@@
T1 F(
-T *S,
+T content,
p)
{
...
(
memcmp(&F->X, E1, E2)
|
memcmp(E1, &F->X, E2)
)
...
}
```
The semantic patch is valid, but for some reason, no patch is generated
by Coccinelle and I can't figure out why.
Anyway, thank you for reading me again.
Have a good day,
Pierrick