LWN.net Logo

Semantic patching with Coccinelle

Semantic patching with Coccinelle

Posted Feb 3, 2009 21:27 UTC (Tue) by padator (guest, #56235)
In reply to: Semantic patching with Coccinelle by robbe
Parent article: Semantic patching with Coccinelle

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.


(Log in to post comments)

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