From: | Mats Kindahl <mats(at)timescale(dot)com> |
---|---|
To: | PostgreSQL Development <pgsql-hackers(at)postgresql(dot)org> |
Subject: | Coccinelle for PostgreSQL development [4/N]: correcting palloc() use |
Date: | 2025-01-07 19:49:45 |
Message-ID: | CA+144264174RYFwFeVNjBtK134vSwN4k=1-qWbDdqK7kPd6AKg@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-hackers |
This is the first example semantic patch and shows how to capture and fix a
common problem.
If you use an palloc() to allocate memory for an object (or an array of
objects) and by mistake type something like:
StringInfoData *info = palloc(sizeof(StringInfoData*));
You will not allocate enough memory for storing the object. This semantic
patch catches any cases where you are either allocating an array of objects
or a single object that do not have corret types in this sense, more
precisely, it captures assignments to a variable of type T* where palloc()
uses sizeof(T) either alone or with a single expression (assuming this is
an array count).
The semantic patch is overzealous in the sense that allocation to a "const
char **" expects a "sizeof(const char *)" and it cannot deal with typedefs
that introduce aliases (these two can be seen in the patch). Although the
sizes of these are the same, and Coccinelle do not have a good system for
comparing types, it might be better to just follow the convention of always
using the type "T*" for any "palloc(sizeof(T))" since it makes automated
checking easier and is a small inconvenience; especially considering that
coccicheck can easily fix this for you. It also simplifies other automated
checking to follow this convention.
We don't really have any real bugs as a result from this, but we have one
case where an allocation of "sizeof(LLVMBasicBlockRef*)" is allocated to an
"LLVMBasicBlockRef*", which strictly speaking is not correct (it should be
"sizeof(LLVMBasicBlockRef)"). However, since they are both pointers, there
is no risk of incorrect allocation size.
--
Best wishes,
Mats Kindahl, Timescale
Attachment | Content-Type | Size |
---|---|---|
0004-Add-semantic-patch-for-sizeof-using-palloc.v1.patch | text/x-patch | 3.7 KB |
From | Date | Subject | |
---|---|---|---|
Next Message | Mats Kindahl | 2025-01-07 19:51:35 | Coccinelle for PostgreSQL development [5/N]: using palloc_array() and friends |
Previous Message | Mats Kindahl | 2025-01-07 19:48:46 | Coccinelle for PostgreSQL development [3/N]: meson support |