[Cocci] Checker - request for comments

Robert Gomulka r.gom1977 at gmail.com
Wed Jan 11 09:14:59 CET 2012


Hi all,
I have written a checker for use invalid pointer. Common use case was:
- free(a); ... a->something
- realloc(a, ...); ... a->something // but not a = realloc(a, ...),
not considering fail condition here

This is something I came up with:
@@
expression E, E2;
identifier fld;
@@

(
 realloc(E, ...);
|
 free(E);
)

 ...

(
 E = E2;
|
- *E
+ E = NULL
|
- E[...]
+ E
|
- E->fld
+ E
)

The question is ... how does it work? I mean, for the following piece of code:
    int *c = NULL, *d;
    int *e = NULL, *f;
    d = c + 1;
    c = realloc(c, 0);
    *c = 1;
    d[1] = 5;
    realloc(e, 0);
    *e = -5;

it correctly produces:
     *c = 1;
     d[1] = 5;
     realloc(e, 0);
-    *e = -5;
+    e = NULL = -5;
     if (a != 4 || a != 5) {
         printf("rrr");
     }

not touching c, as expected. How does it know that it should skip that
line? How could I extend it to catch line, where realloc is assigned
to another variable and supposedly lost, like:
int *n = realloc(c, 0)? I've tried adding another expression E1 and
line E1 = realloc(E, ...) to alternatives list, but then it acts even
when E = E1.

I have written something similar for case:
int *a = ..., *b;
b = a;
realloc(a, ...);
*b // or b[] or b->...
using copy of invalid pointer:

@@
type T;
T *a;
T *b;
@@

(
b = a
|
b = &a[...]
|
b = a + ...
|
b = a - ...
)

...

(
realloc(a, ...)
|
free(a)
)

... when != b = ...

// yes, that replace code should be improved
- b
+ *b


Is my approach correct? Can those checkers be integrated? Can those be improved?
Of course generated patches are incorrect, I just wanted to spot
invalid places and it's somehow easier for me to see -+ lines instead
of - line in case of *.

Best regards,
Robert


More information about the Cocci mailing list