libreboot-utils: extremely safe(ish) malloc usage

yes, a common thing in C programs is one or all
of the following:

* use after frees
* double free (on non-NULL pointer)
* over-writing currently used pointer (mem leak)

i try to reduce the chance of this in my software,
by running free() through a filter function,
free_if_not_null, that returns if a function
is being freed twice - because it sets NULL
after freeing, but will only free if it's not
null already.

this patch adds two functions: smalloc and vmalloc,
for strings and voids. using these makes the program
abort if:

* non-null pointer given for initialisation
* pointer to pointer is null (of course)
* size of zero given, for malloc (zero bytes)

i myself was caught out by this change, prompting
me to make the following fix in fs_dirname_basename()
inside lib/file.c:

-       char *buf;
+       char *buf = NULL;

Yes.

Signed-off-by: Leah Rowe <leah@libreboot.org>
This commit is contained in:
Leah Rowe
2026-03-28 04:19:25 +00:00
parent cec9a25c2a
commit 7f39ce5f9b
5 changed files with 75 additions and 60 deletions
+6 -8
View File
@@ -111,12 +111,11 @@ fsync_dir(const char *path)
if (if_err(path == NULL, EFAULT) ||
if_err_sys(slen(path, maxlen, &pathlen) < 0) ||
if_err(pathlen >= maxlen || pathlen < 0, EMSGSIZE) ||
if_err(pathlen == 0, EINVAL)
||
if_err_sys((dirbuf = malloc(pathlen + 1)) == NULL))
if_err(pathlen == 0, EINVAL))
goto err_fsync_dir;
memcpy(dirbuf, path, pathlen + 1);
memcpy(smalloc(&dirbuf, pathlen + 1),
path, pathlen + 1);
slash = strrchr(dirbuf, '/');
if (slash != NULL) {
@@ -862,7 +861,7 @@ fs_dirname_basename(const char *path,
char **dir, char **base,
int allow_relative)
{
char *buf;
char *buf = NULL;
char *slash;
size_t len;
int rval;
@@ -874,11 +873,10 @@ fs_dirname_basename(const char *path,
#endif
if (path == NULL || dir == NULL || base == NULL ||
if_err_sys(slen(path, maxlen, &len) < 0) ||
if_err_sys((buf = malloc(len + 1)) == NULL))
if_err_sys(slen(path, maxlen, &len) < 0))
return -1;
memcpy(buf, path, len + 1);
memcpy(smalloc(&buf, len + 1), path, len + 1);
/* strip trailing slashes */
while (len > 1 && buf[len - 1] == '/')