Skip to content

Commit cebab18

Browse files
mkindahlCommitfest Bot
authored and
Commitfest Bot
committed
Semantic patch for sizeof() using palloc()
If palloc() is used to allocate elements of type T it should be assigned to a variable of type T* or risk indexes out of bounds. This semantic patch checks that allocations to variables of type T* are using sizeof(T) when allocating memory using palloc().
1 parent 18bef14 commit cebab18

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

cocci/palloc_sizeof.cocci

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
virtual report
2+
virtual context
3+
virtual patch
4+
5+
@initialize:python@
6+
@@
7+
import re
8+
9+
CONST_CRE = re.compile(r'\bconst\b')
10+
11+
def is_simple_type(s):
12+
return s != 'void' and not CONST_CRE.search(s)
13+
14+
@r1 depends on report || context@
15+
type T1 : script:python () { is_simple_type(T1) };
16+
idexpression T1 *I;
17+
type T2 != T1;
18+
position p;
19+
expression E;
20+
identifier func = {palloc, palloc0};
21+
@@
22+
(
23+
* I = func@p(sizeof(T2))
24+
|
25+
* I = func@p(E * sizeof(T2))
26+
)
27+
28+
@script:python depends on report@
29+
T1 << r1.T1;
30+
T2 << r1.T2;
31+
I << r1.I;
32+
p << r1.p;
33+
@@
34+
coccilib.report.print_report(p[0], f"'{I}' has type '{T1}*' but 'sizeof({T2})' is used to allocate memory")
35+
36+
@depends on patch@
37+
type T1 : script:python () { is_simple_type(T1) };
38+
idexpression T1 *I;
39+
type T2 != T1;
40+
expression E;
41+
identifier func = {palloc, palloc0};
42+
@@
43+
(
44+
- I = func(sizeof(T2))
45+
+ I = func(sizeof(T1))
46+
|
47+
- I = func(E * sizeof(T2))
48+
+ I = func(E * sizeof(T1))
49+
)

0 commit comments

Comments
 (0)