Files
systemd/src/basic/string-table.c
T
Michael Vogt 9f35848ce9 basic: add assert() when doing pointer deref
Lennart reminded me in [1] that we need to add assert() in functions
that do pointer access. For the simple `*p` pointer dereferences
we even have an automatic coccinelle script that ensures that as
part of the automatic code checks.

However for deref in the `p->` style this is not supported right
now and adding it to coccinelle is hard because its too slow for
this kind of check. So I created a (slightly messy) tree-sitter
python script to see how many asserts we are currently missing.

This commit is the result of running it over the `src/basic`
dir and fixing the flagged issues. I plan to tidy it up and
add it to the checks too but this is orthogonal to this commit.

[1] https://github.com/systemd/systemd/pull/42360#discussion_r3426964562

(cherry picked from commit bc4dfc24a5)
2026-06-26 11:40:48 +01:00

81 lines
2.0 KiB
C

/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include "parse-util.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
const char* string_table_lookup_to_string(const char * const *table, size_t len, ssize_t i) {
if (i < 0 || i >= (ssize_t) len)
return NULL;
assert(table);
return table[i];
}
ssize_t string_table_lookup_from_string(const char * const *table, size_t len, const char *key) {
assert_return(table, -EINVAL);
if (!key)
return -EINVAL;
for (size_t i = 0; i < len; ++i)
if (streq_ptr(table[i], key))
return (ssize_t) i;
return -EINVAL;
}
ssize_t string_table_lookup_from_string_with_boolean(const char * const *table, size_t len, const char *key, ssize_t yes) {
if (!key)
return -EINVAL;
int b = parse_boolean(key);
if (b == 0)
return 0;
if (b > 0)
return yes;
return string_table_lookup_from_string(table, len, key);
}
int string_table_lookup_to_string_fallback(const char * const *table, size_t len, ssize_t i, size_t max, char **ret) {
char *s;
assert(table);
assert(ret);
if (i < 0 || i > (ssize_t) max)
return -ERANGE;
if (i < (ssize_t) len && table[i])
s = strdup(table[i]);
else
s = asprintf_safe("%zd", i);
if (!s)
return -ENOMEM;
*ret = s;
return 0;
}
ssize_t string_table_lookup_from_string_fallback(const char * const *table, size_t len, const char *s, size_t max) {
if (!s)
return -EINVAL;
ssize_t i = string_table_lookup_from_string(table, len, s);
if (i >= 0)
return i;
unsigned u;
if (safe_atou(s, &u) < 0)
return -EINVAL;
if (u > max)
return -EINVAL;
return u;
}