From 3d7bca9422d5e9c851e42f442afeeb2dfc2104c3 Mon Sep 17 00:00:00 2001
From: Mats Kindahl <mats@kindahl.net>
Date: Sun, 5 Jan 2025 19:26:47 +0100
Subject: 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().
---
 cocci/palloc_sizeof.cocci | 49 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)
 create mode 100644 cocci/palloc_sizeof.cocci

diff --git a/cocci/palloc_sizeof.cocci b/cocci/palloc_sizeof.cocci
new file mode 100644
index 00000000000..5f8593c2687
--- /dev/null
+++ b/cocci/palloc_sizeof.cocci
@@ -0,0 +1,49 @@
+virtual report
+virtual context
+virtual patch
+
+@initialize:python@
+@@
+import re
+
+CONST_CRE = re.compile(r'\bconst\b')
+
+def is_simple_type(s):
+    return s != 'void' and not CONST_CRE.search(s)
+
+@r1 depends on report || context@
+type T1 : script:python () { is_simple_type(T1) };
+idexpression T1 *I;
+type T2 != T1;
+position p;
+expression E;
+identifier func = {palloc, palloc0};
+@@
+(
+* I = func@p(sizeof(T2))
+|
+* I = func@p(E * sizeof(T2))
+)
+
+@script:python depends on report@
+T1 << r1.T1;
+T2 << r1.T2;
+I << r1.I;
+p << r1.p;
+@@
+coccilib.report.print_report(p[0], f"'{I}' has type '{T1}*' but 'sizeof({T2})' is used to allocate memory")
+
+@depends on patch@
+type T1 : script:python () { is_simple_type(T1) };
+idexpression T1 *I;
+type T2 != T1;
+expression E;
+identifier func = {palloc, palloc0};
+@@
+(
+- I = func(sizeof(T2))
++ I = func(sizeof(T1))
+|
+- I = func(E * sizeof(T2))
++ I = func(E * sizeof(T1))
+)
-- 
2.43.0

