User: Password:
|
|
Subscribe / Log in / New account

Semantic patching with Coccinelle

Semantic patching with Coccinelle

Posted Feb 3, 2009 13:56 UTC (Tue) by robbe (subscriber, #16131)
Parent article: Semantic patching with Coccinelle

I was a bit disheartened to see the example code transformed into code
that leaks (remember that memory reserved with alloca() is automatically
freed, malloc() does not have this property).

All the while I was hoping to see a third run of the tool which added the
missing free() call before every return statement. Is that possible with
Coccinelle?


(Log in to post comments)

Semantic patching with Coccinelle

Posted Feb 3, 2009 21:27 UTC (Tue) by padator (guest, #56235) [Link]

Nice catch :)

Yes coccinelle can do that too.
Here is an example of a better semantic patch:

@@
expression E;
identifier ptr;
identifier func;
@@
func(...) {
...
- ptr = alloca(E);
+ ptr = malloc(E);
+ if (ptr == NULL)
+ return 1;
...
+ free(ptr);
return ...;
}

Note that the coccinelle engine will take care to add the call to free() to all control flow paths before a return. Here is an example of a patch produced by spatch on a simple C file:
./spatch -sp_file demos/lwn.cocci demos/lwn.c

--- demos/lwn.c 2009-02-03 15:10:38.000000000 -0600
+++ /tmp/cocci-output-22113-f80295-lwn.c 2009-02-03 15:15:05.000000000 -0600
@@ -3,12 +3,17 @@ void main(int argc, char *argv[])
char *buf;

/* allocate memory */
- buf = alloca(bytes);
+ buf = malloc(bytes);
+ if (buf == NULL)
+ return 1;


- if(argc == 0)
+ if(argc == 0) {
+ free(buf);
return 0;
+ }

+ free(buf);
return 1;
}

note: see also how (beautifully) coccinelle adds the necessary { } after the if to make it a compound statement. Coccinelle also put
the correct indentation each time, even if the LWN html page does not
show it because of html space mangling I guess.


Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds