diff options
127 files changed, 657 insertions, 687 deletions
diff --git a/src/analyze/analyze-security.c b/src/analyze/analyze-security.c index fc5af11f55..f20606c17c 100644 --- a/src/analyze/analyze-security.c +++ b/src/analyze/analyze-security.c @@ -2116,7 +2116,7 @@ int analyze_security(sd_bus *bus, char **units, AnalyzeSecurityFlags flags) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_strv_free_ char **list = NULL; - size_t allocated = 0, n = 0; + size_t n = 0; char **i; r = sd_bus_call_method( @@ -2148,7 +2148,7 @@ int analyze_security(sd_bus *bus, char **units, AnalyzeSecurityFlags flags) { if (!endswith(info.id, ".service")) continue; - if (!GREEDY_REALLOC(list, allocated, n + 2)) + if (!GREEDY_REALLOC(list, n + 2)) return log_oom(); copy = strdup(info.id); diff --git a/src/analyze/analyze.c b/src/analyze/analyze.c index 1ad3731852..62c0ccbdfe 100644 --- a/src/analyze/analyze.c +++ b/src/analyze/analyze.c @@ -342,7 +342,7 @@ static int acquire_time_data(sd_bus *bus, UnitTimes **out) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(unit_times_free_arrayp) UnitTimes *unit_times = NULL; BootTimes *boot_times = NULL; - size_t allocated = 0, c = 0; + size_t c = 0; UnitInfo u; int r; @@ -361,7 +361,7 @@ static int acquire_time_data(sd_bus *bus, UnitTimes **out) { while ((r = bus_parse_unit_info(reply, &u)) > 0) { UnitTimes *t; - if (!GREEDY_REALLOC(unit_times, allocated, c + 2)) + if (!GREEDY_REALLOC(unit_times, c + 2)) return log_oom(); unit_times[c + 1].has_data = false; diff --git a/src/basic/alloc-util.c b/src/basic/alloc-util.c index bad15cc204..5545af5497 100644 --- a/src/basic/alloc-util.c +++ b/src/basic/alloc-util.c @@ -39,24 +39,32 @@ void* memdup_suffix0(const void *p, size_t l) { return ret; } -void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) { +void* greedy_realloc( + void **p, + size_t need, + size_t size) { + size_t a, newalloc; void *q; assert(p); - assert(allocated); - if (*allocated >= need) + /* We use malloc_usable_size() for determining the current allocated size. On all systems we care + * about this should be safe to rely on. Should there ever arise the need to avoid relying on this we + * can instead locally fall back to realloc() on every call, rounded up to the next exponent of 2 or + * so. */ + + if (*p && (size == 0 || (MALLOC_SIZEOF_SAFE(*p) / size >= need))) return *p; if (_unlikely_(need > SIZE_MAX/2)) /* Overflow check */ return NULL; - newalloc = need * 2; + if (size_multiply_overflow(newalloc, size)) return NULL; - a = newalloc * size; + if (a < 64) /* Allocate at least 64 bytes */ a = 64; @@ -64,49 +72,34 @@ void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) { if (!q) return NULL; - if (size > 0) { - size_t bn; - - /* Adjust for the 64 byte minimum */ - newalloc = a / size; - - bn = malloc_usable_size(q) / size; - if (bn > newalloc) { - void *qq; - - /* The actual size allocated is larger than what we asked for. Let's call realloc() again to - * take possession of the extra space. This should be cheap, since libc doesn't have to move - * the memory for this. */ - - qq = reallocarray(q, bn, size); - if (_likely_(qq)) { - *p = qq; - *allocated = bn; - return qq; - } - } - } - - *p = q; - *allocated = newalloc; - return q; + return *p = q; } -void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) { - size_t prev; +void* greedy_realloc0( + void **p, + size_t need, + size_t size) { + + size_t before, after; uint8_t *q; assert(p); - assert(allocated); - prev = *allocated; + before = MALLOC_SIZEOF_SAFE(*p); /* malloc_usable_size() will return 0 on NULL input, as per docs */ - q = greedy_realloc(p, allocated, need, size); + q = greedy_realloc(p, need, size); if (!q) return NULL; - if (*allocated > prev) - memzero(q + prev * size, (*allocated - prev) * size); + after = MALLOC_SIZEOF_SAFE(q); + + if (size == 0) /* avoid division by zero */ + before = 0; + else + before = (before / size) * size; /* Round down */ + + if (after > before) + memzero(q + before, after - before); return q; } diff --git a/src/basic/alloc-util.h b/src/basic/alloc-util.h index 195795285b..3ef126955b 100644 --- a/src/basic/alloc-util.h +++ b/src/basic/alloc-util.h @@ -121,14 +121,14 @@ static inline void *memdup_suffix0_multiply(const void *p, size_t size, size_t n return memdup_suffix0(p, size * need); } -void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size); -void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size); +void* greedy_realloc(void **p, size_t need, size_t size); +void* greedy_realloc0(void **p, size_t need, size_t size); -#define GREEDY_REALLOC(array, allocated, need) \ - greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0])) +#define GREEDY_REALLOC(array, need) \ + greedy_realloc((void**) &(array), (need), sizeof((array)[0])) -#define GREEDY_REALLOC0(array, allocated, need) \ - greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0])) +#define GREEDY_REALLOC0(array, need) \ + greedy_realloc0((void**) &(array), (need), sizeof((array)[0])) #define alloca0(n) \ ({ \ diff --git a/src/basic/btrfs-util.c b/src/basic/btrfs-util.c index 51aaee71fd..bc1fb8d29d 100644 --- a/src/basic/btrfs-util.c +++ b/src/basic/btrfs-util.c @@ -1728,7 +1728,7 @@ int btrfs_qgroup_find_parents(int fd, uint64_t qgroupid, uint64_t **ret) { }; _cleanup_free_ uint64_t *items = NULL; - size_t n_items = 0, n_allocated = 0; + size_t n_items = 0; int r; assert(fd >= 0); @@ -1775,7 +1775,7 @@ int btrfs_qgroup_find_parents(int fd, uint64_t qgroupid, uint64_t **ret) { if (sh->objectid != qgroupid) continue; - if (!GREEDY_REALLOC(items, n_allocated, n_items+1)) + if (!GREEDY_REALLOC(items, n_items+1)) return -ENOMEM; items[n_items++] = sh->offset; diff --git a/src/basic/cap-list.c b/src/basic/cap-list.c index d295a635ca..fdc7948a23 100644 --- a/src/basic/cap-list.c +++ b/src/basic/cap-list.c @@ -59,7 +59,7 @@ int capability_list_length(void) { int capability_set_to_string_alloc(uint64_t set, char **s) { _cleanup_free_ char *str = NULL; - size_t allocated = 0, n = 0; + size_t n = 0; assert(s); @@ -77,14 +77,14 @@ int capability_set_to_string_alloc(uint64_t set, char **s) { add = strlen(p); - if (!GREEDY_REALLOC(str, allocated, n + add + 2)) + if (!GREEDY_REALLOC(str, n + add + 2)) return -ENOMEM; strcpy(mempcpy(str + n, p, add), " "); n += add + 1; } - if (!GREEDY_REALLOC(str, allocated, n + 1)) + if (!GREEDY_REALLOC(str, n + 1)) return -ENOMEM; str[n > 0 ? n - 1 : 0] = '\0'; /* truncate the last space, if it's there */ diff --git a/src/basic/cgroup-util.c b/src/basic/cgroup-util.c index b790df6dbe..e39bfd9bc7 100644 --- a/src/basic/cgroup-util.c +++ b/src/basic/cgroup-util.c @@ -1817,9 +1817,9 @@ done: int cg_mask_to_string(CGroupMask mask, char **ret) { _cleanup_free_ char *s = NULL; - size_t n = 0, allocated = 0; bool space = false; CGroupController c; + size_t n = 0; assert(ret); @@ -1838,7 +1838,7 @@ int cg_mask_to_string(CGroupMask mask, char **ret) { k = cgroup_controller_to_string(c); l = strlen(k); - if (!GREEDY_REALLOC(s, allocated, n + space + l + 1)) + if (!GREEDY_REALLOC(s, n + space + l + 1)) return -ENOMEM; if (space) diff --git a/src/basic/env-file.c b/src/basic/env-file.c index a300909360..599b73bc22 100644 --- a/src/basic/env-file.c +++ b/src/basic/env-file.c @@ -20,7 +20,7 @@ static int parse_env_file_internal( void *userdata, int *n_pushed) { - size_t key_alloc = 0, n_key = 0, value_alloc = 0, n_value = 0, last_value_whitespace = SIZE_MAX, last_key_whitespace = SIZE_MAX; + size_t n_key = 0, n_value = 0, last_value_whitespace = SIZE_MAX, last_key_whitespace = SIZE_MAX; _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL; unsigned line = 1; char *p; @@ -58,7 +58,7 @@ static int parse_env_file_internal( state = KEY; last_key_whitespace = SIZE_MAX; - if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) + if (!GREEDY_REALLOC(key, n_key+2)) return -ENOMEM; key[n_key++] = c; @@ -79,7 +79,7 @@ static int parse_env_file_internal( else if (last_key_whitespace == SIZE_MAX) last_key_whitespace = n_key; - if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) + if (!GREEDY_REALLOC(key, n_key+2)) return -ENOMEM; key[n_key++] = c; @@ -106,7 +106,7 @@ static int parse_env_file_internal( n_key = 0; value = NULL; - value_alloc = n_value = 0; + n_value = 0; } else if (c == '\'') state = SINGLE_QUOTE_VALUE; @@ -117,7 +117,7 @@ static int parse_env_file_internal( else if (!strchr(WHITESPACE, c)) { state = VALUE; - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; @@ -149,7 +149,7 @@ static int parse_env_file_internal( n_key = 0; value = NULL; - value_alloc = n_value = 0; + n_value = 0; } else if (c == '\\') { state = VALUE_ESCAPE; @@ -160,7 +160,7 @@ static int parse_env_file_internal( else if (last_value_whitespace == SIZE_MAX) last_value_whitespace = n_value; - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; @@ -173,7 +173,7 @@ static int parse_env_file_internal( if (!strchr(NEWLINE, c)) { /* Escaped newlines we eat up entirely */ - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; @@ -184,7 +184,7 @@ static int parse_env_file_internal( if (c == '\'') state = PRE_VALUE; else { - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; @@ -198,7 +198,7 @@ static int parse_env_file_internal( else if (c == '\\') state = DOUBLE_QUOTE_VALUE_ESCAPE; else { - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; @@ -211,13 +211,13 @@ static int parse_env_file_internal( if (strchr(SHELL_NEED_ESCAPE, c)) { /* If this is a char that needs escaping, just unescape it. */ - if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) + if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } else if (c != '\n') { /* If other char than what needs escaping, keep the "\" in place, like the * real shell does. */ - if (!GREEDY_REALLOC(value, value_alloc, n_value+3)) + if (!GREEDY_REALLOC(value, n_value+3)) return -ENOMEM; value[n_value++] = '\\'; value[n_value++] = c; diff --git a/src/basic/extract-word.c b/src/basic/extract-word.c index d1af11318a..2c14b6f0cf 100644 --- a/src/basic/extract-word.c +++ b/src/basic/extract-word.c @@ -19,7 +19,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, ExtractFlags flags) { _cleanup_free_ char *s = NULL; - size_t allocated = 0, sz = 0; + size_t sz = 0; char quote = 0; /* 0 or ' or " */ bool backslash = false; /* whether we've just seen a backslash */ char c; @@ -42,7 +42,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, Extra * the pointer *p at the first invalid character. */ if (flags & EXTRACT_DONT_COALESCE_SEPARATORS) - if (!GREEDY_REALLOC(s, allocated, sz+1)) + if (!GREEDY_REALLOC(s, sz+1)) return -ENOMEM; for (;; (*p)++, c = **p) { @@ -57,7 +57,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, Extra /* We found a non-blank character, so we will always * want to return a string (even if it is empty), * allocate it here. */ - if (!GREEDY_REALLOC(s, allocated, sz+1)) + if (!GREEDY_REALLOC(s, sz+1)) return -ENOMEM; break; } @@ -65,7 +65,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, Extra for (;; (*p)++, c = **p) { if (backslash) { - if (!GREEDY_REALLOC(s, allocated, sz+7)) + if (!GREEDY_REALLOC(s, sz+7)) return -ENOMEM; if (c == 0) { @@ -128,7 +128,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, Extra backslash = true; break; } else { - if (!GREEDY_REALLOC(s, allocated, sz+2)) + if (!GREEDY_REALLOC(s, sz+2)) return -ENOMEM; s[sz++] = c; @@ -160,7 +160,7 @@ int extract_first_word(const char **p, char **ret, const char *separators, Extra goto finish; } else { - if (!GREEDY_REALLOC(s, allocated, sz+2)) + if (!GREEDY_REALLOC(s, sz+2)) return -ENOMEM; s[sz++] = c; diff --git a/src/basic/fileio.c b/src/basic/fileio.c index 4afab84ed3..0df03077d3 100644 --- a/src/basic/fileio.c +++ b/src/basic/fileio.c @@ -1212,8 +1212,8 @@ static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) { DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL); int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) { - size_t n = 0, allocated = 0, count = 0; _cleanup_free_ char *buffer = NULL; + size_t n = 0, count = 0; int r; assert(f); @@ -1243,7 +1243,7 @@ int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) { * If a line shall be skipped ret may be initialized as NULL. */ if (ret) { - if (!GREEDY_REALLOC(buffer, allocated, 1)) + if (!GREEDY_REALLOC(buffer, 1)) return -ENOMEM; } @@ -1315,7 +1315,7 @@ int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) { } if (ret) { - if (!GREEDY_REALLOC(buffer, allocated, n + 2)) + if (!GREEDY_REALLOC(buffer, n + 2)) return -ENOMEM; buffer[n] = c; diff --git a/src/basic/fs-util.c b/src/basic/fs-util.c index 46d6f7780e..e8435cab2c 100644 --- a/src/basic/fs-util.c +++ b/src/basic/fs-util.c @@ -549,10 +549,10 @@ int mkfifoat_atomic(int dirfd, const char *path, mode_t mode) { } int get_files_in_directory(const char *path, char ***list) { + _cleanup_strv_free_ char **l = NULL; _cleanup_closedir_ DIR *d = NULL; struct dirent *de; - size_t bufsize = 0, n = 0; - _cleanup_strv_free_ char **l = NULL; + size_t n = 0; assert(path); @@ -572,7 +572,7 @@ int get_files_in_directory(const char *path, char ***list) { if (list) { /* one extra slot is needed for the terminating NULL */ - if (!GREEDY_REALLOC(l, bufsize, n + 2)) + if (!GREEDY_REALLOC(l, n + 2)) return -ENOMEM; l[n] = strdup(de->d_name); diff --git a/src/basic/hashmap.c b/src/basic/hashmap.c index e354c67adc..34fed69d99 100644 --- a/src/basic/hashmap.c +++ b/src/basic/hashmap.c @@ -230,7 +230,7 @@ struct Set { typedef struct CacheMem { const void **ptr; - size_t n_populated, n_allocated; + size_t n_populated; bool active:1; } CacheMem; @@ -1897,10 +1897,10 @@ int set_put_strsplit(Set *s, const char *v, const char *separators, ExtractFlags } /* expand the cachemem if needed, return true if newly (re)activated. */ -static int cachemem_maintain(CacheMem *mem, unsigned size) { +static int cachemem_maintain(CacheMem *mem, size_t size) { assert(mem); - if (!GREEDY_REALLOC(mem->ptr, mem->n_allocated, size)) { + if (!GREEDY_REALLOC(mem->ptr, size)) { if (size > 0) return -ENOMEM; } @@ -1915,7 +1915,7 @@ static int cachemem_maintain(CacheMem *mem, unsigned size) { int iterated_cache_get(IteratedCache *cache, const void ***res_keys, const void ***res_values, unsigned *res_n_entries) { bool sync_keys = false, sync_values = false; - unsigned size; + size_t size; int r; assert(cache); @@ -1988,8 +1988,8 @@ IteratedCache* iterated_cache_free(IteratedCache *cache) { } int set_strjoin(Set *s, const char *separator, bool wrap_with_separator, char **ret) { - size_t separator_len, allocated = 0, len = 0; _cleanup_free_ char *str = NULL; + size_t separator_len, len = 0; const char *value; bool first; @@ -2013,7 +2013,7 @@ int set_strjoin(Set *s, const char *separator, bool wrap_with_separator, char ** if (l == 0) continue; - if (!GREEDY_REALLOC(str, allocated, len + l + (first ? 0 : separator_len) + (wrap_with_separator ? separator_len : 0) + 1)) + if (!GREEDY_REALLOC(str, len + l + (first ? 0 : separator_len) + (wrap_with_separator ? separator_len : 0) + 1)) return -ENOMEM; if (separator_len > 0 && !first) { diff --git a/src/basic/io-util.c b/src/basic/io-util.c index f0a66da9bf..783ca1309d 100644 --- a/src/basic/io-util.c +++ b/src/basic/io-util.c @@ -288,7 +288,6 @@ void iovw_free_contents(struct iovec_wrapper *iovw, bool free_vectors) { iovw->iovec = mfree(iovw->iovec); iovw->count = 0; - iovw->size_bytes = 0; } struct iovec_wrapper *iovw_free_free(struct iovec_wrapper *iovw) { @@ -307,7 +306,7 @@ int iovw_put(struct iovec_wrapper *iovw, void *data, size_t len) { if (iovw->count >= IOV_MAX) return -E2BIG; - if (!GREEDY_REALLOC(iovw->iovec, iovw->size_bytes, iovw->count + 1)) + if (!GREEDY_REALLOC(iovw->iovec, iovw->count + 1)) return -ENOMEM; iovw->iovec[iovw->count++] = IOVEC_MAKE(data, len); diff --git a/src/basic/io-util.h b/src/basic/io-util.h index ce54ca228b..39728e06bc 100644 --- a/src/basic/io-util.h +++ b/src/basic/io-util.h @@ -85,7 +85,6 @@ char* set_iovec_string_field_free(struct iovec *iovec, size_t *n_iovec, const ch struct iovec_wrapper { struct iovec *iovec; size_t count; - size_t size_bytes; }; struct iovec_wrapper *iovw_new(void); diff --git a/src/basic/process-util.c b/src/basic/process-util.c index de28daf2b1..22903cd677 100644 --- a/src/basic/process-util.c +++ b/src/basic/process-util.c @@ -601,7 +601,7 @@ int get_process_root(pid_t pid, char **root) { int get_process_environ(pid_t pid, char **env) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *outcome = NULL; - size_t allocated = 0, sz = 0; + size_t sz = 0; const char *p; int r; @@ -622,7 +622,7 @@ int get_process_environ(pid_t pid, char **env) { if (sz >= ENVIRONMENT_BLOCK_MAX) return -ENOBUFS; - if (!GREEDY_REALLOC(outcome, allocated, sz + 5)) + if (!GREEDY_REALLOC(outcome, sz + 5)) return -ENOMEM; r = safe_fgetc(f, &c); diff --git a/src/basic/string-util.c b/src/basic/string-util.c index f4b6515a43..fd922b117b 100644 --- a/src/basic/string-util.c +++ b/src/basic/string-util.c @@ -522,7 +522,7 @@ char* strshorten(char *s, size_t l) { } char *strreplace(const char *text, const char *old_string, const char *new_string) { - size_t l, old_len, new_len, allocated = 0; + size_t l, old_len, new_len; char *t, *ret = NULL; const char *f; @@ -536,7 +536,7 @@ char *strreplace(const char *text, const char *old_string, const char *new_strin new_len = strlen(new_string); l = strlen(text); - if (!GREEDY_REALLOC(ret, allocated, l+1)) + if (!GREEDY_REALLOC(ret, l+1)) return NULL; f = text; @@ -552,7 +552,7 @@ char *strreplace(const char *text, const char *old_string, const char *new_strin d = t - ret; nl = l - old_len + new_len; - if (!GREEDY_REALLOC(ret, allocated, nl + 1)) + if (!GREEDY_REALLOC(ret, nl + 1)) return mfree(ret); l = nl; diff --git a/src/basic/strv.c b/src/basic/strv.c index 765da04a7b..3adf3c5c7e 100644 --- a/src/basic/strv.c +++ b/src/basic/strv.c @@ -266,7 +266,7 @@ int strv_split_newlines_full(char ***ret, const char *s, ExtractFlags flags) { int strv_split_full(char ***t, const char *s, const char *separators, ExtractFlags flags) { _cleanup_strv_free_ char **l = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; int r; assert(t); @@ -281,7 +281,7 @@ int strv_split_full(char ***t, const char *s, const char *separators, ExtractFla if (r == 0) break; - if (!GREEDY_REALLOC(l, allocated, n + 2)) + if (!GREEDY_REALLOC(l, n + 2)) return -ENOMEM; l[n++] = TAKE_PTR(word); @@ -302,7 +302,7 @@ int strv_split_full(char ***t, const char *s, const char *separators, ExtractFla int strv_split_colon_pairs(char ***t, const char *s) { _cleanup_strv_free_ char **l = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; int r; assert(t); @@ -332,7 +332,7 @@ int strv_split_colon_pairs(char ***t, const char *s) { if (!second_or_empty) return -ENOMEM; - if (!GREEDY_REALLOC(l, allocated, n + 3)) + if (!GREEDY_REALLOC(l, n + 3)) return -ENOMEM; l[n++] = TAKE_PTR(first); @@ -708,9 +708,9 @@ int strv_make_nulstr(char * const *l, char **ret, size_t *ret_size) { * is provided separately. */ - size_t n_allocated = 0, n = 0; _cleanup_free_ char *m = NULL; char * const *i; + size_t n = 0; assert(ret); assert(ret_size); @@ -720,7 +720,7 @@ int strv_make_nulstr(char * const *l, char **ret, size_t *ret_size) { z = strlen(*i); - if (!GREEDY_REALLOC(m, n_allocated, n + z + 2)) + if (!GREEDY_REALLOC(m, n + z + 2)) return -ENOMEM; memcpy(m + n, *i, z + 1); diff --git a/src/basic/time-util.c b/src/basic/time-util.c index b6087c4550..da3f025583 100644 --- a/src/basic/time-util.c +++ b/src/basic/time-util.c @@ -1247,7 +1247,7 @@ int parse_nsec(const char *t, nsec_t *nsec) { int get_timezones(char ***ret) { _cleanup_fclose_ FILE *f = NULL; _cleanup_strv_free_ char **zones = NULL; - size_t n_zones = 0, n_allocated = 0; + size_t n_zones = 0; int r; assert(ret); @@ -1256,7 +1256,6 @@ int get_timezones(char ***ret) { if (!zones) return -ENOMEM; - n_allocated = 2; n_zones = 1; f = fopen("/usr/share/zoneinfo/zone1970.tab", "re"); @@ -1294,7 +1293,7 @@ int get_timezones(char ***ret) { if (!w) return -ENOMEM; - if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) + if (!GREEDY_REALLOC(zones, n_zones + 2)) return -ENOMEM; zones[n_zones++] = TAKE_PTR(w); diff --git a/src/busctl/busctl.c b/src/busctl/busctl.c index f081e98ae0..8aa769e0f9 100644 --- a/src/busctl/busctl.c +++ b/src/busctl/busctl.c @@ -1644,8 +1644,8 @@ static int message_append_cmdline(sd_bus_message *m, const char *signature, char static int json_transform_one(sd_bus_message *m, JsonVariant **ret); static int json_transform_array_or_struct(sd_bus_message *m, JsonVariant **ret) { - size_t n_elements = 0, n_allocated = 0; JsonVariant **elements = NULL; + size_t n_elements = 0; int r; assert(m); @@ -1660,7 +1660,7 @@ static int json_transform_array_or_struct(sd_bus_message *m, JsonVariant **ret) if (r > 0) break; - if (!GREEDY_REALLOC(elements, n_allocated, n_elements + 1)) { + if (!GREEDY_REALLOC(elements, n_elements + 1)) { r = log_oom(); goto finish; } @@ -1702,8 +1702,8 @@ static int json_transform_variant(sd_bus_message *m, const char *contents, JsonV } static int json_transform_dict_array(sd_bus_message *m, JsonVariant **ret) { - size_t n_elements = 0, n_allocated = 0; JsonVariant **elements = NULL; + size_t n_elements = 0; int r; assert(m); @@ -1727,7 +1727,7 @@ static int json_transform_dict_array(sd_bus_message *m, JsonVariant **ret) { assert(type == 'e'); - if (!GREEDY_REALLOC(elements, n_allocated, n_elements + 2)) { + if (!GREEDY_REALLOC(elements, n_elements + 2)) { r = log_oom(); goto finish; } diff --git a/src/core/execute.c b/src/core/execute.c index 6a1e6c8429..ebd1418c8c 100644 --- a/src/core/execute.c +++ b/src/core/execute.c @@ -1967,7 +1967,7 @@ static int build_environment( static int build_pass_environment(const ExecContext *c, char ***ret) { _cleanup_strv_free_ char **pass_env = NULL; - size_t n_env = 0, n_bufsize = 0; + size_t n_env = 0; char **i; STRV_FOREACH(i, c->pass_environment) { @@ -1981,7 +1981,7 @@ static int build_pass_environment(const ExecContext *c, char ***ret) { if (!x) return -ENOMEM; - if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2)) + if (!GREEDY_REALLOC(pass_env, n_env + 2)) return -ENOMEM; pass_env[n_env++] = TAKE_PTR(x); diff --git a/src/core/job.c b/src/core/job.c index 57829d185a..c626ddca91 100644 --- a/src/core/job.c +++ b/src/core/job.c @@ -1498,8 +1498,8 @@ static size_t sort_job_list(Job **list, size_t n) { int job_get_before(Job *j, Job*** ret) { _cleanup_free_ Job** list = NULL; - size_t n = 0, n_allocated = 0; Unit *other = NULL; + size_t n = 0; void *v; /* Returns a list of all pending jobs that need to finish before this job may be started. */ @@ -1518,7 +1518,7 @@ int job_get_before(Job *j, Job*** ret) { if (job_compare(j, other->job, UNIT_AFTER) <= 0) continue; - if (!GREEDY_REALLOC(list, n_allocated, n+1)) + if (!GREEDY_REALLOC(list, n+1)) return -ENOMEM; list[n++] = other->job; } @@ -1529,7 +1529,7 @@ int job_get_before(Job *j, Job*** ret) { if (job_compare(j, other->job, UNIT_BEFORE) <= 0) continue; - if (!GREEDY_REALLOC(list, n_allocated, n+1)) + if (!GREEDY_REALLOC(list, n+1)) return -ENOMEM; list[n++] = other->job; } @@ -1543,8 +1543,8 @@ int job_get_before(Job *j, Job*** ret) { int job_get_after(Job *j, Job*** ret) { _cleanup_free_ Job** list = NULL; - size_t n = 0, n_allocated = 0; Unit *other = NULL; + size_t n = 0; void *v; assert(j); @@ -1562,7 +1562,7 @@ int job_get_after(Job *j, Job*** ret) { if (job_compare(j, other->job, UNIT_BEFORE) >= 0) continue; - if (!GREEDY_REALLOC(list, n_allocated, n+1)) + if (!GREEDY_REALLOC(list, n+1)) return -ENOMEM; list[n++] = other->job; } @@ -1577,7 +1577,7 @@ int job_get_after(Job *j, Job*** ret) { if (job_compare(j, other->job, UNIT_AFTER) >= 0) continue; - if (!GREEDY_REALLOC(list, n_allocated, n+1)) + if (!GREEDY_REALLOC(list, n+1)) return -ENOMEM; list[n++] = other->job; } diff --git a/src/core/load-fragment.c b/src/core/load-fragment.c index 3dd1e869eb..cd37314542 100644 --- a/src/core/load-fragment.c +++ b/src/core/load-fragment.c @@ -712,7 +712,7 @@ int config_parse_exec( bool ignore = false, separate_argv0 = false; _cleanup_free_ ExecCommand *nce = NULL; _cleanup_strv_free_ char **n = NULL; - size_t nlen = 0, nbufsize = 0; + size_t nlen = 0; const char *f; semicolon = false; @@ -799,7 +799,7 @@ int config_parse_exec( if (!separate_argv0) { char *w = NULL; - if (!GREEDY_REALLOC(n, nbufsize, nlen + 2)) + if (!GREEDY_REALLOC(n, nlen + 2)) return log_oom(); w = strdup(path); @@ -831,7 +831,7 @@ int config_parse_exec( p += 2; p += strspn(p, WHITESPACE); - if (!GREEDY_REALLOC(n, nbufsize, nlen + 2)) + if (!GREEDY_REALLOC(n, nlen + 2)) return log_oom(); w = strdup(";"); @@ -856,7 +856,7 @@ int config_parse_exec( return ignore ? 0 : -ENOEXEC; } - if (!GREEDY_REALLOC(n, nbufsize, nlen + 2)) + if (!GREEDY_REALLOC(n, nlen + 2)) return log_oom(); n[nlen++] = TAKE_PTR(resolved); @@ -2691,9 +2691,9 @@ int config_parse_pass_environ( void *userdata) { _cleanup_strv_free_ char **n = NULL; - size_t nlen = 0, nbufsize = 0; - char*** passenv = data; const Unit *u = userdata; + char*** passenv = data; + size_t nlen = 0; int r; assert(filename); @@ -2737,7 +2737,7 @@ int config_parse_pass_environ( continue; } - if (!GREEDY_REALLOC(n, nbufsize, nlen + 2)) + if (!GREEDY_REALLOC(n, nlen + 2)) return log_oom(); n[nlen++] = TAKE_PTR(k); @@ -2766,9 +2766,9 @@ int config_parse_unset_environ( void *userdata) { _cleanup_strv_free_ char **n = NULL; - size_t nlen = 0, nbufsize = 0; char*** unsetenv = data; const Unit *u = userdata; + size_t nlen = 0; int r; assert(filename); @@ -2812,7 +2812,7 @@ int config_parse_unset_environ( continue; } - if (!GREEDY_REALLOC(n, nbufsize, nlen + 2)) + if (!GREEDY_REALLOC(n, nlen + 2)) return log_oom(); n[nlen++] = TAKE_PTR(k); diff --git a/src/core/service.c b/src/core/service.c index 085715b65a..c34030644a 100644 --- a/src/core/service.c +++ b/src/core/service.c @@ -2566,10 +2566,10 @@ static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, ExecC static int service_serialize_exec_command(Unit *u, FILE *f, ExecCommand *command) { _cleanup_free_ char *args = NULL, *p = NULL; - size_t allocated = 0, length = 0; Service *s = SERVICE(u); const char *type, *key; ServiceExecCommand id; + size_t length = 0; unsigned idx; char **arg; @@ -2598,7 +2598,7 @@ static int service_serialize_exec_command(Unit *u, FILE *f, ExecCommand *command return log_oom(); n = strlen(e); - if (!GREEDY_REALLOC(args, allocated, length + 2 + n + 2)) + if (!GREEDY_REALLOC(args, length + 2 + n + 2)) return log_oom(); if (length > 0) @@ -2610,7 +2610,7 @@ static int service_serialize_exec_command(Unit *u, FILE *f, ExecCommand *command args[length++] = '"'; } - if (!GREEDY_REALLOC(args, allocated, length + 1)) + if (!GREEDY_REALLOC(args, length + 1)) return log_oom(); args[length++] = 0; diff --git a/src/core/smack-setup.c b/src/core/smack-setup.c index 8cc1696a4f..58ad085dcd 100644 --- a/src/core/smack-setup.c +++ b/src/core/smack-setup.c @@ -247,7 +247,7 @@ static int write_onlycap_list(void) { _cleanup_close_ int onlycap_fd = -1; _cleanup_free_ char *list = NULL; _cleanup_fclose_ FILE *f = NULL; - size_t len = 0, allocated = 0; + size_t len = 0; int r; f = fopen("/etc/smack/onlycap", "re"); @@ -272,7 +272,7 @@ static int write_onlycap_list(void) { continue; l = strlen(buf); - if (!GREEDY_REALLOC(list, allocated, len + l + 1)) + if (!GREEDY_REALLOC(list, len + l + 1)) return log_oom(); stpcpy(list + len, buf)[0] = ' '; diff --git a/src/core/transaction.c b/src/core/transaction.c index 1d3cf8f1fc..4a55c075b4 100644 --- a/src/core/transaction.c +++ b/src/core/transaction.c @@ -330,11 +330,11 @@ _pure_ static bool unit_matters_to_anchor(Unit *u, Job *j) { static char* merge_unit_ids(const char* unit_log_field, char **pairs) { char **unit_id, **job_type, *ans = NULL; - size_t alloc = 0, size = 0, next; + size_t size = 0, next; STRV_FOREACH_PAIR(unit_id, job_type, pairs) { next = strlen(unit_log_field) + strlen(*unit_id); - if (!GREEDY_REALLOC(ans, alloc, size + next + 1)) + if (!GREEDY_REALLOC(ans, size + next + 1)) return mfree(ans); sprintf(ans + size, "%s%s", unit_log_field, *unit_id); diff --git a/src/core/unit.c b/src/core/unit.c index 67d811d7dd..fc63f3bee5 100644 --- a/src/core/unit.c +++ b/src/core/unit.c @@ -4004,7 +4004,7 @@ char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) { char* unit_concat_strv(char **l, UnitWriteFlags flags) { _cleanup_free_ char *result = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; char **i; /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a @@ -4021,7 +4021,7 @@ char* unit_concat_strv(char **l, UnitWriteFlags flags) { return NULL; a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */ - if (!GREEDY_REALLOC(result, allocated, n + a + 1)) + if (!GREEDY_REALLOC(result, n + a + 1)) return NULL; q = result + n; @@ -4035,7 +4035,7 @@ char* unit_concat_strv(char **l, UnitWriteFlags flags) { n += a; } - if (!GREEDY_REALLOC(result, allocated, n + 1)) + if (!GREEDY_REALLOC(result, n + 1)) return NULL; result[n] = 0; diff --git a/src/cryptenroll/cryptenroll-list.c b/src/cryptenroll/cryptenroll-list.c index d56deaa6b1..c3ad819430 100644 --- a/src/cryptenroll/cryptenroll-list.c +++ b/src/cryptenroll/cryptenroll-list.c @@ -11,8 +11,8 @@ int list_enrolled(struct crypt_device *cd) { int slot; const char *type; } *keyslot_metadata = NULL; - size_t n_keyslot_metadata = 0, n_keyslot_metadata_allocated = 0; _cleanup_(table_unrefp) Table *t = NULL; + size_t n_keyslot_metadata = 0; int slot_max, r; TableCell *cell; @@ -27,7 +27,7 @@ int list_enrolled(struct crypt_device *cd) { if (!IN_SET(status, CRYPT_SLOT_ACTIVE, CRYPT_SLOT_ACTIVE_LAST)) continue; - if (!GREEDY_REALLOC(keyslot_metadata, n_keyslot_metadata_allocated, n_keyslot_metadata+1)) + if (!GREEDY_REALLOC(keyslot_metadata, n_keyslot_metadata+1)) return log_oom(); keyslot_metadata[n_keyslot_metadata++] = (struct keyslot_metadata) { diff --git a/src/delta/delta.c b/src/delta/delta.c index bb38db54a4..8c702459c1 100644 --- a/src/delta/delta.c +++ b/src/delta/delta.c @@ -291,7 +291,7 @@ static int enumerate_dir( _cleanup_closedir_ DIR *d = NULL; struct dirent *de; _cleanup_strv_free_ char **files = NULL, **dirs = NULL; - size_t n_files = 0, allocated_files = 0, n_dirs = 0, allocated_dirs = 0; + size_t n_files = 0, n_dirs = 0; char **t; int r; @@ -314,7 +314,7 @@ static int enumerate_dir( dirent_ensure_type(d, de); if (dropins && de->d_type == DT_DIR && endswith(de->d_name, ".d")) { - if (!GREEDY_REALLOC0(dirs, allocated_dirs, n_dirs + 2)) + if (!GREEDY_REALLOC0(dirs, n_dirs + 2)) return -ENOMEM; dirs[n_dirs] = strdup(de->d_name); @@ -326,7 +326,7 @@ static int enumerate_dir( if (!dirent_is_file(de)) continue; - if (!GREEDY_REALLOC0(files, allocated_files, n_files + 2)) + if (!GREEDY_REALLOC0(files, n_files + 2)) return -ENOMEM; files[n_files] = strdup(de->d_name); diff --git a/src/fuzz/fuzz-compress.c b/src/fuzz/fuzz-compress.c index f94fd0673e..189bd210b5 100644 --- a/src/fuzz/fuzz-compress.c +++ b/src/fuzz/fuzz-compress.c @@ -73,7 +73,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { size_t sw_len = MIN(data_len - 1, h->sw_len); - r = decompress_startswith(alg, buf, csize, &buf2, &sw_alloc, h->data, sw_len, h->data[sw_len]); + r = decompress_startswith(alg, buf, csize, &buf2, h->data, sw_len, h->data[sw_len]); assert_se(r > 0); return 0; diff --git a/src/import/pull-job.c b/src/import/pull-job.c index 33512cd77a..9ab3776e50 100644 --- a/src/import/pull-job.c +++ b/src/import/pull-job.c @@ -75,7 +75,6 @@ static int pull_job_restart(PullJob *j, const char *new_url) { j->error = 0; j->payload = mfree(j->payload); j->payload_size = 0; - j->payload_allocated = 0; j->written_compressed = 0; j->written_uncompressed = 0; j->content_length = UINT64_MAX; @@ -266,7 +265,7 @@ static int pull_job_write_uncompressed(const void *p, size_t sz, void *userdata) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write"); } else { - if (!GREEDY_REALLOC(j->payload, j->payload_allocated, j->payload_size + sz)) + if (!GREEDY_REALLOC(j->payload, j->payload_size + sz)) return log_oom(); memcpy(j->payload + j->payload_size, p, sz); @@ -371,7 +370,6 @@ static int pull_job_detect_compression(PullJob *j) { j->payload = NULL; j->payload_size = 0; - j->payload_allocated = 0; j->state = PULL_JOB_RUNNING; @@ -395,7 +393,7 @@ static size_t pull_job_write_callback(void *contents, size_t size, size_t nmemb, case PULL_JOB_ANALYZING: /* Let's first check what it actually is */ - if (!GREEDY_REALLOC(j->payload, j->payload_allocated, j->payload_size + sz)) { + if (!GREEDY_REALLOC(j->payload, j->payload_size + sz)) { r = log_oom(); goto fail; } diff --git a/src/import/pull-job.h b/src/import/pull-job.h index 8e416d51ba..023ccc8302 100644 --- a/src/import/pull-job.h +++ b/src/import/pull-job.h @@ -57,7 +57,6 @@ struct PullJob { uint8_t *payload; size_t payload_size; - size_t payload_allocated; int disk_fd; diff --git a/src/journal-remote/journal-remote.c b/src/journal-remote/journal-remote.c index 13461dbe41..6e5aebdc48 100644 --- a/src/journal-remote/journal-remote.c +++ b/src/journal-remote/journal-remote.c @@ -171,7 +171,7 @@ static int get_source_for_fd(RemoteServer *s, assert(fd >= 0); assert(source); - if (!GREEDY_REALLOC0(s->sources, s->sources_size, fd + 1)) + if (!GREEDY_REALLOC0(s->sources, fd + 1)) return log_oom(); r = journal_remote_get_writer(s, name, &writer); @@ -197,7 +197,7 @@ static int remove_source(RemoteServer *s, int fd) { RemoteSource *source; assert(s); - assert(fd >= 0 && fd < (ssize_t) s->sources_size); + assert(fd >= 0 && fd < (ssize_t) MALLOC_ELEMENTSOF(s->sources)); source = s->sources[fd]; if (source) { @@ -352,8 +352,7 @@ void journal_remote_server_destroy(RemoteServer *s) { hashmap_free_with_destructor(s->daemons, MHDDaemonWrapper_free); #endif - assert(s->sources_size == 0 || s->sources); - for (i = 0; i < s->sources_size; i++) + for (i = 0; i < MALLOC_ELEMENTSOF(s->sources); i++) remove_source(s, i); free(s->sources); @@ -388,7 +387,7 @@ int journal_remote_handle_raw_source( * 0 if data is currently exhausted, negative on error. */ - assert(fd >= 0 && fd < (ssize_t) s->sources_size); + assert(fd >= 0 && fd < (ssize_t) MALLOC_ELEMENTSOF(s->sources)); source = s->sources[fd]; assert(source->importer.fd == fd); diff --git a/src/journal-remote/journal-remote.h b/src/journal-remote/journal-remote.h index 247ffa9765..45176e964d 100644 --- a/src/journal-remote/journal-remote.h +++ b/src/journal-remote/journal-remote.h @@ -23,7 +23,6 @@ struct MHDDaemonWrapper { struct RemoteServer { RemoteSource **sources; - size_t sources_size; size_t active; sd_event *events; diff --git a/src/journal/fuzz-journald.c b/src/journal/fuzz-journald.c index e2f73ffa7e..ff1746e122 100644 --- a/src/journal/fuzz-journald.c +++ b/src/journal/fuzz-journald.c @@ -22,7 +22,6 @@ void dummy_server_init(Server *s, const uint8_t *buffer, size_t size) { if (buffer) { s->buffer = memdup_suffix0(buffer, size); assert_se(s->buffer); - s->buffer_size = size + 1; } } diff --git a/src/journal/journald-audit.c b/src/journal/journald-audit.c index 744f750ca3..507b12137d 100644 --- a/src/journal/journald-audit.c +++ b/src/journal/journald-audit.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include <malloc.h> + #include "alloc-util.h" #include "audit-type.h" #include "errno-util.h" @@ -13,12 +15,17 @@ typedef struct MapField { const char *audit_field; const char *journal_field; - int (*map)(const char *field, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov); + int (*map)(const char *field, const char **p, struct iovec **iov, size_t *n_iov); } MapField; -static int map_simple_field(const char *field, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov) { +static int map_simple_field( + const char *field, + const char **p, + struct iovec **iov, + size_t *n_iov) { + _cleanup_free_ char *c = NULL; - size_t l = 0, allocated = 0; + size_t l = 0; const char *e; assert(field); @@ -27,14 +34,13 @@ static int map_simple_field(const char *field, const char **p, struct iovec **io assert(n_iov); l = strlen(field); - allocated = l + 1; - c = malloc(allocated); + c = malloc(l + 1); if (!c) return -ENOMEM; memcpy(c, field, l); for (e = *p; !IN_SET(*e, 0, ' '); e++) { - if (!GREEDY_REALLOC(c, allocated, l+2)) + if (!GREEDY_REALLOC(c, l+2)) return -ENOMEM; c[l++] = *e; @@ -42,7 +48,7 @@ static int map_simple_field(const char *field, const char **p, struct iovec **io c[l] = 0; - if (!GREEDY_REALLOC(*iov, *n_iov_allocated, *n_iov + 1)) + if (!GREEDY_REALLOC(*iov, *n_iov + 1)) return -ENOMEM; (*iov)[(*n_iov)++] = IOVEC_MAKE(c, l); @@ -53,7 +59,13 @@ static int map_simple_field(const char *field, const char **p, struct iovec **io return 1; } -static int map_string_field_internal(const char *field, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov, bool filter_printable) { +static int map_string_field_internal( + const char *field, + const char **p, + struct iovec **iov, + size_t *n_iov, + bool filter_printable) { + _cleanup_free_ char *c = NULL; const char *s, *e; size_t l; @@ -83,11 +95,8 @@ static int map_string_field_internal(const char *field, const char **p, struct i } else if (unhexchar(**p) >= 0) { /* Hexadecimal escaping */ - size_t allocated = 0; - l = strlen(field); - allocated = l + 2; - c = malloc(allocated); + c = malloc(l + 2); if (!c) return -ENOMEM; @@ -109,7 +118,7 @@ static int map_string_field_internal(const char *field, const char **p, struct i if (filter_printable && x < (uint8_t) ' ') x = (uint8_t) ' '; - if (!GREEDY_REALLOC(c, allocated, l+2)) + if (!GREEDY_REALLOC(c, l+2)) return -ENOMEM; c[l++] = (char) x; @@ -119,7 +128,7 @@ static int map_string_field_internal(const char *field, const char **p, struct i } else return 0; - if (!GREEDY_REALLOC(*iov, *n_iov_allocated, *n_iov + 1)) + if (!GREEDY_REALLOC(*iov, *n_iov + 1)) return -ENOMEM; (*iov)[(*n_iov)++] = IOVEC_MAKE(c, l); @@ -130,15 +139,20 @@ static int map_string_field_internal(const char *field, const char **p, struct i return 1; } -static int map_string_field(const char *field, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov) { - return map_string_field_internal(field, p, iov, n_iov_allocated, n_iov, false); +static int map_string_field(const char *field, const char **p, struct iovec **iov, size_t *n_iov) { + return map_string_field_internal(field, p, iov, n_iov, false); } -static int map_string_field_printable(const char *field, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov) { - return map_string_field_internal(field, p, iov, n_iov_allocated, n_iov, true); +static int map_string_field_printable(const char *field, const char **p, struct iovec **iov, size_t *n_iov) { + return map_string_field_internal(field, p, iov, n_iov, true); } -static int map_generic_field(const char *prefix, const char **p, struct iovec **iov, size_t *n_iov_allocated, size_t *n_iov) { +static int map_generic_field( + const char *prefix, + const char **p, + struct iovec **iov, + size_t *n_iov) { + const char *e, *f; char *c, *t; int r; @@ -182,7 +196,7 @@ static int map_generic_field(const char *prefix, const char **p, struct iovec ** e++; - r = map_simple_field(c, &e, iov, n_iov_allocated, n_iov); + r = map_simple_field(c, &e, iov, n_iov); if (r < 0) return r; @@ -242,14 +256,12 @@ static int map_all_fields( const char *prefix, bool handle_msg, struct iovec **iov, - size_t *n_iov_allocated, size_t *n_iov) { int r; assert(p); assert(iov); - assert(n_iov_allocated); assert(n_iov); for (;;) { @@ -284,7 +296,7 @@ static int map_all_fields( if (!c) return -ENOMEM; - return map_all_fields(c, map_fields_userspace, "AUDIT_FIELD_", false, iov, n_iov_allocated, n_iov); + return map_all_fields(c, map_fields_userspace, "AUDIT_FIELD_", false, iov, n_iov); } } @@ -294,7 +306,7 @@ static int map_all_fields( if (!v) continue; - r = m->map(m->journal_field, &v, iov, n_iov_allocated, n_iov); + r = m->map(m->journal_field, &v, iov, n_iov); if (r < 0) return log_debug_errno(r, "Failed to parse audit array: %m"); @@ -306,7 +318,7 @@ static int map_all_fields( } if (!mapped) { - r = map_generic_field(prefix, &p, iov, n_iov_allocated, n_iov); + r = map_generic_field(prefix, &p, iov, n_iov); if (r < 0) return log_debug_errno(r, "Failed to parse audit array: %m"); @@ -318,7 +330,7 @@ static int map_all_fields( } void process_audit_string(Server *s, int type, const char *data, size_t size) { - size_t n_iov_allocated = 0, n_iov = 0, z; + size_t n_iov = 0, z; _cleanup_free_ struct iovec *iov = NULL; uint64_t seconds, msec, id; const char *p, *type_name; @@ -359,8 +371,7 @@ void process_audit_string(Server *s, int type, const char *data, size_t size) { if (isempty(p)) return; - n_iov_allocated = N_IOVEC_META_FIELDS + 8; - iov = new(struct iovec, n_iov_allocated); + iov = new(struct iovec, N_IOVEC_META_FIELDS + 8); if (!iov) { log_oom(); return; @@ -392,14 +403,14 @@ void process_audit_string(Server *s, int type, const char *data, size_t size) { z = n_iov; - map_all_fields(p, map_fields_kernel, "_AUDIT_FIELD_", true, &iov, &n_iov_allocated, &n_iov); + map_all_fields(p, map_fields_kernel, "_AUDIT_FIELD_", true, &iov, &n_iov); - if (!GREEDY_REALLOC(iov, n_iov_allocated, n_iov + N_IOVEC_META_FIELDS)) { + if (!GREEDY_REALLOC(iov, n_iov + N_IOVEC_META_FIELDS)) { log_oom(); goto finish; } - server_dispatch_message(s, iov, n_iov, n_iov_allocated, NULL, NULL, LOG_NOTICE, 0); + server_dispatch_message(s, iov, n_iov, MALLOC_ELEMENTSOF(iov), NULL, NULL, LOG_NOTICE, 0); finish: /* free() all entries that map_all_fields() added. All others diff --git a/src/journal/journald-context.c b/src/journal/journald-context.c index 694056d558..27608ff089 100644 --- a/src/journal/journald-context.c +++ b/src/journal/journald-context.c @@ -378,8 +378,8 @@ static int client_context_read_extra_fields( Server *s, ClientContext *c) { - size_t size = 0, n_iovec = 0, n_allocated = 0, left; _cleanup_free_ struct iovec *iovec = NULL; + size_t size = 0, n_iovec = 0, left; _cleanup_free_ void *data = NULL; _cleanup_fclose_ FILE *f = NULL; struct stat st; @@ -445,7 +445,7 @@ static int client_context_read_extra_fields( if (!journal_field_valid((const char *) field, eq - field, false)) return -EBADMSG; - if (!GREEDY_REALLOC(iovec, n_allocated, n_iovec+1)) + if (!GREEDY_REALLOC(iovec, n_iovec+1)) return -ENOMEM; iovec[n_iovec++] = IOVEC_MAKE(field, v); diff --git a/src/journal/journald-native.c b/src/journal/journald-native.c index 102814a403..032578822d 100644 --- a/src/journal/journald-native.c +++ b/src/journal/journald-native.c @@ -105,7 +105,7 @@ static int server_process_entry( * * Note that *remaining is altered on both success and failure. */ - size_t n = 0, j, tn = SIZE_MAX, m = 0, entry_size = 0; + size_t n = 0, j, tn = SIZE_MAX, entry_size = 0; char *identifier = NULL, *message = NULL; struct iovec *iovec = NULL; int priority = LOG_INFO; @@ -146,7 +146,7 @@ static int server_process_entry( } /* n existing properties, 1 new, +1 for _TRANSPORT */ - if (!GREEDY_REALLOC(iovec, m, + if (!GREEDY_REALLOC(iovec, n + 2 + N_IOVEC_META_FIELDS + N_IOVEC_OBJECT_FIELDS + client_context_extra_fields_n_iovec(context))) { @@ -273,7 +273,7 @@ static int server_process_entry( server_forward_wall(s, priority, identifier, message, ucred); } - server_dispatch_message(s, iovec, n, m, context, tv, priority, object_pid); + server_dispatch_message(s, iovec, n, MALLOC_ELEMENTSOF(iovec), context, tv, priority, object_pid); finish: for (j = 0; j < n; j++) { diff --git a/src/journal/journald-server.c b/src/journal/journald-server.c index 6d87fa0f84..2907e26b77 100644 --- a/src/journal/journald-server.c +++ b/src/journal/journald-server.c @@ -1254,12 +1254,12 @@ int server_process_datagram( uint32_t revents, void *userdata) { + size_t label_len = 0, m; Server *s = userdata; struct ucred *ucred = NULL; struct timeval *tv = NULL; struct cmsghdr *cmsg; char *label = NULL; - size_t label_len = 0, m; struct iovec iovec; ssize_t n; int *fds = NULL, v = 0; @@ -1302,10 +1302,10 @@ int server_process_datagram( (size_t) LINE_MAX, ALIGN(sizeof(struct nlmsghdr)) + ALIGN((size_t) MAX_AUDIT_MESSAGE_LENGTH)) + 1); - if (!GREEDY_REALLOC(s->buffer, s->buffer_size, m)) + if (!GREEDY_REALLOC(s->buffer, m)) return log_oom(); - iovec = IOVEC_MAKE(s->buffer, s->buffer_size - 1); /* Leave room for trailing NUL we add later */ + iovec = IOVEC_MAKE(s->buffer, MALLOC_ELEMENTSOF(s->buffer) - 1); /* Leave room for trailing NUL we add later */ n = recvmsg_safe(fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC); if (IN_SET(n, -EINTR, -EAGAIN)) diff --git a/src/journal/journald-server.h b/src/journal/journald-server.h index 09f80475a7..53e75ff3b0 100644 --- a/src/journal/journald-server.h +++ b/src/journal/journald-server.h @@ -95,7 +95,6 @@ struct Server { uint64_t seqnum; char *buffer; - size_t buffer_size; JournalRateLimit *ratelimit; usec_t sync_interval_usec; diff --git a/src/journal/journald-stream.c b/src/journal/journald-stream.c index 85723f5b30..c6720b6b13 100644 --- a/src/journal/journald-stream.c +++ b/src/journal/journald-stream.c @@ -90,7 +90,6 @@ struct StdoutStream { char *buffer; size_t length; - size_t allocated; sd_event_source *event_source; @@ -552,8 +551,8 @@ static int stdout_stream_scan( static int stdout_stream_process(sd_event_source *es, int fd, uint32_t revents, void *userdata) { CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control; + size_t limit, consumed, allocated; StdoutStream *s = userdata; - size_t limit, consumed; struct ucred *ucred; struct iovec iovec; ssize_t l; @@ -575,16 +574,19 @@ static int stdout_stream_process(sd_event_source *es, int fd, uint32_t revents, } /* If the buffer is almost full, add room for another 1K */ - if (s->length + 512 >= s->allocated) { - if (!GREEDY_REALLOC(s->buffer, s->allocated, s->length + 1 + 1024)) { + allocated = MALLOC_ELEMENTSOF(s->buffer); + if (s->length + 512 >= allocated) { + if (!GREEDY_REALLOC(s->buffer, s->length + 1 + 1024)) { log_oom(); goto terminate; } + + allocated = MALLOC_ELEMENTSOF(s->buffer); } /* Try to make use of the allocated buffer in full, but never read more than the configured line size. Also, * always leave room for a terminating NUL we might need to add. */ - limit = MIN(s->allocated - 1, MAX(s->server->line_max, STDOUT_STREAM_SETUP_PROTOCOL_LINE_MAX)); + limit = MIN(allocated - 1, MAX(s->server->line_max, STDOUT_STREAM_SETUP_PROTOCOL_LINE_MAX)); assert(s->length <= limit); iovec = IOVEC_MAKE(s->buffer + s->length, limit - s->length); diff --git a/src/libsystemd-network/dhcp-lease-internal.h b/src/libsystemd-network/dhcp-lease-internal.h index 49392d1bea..35a74dd7c2 100644 --- a/src/libsystemd-network/dhcp-lease-internal.h +++ b/src/libsystemd-network/dhcp-lease-internal.h @@ -53,7 +53,7 @@ struct sd_dhcp_lease { DHCPServerData servers[_SD_DHCP_LEASE_SERVER_TYPE_MAX]; struct sd_dhcp_route *static_route; - size_t static_route_size, static_route_allocated; + size_t static_route_size; uint16_t mtu; /* 0 if unset */ diff --git a/src/libsystemd-network/dhcp6-internal.h b/src/libsystemd-network/dhcp6-internal.h index 1e5a6b0e37..34e1f61cb0 100644 --- a/src/libsystemd-network/dhcp6-internal.h +++ b/src/libsystemd-network/dhcp6-internal.h @@ -104,8 +104,7 @@ int dhcp6_option_parse(uint8_t **buf, size_t *buflen, uint16_t *optcode, int dhcp6_option_parse_status(DHCP6Option *option, size_t len); int dhcp6_option_parse_ia(sd_dhcp6_client *client, DHCP6Option *iaoption, DHCP6IA *ia, uint16_t *ret_status_code); int dhcp6_option_parse_ip6addrs(uint8_t *optval, uint16_t optlen, - struct in6_addr **addrs, size_t count, - size_t *allocated); + struct in6_addr **addrs, size_t count); int dhcp6_option_parse_domainname_list(const uint8_t *optval, uint16_t optlen, char ***str_arr); int dhcp6_option_parse_domainname(const uint8_t *optval, uint16_t optlen, char **str); diff --git a/src/libsystemd-network/dhcp6-lease-internal.h b/src/libsystemd-network/dhcp6-lease-internal.h index e9e2362d6f..391b4f1fa9 100644 --- a/src/libsystemd-network/dhcp6-lease-internal.h +++ b/src/libsystemd-network/dhcp6-lease-internal.h @@ -27,12 +27,10 @@ struct sd_dhcp6_lease { struct in6_addr *dns; size_t dns_count; - size_t dns_allocated; char **domains; size_t domains_count; struct in6_addr *ntp; size_t ntp_count; - size_t ntp_allocated; char **ntp_fqdn; size_t ntp_fqdn_count; char *fqdn; diff --git a/src/libsystemd-network/dhcp6-option.c b/src/libsystemd-network/dhcp6-option.c index 6aca898d33..97ef03a2d2 100644 --- a/src/libsystemd-network/dhcp6-option.c +++ b/src/libsystemd-network/dhcp6-option.c @@ -678,14 +678,12 @@ int dhcp6_option_parse_ia(sd_dhcp6_client *client, DHCP6Option *iaoption, DHCP6I } int dhcp6_option_parse_ip6addrs(uint8_t *optval, uint16_t optlen, - struct in6_addr **addrs, size_t count, - size_t *allocated) { + struct in6_addr **addrs, size_t count) { if (optlen == 0 || optlen % sizeof(struct in6_addr) != 0) return -EINVAL; - if (!GREEDY_REALLOC(*addrs, *allocated, - count * sizeof(struct in6_addr) + optlen)) + if (!GREEDY_REALLOC(*addrs, count * sizeof(struct in6_addr) + optlen)) return -ENOMEM; memcpy(*addrs + count, optval, optlen); @@ -697,10 +695,10 @@ int dhcp6_option_parse_ip6addrs(uint8_t *optval, uint16_t optlen, static int parse_domain(const uint8_t **data, uint16_t *len, char **out_domain) { _cleanup_free_ char *ret = NULL; - size_t n = 0, allocated = 0; const uint8_t *optval = *data; uint16_t optlen = *len; bool first = true; + size_t n = 0; int r; if (optlen <= 1) @@ -730,7 +728,7 @@ static int parse_domain(const uint8_t **data, uint16_t *len, char **out_domain) optval += c; optlen -= c; - if (!GREEDY_REALLOC(ret, allocated, n + !first + DNS_LABEL_ESCAPED_MAX)) + if (!GREEDY_REALLOC(ret, n + !first + DNS_LABEL_ESCAPED_MAX)) return -ENOMEM; if (first) @@ -746,7 +744,7 @@ static int parse_domain(const uint8_t **data, uint16_t *len, char **out_domain) } if (n) { - if (!GREEDY_REALLOC(ret, allocated, n + 1)) + if (!GREEDY_REALLOC(ret, n + 1)) return -ENOMEM; ret[n] = 0; } diff --git a/src/libsystemd-network/ndisc-router.c b/src/libsystemd-network/ndisc-router.c index 46f30332bb..6db07b0dbc 100644 --- a/src/libsystemd-network/ndisc-router.c +++ b/src/libsystemd-network/ndisc-router.c @@ -630,7 +630,7 @@ static int get_dnssl_info(sd_ndisc_router *rt, uint8_t **ret) { _public_ int sd_ndisc_router_dnssl_get_domains(sd_ndisc_router *rt, char ***ret) { _cleanup_strv_free_ char **l = NULL; _cleanup_free_ char *e = NULL; - size_t allocated = 0, n = 0, left; + size_t n = 0, left; uint8_t *ri, *p; bool first = true; int r; @@ -691,7 +691,7 @@ _public_ int sd_ndisc_router_dnssl_get_domains(sd_ndisc_router *rt, char ***ret) if (1U + *p + 1U > left) return -EBADMSG; - if (!GREEDY_REALLOC(e, allocated, n + !first + DNS_LABEL_ESCAPED_MAX + 1U)) + if (!GREEDY_REALLOC(e, n + !first + DNS_LABEL_ESCAPED_MAX + 1U)) return -ENOMEM; if (first) diff --git a/src/libsystemd-network/network-internal.c b/src/libsystemd-network/network-internal.c index 12b73cd50d..bc7aec2f9d 100644 --- a/src/libsystemd-network/network-internal.c +++ b/src/libsystemd-network/network-internal.c @@ -158,13 +158,12 @@ void serialize_dhcp_routes(FILE *f, const char *key, sd_dhcp_route **routes, siz fputs("\n", f); } -int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, size_t *ret_allocated, const char *string) { +int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, const char *string) { _cleanup_free_ struct sd_dhcp_route *routes = NULL; - size_t size = 0, allocated = 0; + size_t size = 0; assert(ret); assert(ret_size); - assert(ret_allocated); assert(string); /* WORD FORMAT: dst_ip/dst_prefixlen,gw_ip */ @@ -180,7 +179,7 @@ int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, size_t if (r == 0) break; - if (!GREEDY_REALLOC(routes, allocated, size + 1)) + if (!GREEDY_REALLOC(routes, size + 1)) return -ENOMEM; tok = word; @@ -220,7 +219,6 @@ int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, size_t } *ret_size = size; - *ret_allocated = allocated; *ret = TAKE_PTR(routes); return 0; diff --git a/src/libsystemd-network/network-internal.h b/src/libsystemd-network/network-internal.h index e5b853c0cd..895a00d01b 100644 --- a/src/libsystemd-network/network-internal.h +++ b/src/libsystemd-network/network-internal.h @@ -22,7 +22,7 @@ struct sd_dhcp_route; struct sd_dhcp_lease; void serialize_dhcp_routes(FILE *f, const char *key, sd_dhcp_route **routes, size_t size); -int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, size_t *ret_allocated, const char *string); +int deserialize_dhcp_routes(struct sd_dhcp_route **ret, size_t *ret_size, const char *string); /* It is not necessary to add deserialize_dhcp_option(). Use unhexmem() instead. */ int serialize_dhcp_option(FILE *f, const char *key, const void *data, size_t size); diff --git a/src/libsystemd-network/sd-dhcp-lease.c b/src/libsystemd-network/sd-dhcp-lease.c index 6d88c88e6b..095a4ee683 100644 --- a/src/libsystemd-network/sd-dhcp-lease.c +++ b/src/libsystemd-network/sd-dhcp-lease.c @@ -440,14 +440,13 @@ static int lease_parse_sip_server(const uint8_t *option, size_t len, struct in_a static int lease_parse_routes( const uint8_t *option, size_t len, - struct sd_dhcp_route **routes, size_t *routes_size, size_t *routes_allocated) { + struct sd_dhcp_route **routes, size_t *routes_size) { struct in_addr addr; assert(option || len <= 0); assert(routes); assert(routes_size); - assert(routes_allocated); if (len <= 0) return 0; @@ -455,7 +454,7 @@ static int lease_parse_routes( if (len % 8 != 0) return -EINVAL; - if (!GREEDY_REALLOC(*routes, *routes_allocated, *routes_size + (len / 8))) + if (!GREEDY_REALLOC(*routes, *routes_size + (len / 8))) return -ENOMEM; while (len >= 8) { @@ -486,12 +485,11 @@ static int lease_parse_routes( /* parses RFC3442 Classless Static Route Option */ static int lease_parse_classless_routes( const uint8_t *option, size_t len, - struct sd_dhcp_route **routes, size_t *routes_size, size_t *routes_allocated) { + struct sd_dhcp_route **routes, size_t *routes_size) { assert(option || len <= 0); assert(routes); assert(routes_size); - assert(routes_allocated); if (len <= 0) return 0; @@ -502,7 +500,7 @@ static int lease_parse_classless_routes( uint8_t dst_octets; struct sd_dhcp_route *route; - if (!GREEDY_REALLOC(*routes, *routes_allocated, *routes_size + 1)) + if (!GREEDY_REALLOC(*routes, *routes_size + 1)) return -ENOMEM; route = *routes + *routes_size; @@ -616,7 +614,7 @@ int dhcp_lease_parse_options(uint8_t code, uint8_t len, const void *option, void break; case SD_DHCP_OPTION_STATIC_ROUTE: - r = lease_parse_routes(option, len, &lease->static_route, &lease->static_route_size, &lease->static_route_allocated); + r = lease_parse_routes(option, len, &lease->static_route, &lease->static_route_size); if (r < 0) log_debug_errno(r, "Failed to parse static routes, ignoring: %m"); break; @@ -678,8 +676,7 @@ int dhcp_lease_parse_options(uint8_t code, uint8_t len, const void *option, void r = lease_parse_classless_routes( option, len, &lease->static_route, - &lease->static_route_size, - &lease->static_route_allocated); + &lease->static_route_size); if (r < 0) log_debug_errno(r, "Failed to parse classless routes, ignoring: %m"); break; @@ -747,7 +744,7 @@ int dhcp_lease_parse_search_domains(const uint8_t *option, size_t len, char ***d while (pos < len) { _cleanup_free_ char *name = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; size_t jump_barrier = pos, next_chunk = 0; bool first = true; @@ -767,7 +764,7 @@ int dhcp_lease_parse_search_domains(const uint8_t *option, size_t len, char ***d if (pos >= len) return -EBADMSG; - if (!GREEDY_REALLOC(name, allocated, n + !first + DNS_LABEL_ESCAPED_MAX)) + if (!GREEDY_REALLOC(name, n + !first + DNS_LABEL_ESCAPED_MAX)) return -ENOMEM; if (first) @@ -806,7 +803,7 @@ int dhcp_lease_parse_search_domains(const uint8_t *option, size_t len, char ***d return -EBADMSG; } - if (!GREEDY_REALLOC(name, allocated, n + 1)) + if (!GREEDY_REALLOC(name, n + 1)) return -ENOMEM; name[n] = 0; @@ -1232,7 +1229,6 @@ int dhcp_lease_load(sd_dhcp_lease **ret, const char *lease_file) { r = deserialize_dhcp_routes( &lease->static_route, &lease->static_route_size, - &lease->static_route_allocated, routes); if (r < 0) log_debug_errno(r, "Failed to parse DHCP routes %s, ignoring: %m", routes); diff --git a/src/libsystemd-network/sd-dhcp6-client.c b/src/libsystemd-network/sd-dhcp6-client.c index 10f82996c8..855a61bb21 100644 --- a/src/libsystemd-network/sd-dhcp6-client.c +++ b/src/libsystemd-network/sd-dhcp6-client.c @@ -66,7 +66,6 @@ struct sd_dhcp6_client { bool information_request; bool iaid_set; be16_t *req_opts; - size_t req_opts_allocated; size_t req_opts_len; char *fqdn; char *mudurl; @@ -456,8 +455,7 @@ int sd_dhcp6_client_set_request_option(sd_dhcp6_client *client, uint16_t option) if (client->req_opts[t] == htobe16(option)) return -EEXIST; - if (!GREEDY_REALLOC(client->req_opts, client->req_opts_allocated, - client->req_opts_len + 1)) + if (!GREEDY_REALLOC(client->req_opts, client->req_opts_len + 1)) return -ENOMEM; client->req_opts[client->req_opts_len++] = htobe16(option); diff --git a/src/libsystemd-network/sd-dhcp6-lease.c b/src/libsystemd-network/sd-dhcp6-lease.c index aca2c1f7e0..9082185bca 100644 --- a/src/libsystemd-network/sd-dhcp6-lease.c +++ b/src/libsystemd-network/sd-dhcp6-lease.c @@ -203,8 +203,7 @@ int dhcp6_lease_set_dns(sd_dhcp6_lease *lease, uint8_t *optval, size_t optlen) { return 0; r = dhcp6_option_parse_ip6addrs(optval, optlen, &lease->dns, - lease->dns_count, - &lease->dns_allocated); + lease->dns_count); if (r < 0) return r; @@ -269,7 +268,6 @@ int dhcp6_lease_set_ntp(sd_dhcp6_lease *lease, uint8_t *optval, size_t optlen) { lease->ntp = mfree(lease->ntp); lease->ntp_count = 0; - lease->ntp_allocated = 0; while ((r = dhcp6_option_parse(&optval, &optlen, &subopt, &sublen, &subval)) >= 0) { @@ -284,8 +282,7 @@ int dhcp6_lease_set_ntp(sd_dhcp6_lease *lease, uint8_t *optval, size_t optlen) { s = dhcp6_option_parse_ip6addrs(subval, sublen, &lease->ntp, - lease->ntp_count, - &lease->ntp_allocated); + lease->ntp_count); if (s < 0) return s; @@ -327,8 +324,7 @@ int dhcp6_lease_set_sntp(sd_dhcp6_lease *lease, uint8_t *optval, size_t optlen) /* Using deprecated SNTP information */ r = dhcp6_option_parse_ip6addrs(optval, optlen, &lease->ntp, - lease->ntp_count, - &lease->ntp_allocated); + lease->ntp_count); if (r < 0) return r; diff --git a/src/libsystemd/sd-bus/bus-creds.c b/src/libsystemd/sd-bus/bus-creds.c index 5e748fdb46..4468b45dd1 100644 --- a/src/libsystemd/sd-bus/bus-creds.c +++ b/src/libsystemd/sd-bus/bus-creds.c @@ -882,8 +882,6 @@ int bus_creds_add_more(sd_bus_creds *c, uint64_t mask, pid_t pid, pid_t tid) { if (missing & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) { p = startswith(line, "Groups:"); if (p) { - size_t allocated = 0; - for (;;) { unsigned long g; int n = 0; @@ -895,7 +893,7 @@ int bus_creds_add_more(sd_bus_creds *c, uint64_t mask, pid_t pid, pid_t tid) { if (sscanf(p, "%lu%n", &g, &n) != 1) return -EIO; - if (!GREEDY_REALLOC(c->supplementary_gids, allocated, c->n_supplementary_gids+1)) + if (!GREEDY_REALLOC(c->supplementary_gids, c->n_supplementary_gids+1)) return -ENOMEM; c->supplementary_gids[c->n_supplementary_gids++] = (gid_t) g; diff --git a/src/libsystemd/sd-bus/bus-internal.h b/src/libsystemd/sd-bus/bus-internal.h index 4a45507da5..51673ad1c5 100644 --- a/src/libsystemd/sd-bus/bus-internal.h +++ b/src/libsystemd/sd-bus/bus-internal.h @@ -222,12 +222,10 @@ struct sd_bus { sd_bus_message **rqueue; size_t rqueue_size; - size_t rqueue_allocated; sd_bus_message **wqueue; size_t wqueue_size; size_t windex; - size_t wqueue_allocated; uint64_t cookie; uint64_t read_counter; /* A counter for each incoming msg */ diff --git a/src/libsystemd/sd-bus/bus-match.c b/src/libsystemd/sd-bus/bus-match.c index 96b50aeaed..648f1ca62f 100644 --- a/src/libsystemd/sd-bus/bus-match.c +++ b/src/libsystemd/sd-bus/bus-match.c @@ -711,7 +711,6 @@ int bus_match_parse( unsigned *ret_n_components) { struct bus_match_component *components = NULL; - size_t components_allocated = 0; unsigned n_components = 0; int r; @@ -724,7 +723,6 @@ int bus_match_parse( enum bus_match_node_type t; unsigned j = 0; _cleanup_free_ char *value = NULL; - size_t value_allocated = 0; bool escaped = false, quoted; uint8_t u; @@ -780,7 +778,7 @@ int bus_match_parse( } } - if (!GREEDY_REALLOC(value, value_allocated, j + 2)) { + if (!GREEDY_REALLOC(value, j + 2)) { r = -ENOMEM; goto fail; } @@ -806,7 +804,7 @@ int bus_match_parse( } else u = 0; - if (!GREEDY_REALLOC(components, components_allocated, n_components + 1)) { + if (!GREEDY_REALLOC(components, n_components + 1)) { r = -ENOMEM; goto fail; } diff --git a/src/libsystemd/sd-bus/bus-message.c b/src/libsystemd/sd-bus/bus-message.c index b25064b672..20f7396c74 100644 --- a/src/libsystemd/sd-bus/bus-message.c +++ b/src/libsystemd/sd-bus/bus-message.c @@ -117,7 +117,6 @@ static void message_reset_containers(sd_bus_message *m) { message_free_last_container(m); m->containers = mfree(m->containers); - m->containers_allocated = 0; m->root_container.index = 0; } @@ -1289,7 +1288,7 @@ static int message_add_offset(sd_bus_message *m, size_t offset) { if (!c->need_offsets) return 0; - if (!GREEDY_REALLOC(c->offsets, c->offsets_allocated, c->n_offsets + 1)) + if (!GREEDY_REALLOC(c->offsets, c->n_offsets + 1)) return -ENOMEM; c->offsets[c->n_offsets++] = offset; @@ -2031,7 +2030,7 @@ _public_ int sd_bus_message_open_container( assert_return(!m->poisoned, -ESTALE); /* Make sure we have space for one more container */ - if (!GREEDY_REALLOC(m->containers, m->containers_allocated, m->n_containers + 1)) { + if (!GREEDY_REALLOC(m->containers, m->n_containers + 1)) { m->poisoned = true; return -ENOMEM; } @@ -4111,7 +4110,7 @@ _public_ int sd_bus_message_enter_container(sd_bus_message *m, if (m->n_containers >= BUS_CONTAINER_DEPTH) return -EBADMSG; - if (!GREEDY_REALLOC(m->containers, m->containers_allocated, m->n_containers + 1)) + if (!GREEDY_REALLOC(m->containers, m->n_containers + 1)) return -ENOMEM; if (message_end_of_signature(m)) diff --git a/src/libsystemd/sd-bus/bus-message.h b/src/libsystemd/sd-bus/bus-message.h index 3561737e2f..e5bf5df160 100644 --- a/src/libsystemd/sd-bus/bus-message.h +++ b/src/libsystemd/sd-bus/bus-message.h @@ -26,7 +26,7 @@ struct bus_container { uint32_t *array_size; /* gvariant: list of offsets to end of children if this is struct/dict entry/array */ - size_t *offsets, n_offsets, offsets_allocated, offset_index; + size_t *offsets, n_offsets, offset_index; size_t item_size; char *peeked_signature; @@ -111,7 +111,6 @@ struct sd_bus_message { struct bus_container root_container, *containers; size_t n_containers; - size_t containers_allocated; struct iovec *iovec; struct iovec iovec_fixed[2]; diff --git a/src/libsystemd/sd-bus/bus-socket.c b/src/libsystemd/sd-bus/bus-socket.c index 832526cc1b..16e61e1e89 100644 --- a/src/libsystemd/sd-bus/bus-socket.c +++ b/src/libsystemd/sd-bus/bus-socket.c @@ -700,7 +700,7 @@ int bus_socket_start_auth(sd_bus *b) { static int bus_socket_inotify_setup(sd_bus *b) { _cleanup_free_ int *new_watches = NULL; _cleanup_free_ char *absolute = NULL; - size_t n_allocated = 0, n = 0, done = 0, i; + size_t n = 0, done = 0, i; unsigned max_follow = 32; const char *p; int wd, r; @@ -737,7 +737,7 @@ static int bus_socket_inotify_setup(sd_bus *b) { * that exists we want to know when files are created or moved into it. For all parents of it we just care if * they are removed or renamed. */ - if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) { + if (!GREEDY_REALLOC(new_watches, n + 1)) { r = -ENOMEM; goto fail; } @@ -786,7 +786,7 @@ static int bus_socket_inotify_setup(sd_bus *b) { goto fail; } - if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) { + if (!GREEDY_REALLOC(new_watches, n + 1)) { r = -ENOMEM; goto fail; } diff --git a/src/libsystemd/sd-bus/sd-bus.c b/src/libsystemd/sd-bus/sd-bus.c index 31f527c571..0ec0d8d26e 100644 --- a/src/libsystemd/sd-bus/sd-bus.c +++ b/src/libsystemd/sd-bus/sd-bus.c @@ -153,13 +153,11 @@ static void bus_reset_queues(sd_bus *b) { bus_message_unref_queued(b->rqueue[--b->rqueue_size], b); b->rqueue = mfree(b->rqueue); - b->rqueue_allocated = 0; while (b->wqueue_size > 0) bus_message_unref_queued(b->wqueue[--b->wqueue_size], b); b->wqueue = mfree(b->wqueue); - b->wqueue_allocated = 0; } static sd_bus* bus_free(sd_bus *b) { @@ -253,7 +251,7 @@ _public_ int sd_bus_new(sd_bus **ret) { }; /* We guarantee that wqueue always has space for at least one entry */ - if (!GREEDY_REALLOC(b->wqueue, b->wqueue_allocated, 1)) + if (!GREEDY_REALLOC(b->wqueue, 1)) return -ENOMEM; assert_se(pthread_mutex_init(&b->memfd_cache_mutex, NULL) == 0); @@ -631,8 +629,8 @@ int bus_start_running(sd_bus *bus) { } static int parse_address_key(const char **p, const char *key, char **value) { - size_t l, n = 0, allocated = 0; _cleanup_free_ char *r = NULL; + size_t l, n = 0; const char *a; assert(p); @@ -675,7 +673,7 @@ static int parse_address_key(const char **p, const char *key, char **value) { a++; } - if (!GREEDY_REALLOC(r, allocated, n + 2)) + if (!GREEDY_REALLOC(r, n + 2)) return -ENOMEM; r[n++] = c; @@ -847,7 +845,6 @@ static int parse_exec_address(sd_bus *b, const char **p, char **guid) { char *path = NULL; unsigned n_argv = 0, j; char **argv = NULL; - size_t allocated = 0; int r; assert(b); @@ -881,7 +878,7 @@ static int parse_exec_address(sd_bus *b, const char **p, char **guid) { (*p)++; if (ul >= n_argv) { - if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) { + if (!GREEDY_REALLOC0(argv, ul + 2)) { r = -ENOMEM; goto fail; } @@ -2048,7 +2045,7 @@ int bus_rqueue_make_room(sd_bus *bus) { if (bus->rqueue_size >= BUS_RQUEUE_MAX) return -ENOBUFS; - if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1)) + if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_size + 1)) return -ENOMEM; return 0; @@ -2164,7 +2161,7 @@ _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie) { if (bus->wqueue_size >= BUS_WQUEUE_MAX) return -ENOBUFS; - if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1)) + if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_size + 1)) return -ENOMEM; bus->wqueue[bus->wqueue_size++] = bus_message_ref_queued(m, bus); diff --git a/src/libsystemd/sd-device/device-enumerator.c b/src/libsystemd/sd-device/device-enumerator.c index a290dbcc9c..3ae80ab942 100644 --- a/src/libsystemd/sd-device/device-enumerator.c +++ b/src/libsystemd/sd-device/device-enumerator.c @@ -29,7 +29,7 @@ struct sd_device_enumerator { DeviceEnumerationType type; sd_device **devices; - size_t n_devices, n_allocated, current_device_index; + size_t n_devices, current_device_index; bool scan_uptodate; Set *match_subsystem; @@ -279,7 +279,7 @@ int device_enumerator_add_device(sd_device_enumerator *enumerator, sd_device *de assert_return(enumerator, -EINVAL); assert_return(device, -EINVAL); - if (!GREEDY_REALLOC(enumerator->devices, enumerator->n_allocated, enumerator->n_devices + 1)) + if (!GREEDY_REALLOC(enumerator->devices, enumerator->n_devices + 1)) return -ENOMEM; enumerator->devices[enumerator->n_devices++] = sd_device_ref(device); diff --git a/src/libsystemd/sd-device/device-private.c b/src/libsystemd/sd-device/device-private.c index e612dbe0a0..09ef87f84c 100644 --- a/src/libsystemd/sd-device/device-private.c +++ b/src/libsystemd/sd-device/device-private.c @@ -480,7 +480,6 @@ static int device_update_properties_bufs(sd_device *device) { const char *val, *prop; _cleanup_free_ char **buf_strv = NULL; _cleanup_free_ uint8_t *buf_nulstr = NULL; - size_t allocated_nulstr = 0; size_t nulstr_len = 0, num = 0, i = 0; assert(device); @@ -493,7 +492,7 @@ static int device_update_properties_bufs(sd_device *device) { len = strlen(prop) + 1 + strlen(val); - buf_nulstr = GREEDY_REALLOC0(buf_nulstr, allocated_nulstr, nulstr_len + len + 2); + buf_nulstr = GREEDY_REALLOC0(buf_nulstr, nulstr_len + len + 2); if (!buf_nulstr) return -ENOMEM; diff --git a/src/libsystemd/sd-event/sd-event.c b/src/libsystemd/sd-event/sd-event.c index 9fba09ba28..611af45293 100644 --- a/src/libsystemd/sd-event/sd-event.c +++ b/src/libsystemd/sd-event/sd-event.c @@ -144,7 +144,6 @@ struct sd_event { unsigned n_sources; struct epoll_event *event_queue; - size_t event_queue_allocated; LIST_HEAD(sd_event_source, sources); @@ -3858,38 +3857,45 @@ static int epoll_wait_usec( } static int process_epoll(sd_event *e, usec_t timeout, int64_t threshold, int64_t *ret_min_priority) { + size_t n_event_queue, m, n_event_max; int64_t min_priority = threshold; bool something_new = false; - size_t n_event_queue, m; int r; assert(e); assert(ret_min_priority); n_event_queue = MAX(e->n_sources, 1u); - if (!GREEDY_REALLOC(e->event_queue, e->event_queue_allocated, n_event_queue)) + if (!GREEDY_REALLOC(e->event_queue, n_event_queue)) return -ENOMEM; + n_event_max = MALLOC_ELEMENTSOF(e->event_queue); + /* If we still have inotify data buffered, then query the other fds, but don't wait on it */ if (e->inotify_data_buffered) timeout = 0; for (;;) { - r = epoll_wait_usec(e->epoll_fd, e->event_queue, e->event_queue_allocated, timeout); + r = epoll_wait_usec( + e->epoll_fd, + e->event_queue, + n_event_max, + timeout); if (r < 0) return r; m = (size_t) r; - if (m < e->event_queue_allocated) + if (m < n_event_max) break; - if (e->event_queue_allocated >= n_event_queue * 10) + if (n_event_max >= n_event_queue * 10) break; - if (!GREEDY_REALLOC(e->event_queue, e->event_queue_allocated, e->event_queue_allocated + n_event_queue)) + if (!GREEDY_REALLOC(e->event_queue, n_event_max + n_event_queue)) return -ENOMEM; + n_event_max = MALLOC_ELEMENTSOF(e->event_queue); timeout = 0; } diff --git a/src/libsystemd/sd-journal/catalog.c b/src/libsystemd/sd-journal/catalog.c index aea3241d18..ce8d47ccc3 100644 --- a/src/libsystemd/sd-journal/catalog.c +++ b/src/libsystemd/sd-journal/catalog.c @@ -249,7 +249,7 @@ static int catalog_entry_lang( int catalog_import_file(OrderedHashmap *h, const char *path) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *payload = NULL; - size_t payload_size = 0, payload_allocated = 0; + size_t payload_size = 0; unsigned n = 0; sd_id128_t id; _cleanup_free_ char *deflang = NULL, *lang = NULL; @@ -345,8 +345,7 @@ int catalog_import_file(OrderedHashmap *h, const char *path) { path, n); line_len = strlen(line); - if (!GREEDY_REALLOC(payload, payload_allocated, - payload_size + (empty_line ? 1 : 0) + line_len + 1 + 1)) + if (!GREEDY_REALLOC(payload, payload_size + (empty_line ? 1 : 0) + line_len + 1 + 1)) return log_oom(); if (empty_line) diff --git a/src/libsystemd/sd-journal/compress.c b/src/libsystemd/sd-journal/compress.c index f366a597b5..c788dd8caf 100644 --- a/src/libsystemd/sd-journal/compress.c +++ b/src/libsystemd/sd-journal/compress.c @@ -1,10 +1,11 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <inttypes.h> +#include <malloc.h> #include <stdlib.h> #include <sys/mman.h> -#include <sys/types.h> #include <sys/stat.h> +#include <sys/types.h> #include <unistd.h> #if HAVE_XZ @@ -157,8 +158,12 @@ int compress_blob_zstd( #endif } -int decompress_blob_xz(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { +int decompress_blob_xz( + const void *src, + uint64_t src_size, + void **dst, + size_t* dst_size, + size_t dst_max) { #if HAVE_XZ _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; @@ -168,16 +173,14 @@ int decompress_blob_xz(const void *src, uint64_t src_size, assert(src); assert(src_size > 0); assert(dst); - assert(dst_alloc_size); assert(dst_size); - assert(*dst_alloc_size == 0 || *dst); ret = lzma_stream_decoder(&s, UINT64_MAX, 0); if (ret != LZMA_OK) return -ENOMEM; space = MIN(src_size * 2, dst_max ?: SIZE_MAX); - if (!greedy_realloc(dst, dst_alloc_size, space, 1)) + if (!greedy_realloc(dst, space, 1)) return -ENOMEM; s.next_in = src; @@ -203,7 +206,7 @@ int decompress_blob_xz(const void *src, uint64_t src_size, used = space - s.avail_out; space = MIN(2 * space, dst_max ?: SIZE_MAX); - if (!greedy_realloc(dst, dst_alloc_size, space, 1)) + if (!greedy_realloc(dst, space, 1)) return -ENOMEM; s.avail_out = space - used; @@ -217,8 +220,12 @@ int decompress_blob_xz(const void *src, uint64_t src_size, #endif } -int decompress_blob_lz4(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { +int decompress_blob_lz4( + const void *src, + uint64_t src_size, + void **dst, + size_t* dst_size, + size_t dst_max) { #if HAVE_LZ4 char* out; @@ -227,9 +234,7 @@ int decompress_blob_lz4(const void *src, uint64_t src_size, assert(src); assert(src_size > 0); assert(dst); - assert(dst_alloc_size); assert(dst_size); - assert(*dst_alloc_size == 0 || *dst); if (src_size <= 8) return -EBADMSG; @@ -237,14 +242,9 @@ int decompress_blob_lz4(const void *src, uint64_t src_size, size = unaligned_read_le64(src); if (size < 0 || (unsigned) size != unaligned_read_le64(src)) return -EFBIG; - if ((size_t) size > *dst_alloc_size) { - out = realloc(*dst, size); - if (!out) - return -ENOMEM; - *dst = out; - *dst_alloc_size = size; - } else - out = *dst; + out = greedy_realloc(dst, size, 1); + if (!out) + return -ENOMEM; r = LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size); if (r < 0 || r != size) @@ -258,8 +258,11 @@ int decompress_blob_lz4(const void *src, uint64_t src_size, } int decompress_blob_zstd( - const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t *dst_size, size_t dst_max) { + const void *src, + uint64_t src_size, + void **dst, + size_t *dst_size, + size_t dst_max) { #if HAVE_ZSTD uint64_t size; @@ -267,9 +270,7 @@ int decompress_blob_zstd( assert(src); assert(src_size > 0); assert(dst); - assert(dst_alloc_size); assert(dst_size); - assert(*dst_alloc_size == 0 || *dst); size = ZSTD_getFrameContentSize(src, src_size); if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN)) @@ -280,7 +281,7 @@ int decompress_blob_zstd( if (size > SIZE_MAX) return -E2BIG; - if (!(greedy_realloc(dst, dst_alloc_size, MAX(ZSTD_DStreamOutSize(), size), 1))) + if (!(greedy_realloc(dst, MAX(ZSTD_DStreamOutSize(), size), 1))) return -ENOMEM; _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = ZSTD_createDCtx(); @@ -293,7 +294,7 @@ int decompress_blob_zstd( }; ZSTD_outBuffer output = { .dst = *dst, - .size = *dst_alloc_size, + .size = MALLOC_SIZEOF_SAFE(*dst), }; size_t k = ZSTD_decompressStream(dctx, &output, &input); @@ -312,57 +313,63 @@ int decompress_blob_zstd( int decompress_blob( int compression, - const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { + const void *src, + uint64_t src_size, + void **dst, + size_t* dst_size, + size_t dst_max) { if (compression == OBJECT_COMPRESSED_XZ) return decompress_blob_xz( src, src_size, - dst, dst_alloc_size, dst_size, dst_max); + dst, dst_size, dst_max); else if (compression == OBJECT_COMPRESSED_LZ4) return decompress_blob_lz4( src, src_size, - dst, dst_alloc_size, dst_size, dst_max); + dst, dst_size, dst_max); else if (compression == OBJECT_COMPRESSED_ZSTD) return decompress_blob_zstd( src, src_size, - dst, dst_alloc_size, dst_size, dst_max); + dst, dst_size, dst_max); else return -EPROTONOSUPPORT; } -int decompress_startswith_xz(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, - const void *prefix, size_t prefix_len, - uint8_t extra) { +int decompress_startswith_xz( + const void *src, + uint64_t src_size, + void **buffer, + const void *prefix, + size_t prefix_len, + uint8_t extra) { #if HAVE_XZ _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; + size_t allocated; lzma_ret ret; - /* Checks whether the decompressed blob starts with the - * mentioned prefix. The byte extra needs to follow the - * prefix */ + /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to + * follow the prefix */ assert(src); assert(src_size > 0); assert(buffer); - assert(buffer_size); assert(prefix); - assert(*buffer_size == 0 || *buffer); ret = lzma_stream_decoder(&s, UINT64_MAX, 0); if (ret != LZMA_OK) return -EBADMSG; - if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1))) + if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1))) return -ENOMEM; + allocated = MALLOC_SIZEOF_SAFE(*buffer); + s.next_in = src; s.avail_in = src_size; s.next_out = *buffer; - s.avail_out = *buffer_size; + s.avail_out = allocated; for (;;) { ret = lzma_code(&s, LZMA_FINISH); @@ -370,19 +377,20 @@ int decompress_startswith_xz(const void *src, uint64_t src_size, if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END)) return -EBADMSG; - if (*buffer_size - s.avail_out >= prefix_len + 1) + if (allocated - s.avail_out >= prefix_len + 1) return memcmp(*buffer, prefix, prefix_len) == 0 && ((const uint8_t*) *buffer)[prefix_len] == extra; if (ret == LZMA_STREAM_END) return 0; - s.avail_out += *buffer_size; + s.avail_out += allocated; - if (!(greedy_realloc(buffer, buffer_size, *buffer_size * 2, 1))) + if (!(greedy_realloc(buffer, allocated * 2, 1))) return -ENOMEM; - s.next_out = *(uint8_t**)buffer + *buffer_size - s.avail_out; + allocated = MALLOC_SIZEOF_SAFE(*buffer); + s.next_out = *(uint8_t**)buffer + allocated - s.avail_out; } #else @@ -390,36 +398,43 @@ int decompress_startswith_xz(const void *src, uint64_t src_size, #endif } -int decompress_startswith_lz4(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, - const void *prefix, size_t prefix_len, - uint8_t extra) { +int decompress_startswith_lz4( + const void *src, + uint64_t src_size, + void **buffer, + const void *prefix, + size_t prefix_len, + uint8_t extra) { + #if HAVE_LZ4 - /* Checks whether the decompressed blob starts with the - * mentioned prefix. The byte extra needs to follow the - * prefix */ + /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to + * follow the prefix */ + size_t allocated; int r; assert(src); assert(src_size > 0); assert(buffer); - assert(buffer_size); assert(prefix); - assert(*buffer_size == 0 || *buffer); if (src_size <= 8) return -EBADMSG; - if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1))) + if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1))) return -ENOMEM; - - r = LZ4_decompress_safe_partial((char*)src + 8, *buffer, src_size - 8, - prefix_len + 1, *buffer_size); - /* One lz4 < 1.8.3, we might get "failure" (r < 0), or "success" where - * just a part of the buffer is decompressed. But if we get a smaller - * amount of bytes than requested, we don't know whether there isn't enough - * data to fill the requested size or whether we just got a partial answer. + allocated = MALLOC_SIZEOF_SAFE(*buffer); + + r = LZ4_decompress_safe_partial( + (char*)src + 8, + *buffer, + src_size - 8, + prefix_len + 1, + allocated); + + /* One lz4 < 1.8.3, we might get "failure" (r < 0), or "success" where just a part of the buffer is + * decompressed. But if we get a smaller amount of bytes than requested, we don't know whether there + * isn't enough data to fill the requested size or whether we just got a partial answer. */ if (r < 0 || (size_t) r < prefix_len + 1) { size_t size; @@ -437,7 +452,7 @@ int decompress_startswith_lz4(const void *src, uint64_t src_size, /* Before version 1.8.3, lz4 always tries to decode full a "sequence", * so in pathological cases might need to decompress the full field. */ - r = decompress_blob_lz4(src, src_size, buffer, buffer_size, &size, 0); + r = decompress_blob_lz4(src, src_size, buffer, &size, 0); if (r < 0) return r; @@ -453,17 +468,17 @@ int decompress_startswith_lz4(const void *src, uint64_t src_size, } int decompress_startswith_zstd( - const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, - const void *prefix, size_t prefix_len, + const void *src, + uint64_t src_size, + void **buffer, + const void *prefix, + size_t prefix_len, uint8_t extra) { #if HAVE_ZSTD assert(src); assert(src_size > 0); assert(buffer); - assert(buffer_size); assert(prefix); - assert(*buffer_size == 0 || *buffer); uint64_t size = ZSTD_getFrameContentSize(src, src_size); if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN)) @@ -476,7 +491,7 @@ int decompress_startswith_zstd( if (!dctx) return -ENOMEM; - if (!(greedy_realloc(buffer, buffer_size, MAX(ZSTD_DStreamOutSize(), prefix_len + 1), 1))) + if (!(greedy_realloc(buffer, MAX(ZSTD_DStreamOutSize(), prefix_len + 1), 1))) return -ENOMEM; ZSTD_inBuffer input = { @@ -485,7 +500,7 @@ int decompress_startswith_zstd( }; ZSTD_outBuffer output = { .dst = *buffer, - .size = *buffer_size, + .size = MALLOC_SIZEOF_SAFE(*buffer), }; size_t k; @@ -505,28 +520,30 @@ int decompress_startswith_zstd( int decompress_startswith( int compression, - const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, - const void *prefix, size_t prefix_len, + const void *src, + uint64_t src_size, + void **buffer, + const void *prefix, + size_t prefix_len, uint8_t extra) { if (compression == OBJECT_COMPRESSED_XZ) return decompress_startswith_xz( src, src_size, - buffer, buffer_size, + buffer, prefix, prefix_len, extra); else if (compression == OBJECT_COMPRESSED_LZ4) return decompress_startswith_lz4( src, src_size, - buffer, buffer_size, + buffer, prefix, prefix_len, extra); else if (compression == OBJECT_COMPRESSED_ZSTD) return decompress_startswith_zstd( src, src_size, - buffer, buffer_size, + buffer, prefix, prefix_len, extra); else diff --git a/src/libsystemd/sd-journal/compress.h b/src/libsystemd/sd-journal/compress.h index db7f3999ed..a82049edd8 100644 --- a/src/libsystemd/sd-journal/compress.h +++ b/src/libsystemd/sd-journal/compress.h @@ -37,30 +37,30 @@ static inline int compress_blob(const void *src, uint64_t src_size, } int decompress_blob_xz(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + void **dst, size_t* dst_size, size_t dst_max); int decompress_blob_lz4(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + void **dst, size_t* dst_size, size_t dst_max); int decompress_blob_zstd(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + void **dst, size_t* dst_size, size_t dst_max); int decompress_blob(int compression, const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + void **dst, size_t* dst_size, size_t dst_max); int decompress_startswith_xz(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, + void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith_lz4(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, + void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith_zstd(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, + void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith(int compression, const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, + void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); diff --git a/src/libsystemd/sd-journal/journal-file.c b/src/libsystemd/sd-journal/journal-file.c index 3cf26f8e44..5f63633bf1 100644 --- a/src/libsystemd/sd-journal/journal-file.c +++ b/src/libsystemd/sd-journal/journal-file.c @@ -1495,7 +1495,7 @@ int journal_file_find_data_object_with_hash( l -= offsetof(Object, data.payload); r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK, - o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0); + o->data.payload, l, &f->compress_buffer, &rsize, 0); if (r < 0) return r; @@ -3919,8 +3919,11 @@ int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint6 #if HAVE_COMPRESSION size_t rsize = 0; - r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK, - o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0); + r = decompress_blob( + o->object.flags & OBJECT_COMPRESSION_MASK, + o->data.payload, l, + &from->compress_buffer, &rsize, + 0); if (r < 0) return r; diff --git a/src/libsystemd/sd-journal/journal-file.h b/src/libsystemd/sd-journal/journal-file.h index 931c874268..de3df7692d 100644 --- a/src/libsystemd/sd-journal/journal-file.h +++ b/src/libsystemd/sd-journal/journal-file.h @@ -108,7 +108,6 @@ typedef struct JournalFile { uint64_t compress_threshold_bytes; #if HAVE_COMPRESSION void *compress_buffer; - size_t compress_buffer_size; #endif #if HAVE_GCRYPT diff --git a/src/libsystemd/sd-journal/journal-internal.h b/src/libsystemd/sd-journal/journal-internal.h index c2d29aae78..7fc6896522 100644 --- a/src/libsystemd/sd-journal/journal-internal.h +++ b/src/libsystemd/sd-journal/journal-internal.h @@ -99,7 +99,6 @@ struct sd_journal { uint64_t fields_offset; uint64_t fields_hash_table_index; char *fields_buffer; - size_t fields_buffer_allocated; int flags; diff --git a/src/libsystemd/sd-journal/journal-vacuum.c b/src/libsystemd/sd-journal/journal-vacuum.c index 0f1c9eb8f7..7b57ba5ec3 100644 --- a/src/libsystemd/sd-journal/journal-vacuum.c +++ b/src/libsystemd/sd-journal/journal-vacuum.c @@ -127,7 +127,7 @@ int journal_directory_vacuum( bool verbose) { uint64_t sum = 0, freed = 0, n_active_files = 0; - size_t n_list = 0, n_allocated = 0, i; + size_t n_list = 0, i; _cleanup_closedir_ DIR *d = NULL; struct vacuum_info *list = NULL; usec_t retention_limit = 0; @@ -262,7 +262,7 @@ int journal_directory_vacuum( patch_realtime(dirfd(d), p, &st, &realtime); - if (!GREEDY_REALLOC(list, n_allocated, n_list + 1)) { + if (!GREEDY_REALLOC(list, n_list + 1)) { r = -ENOMEM; goto finish; } diff --git a/src/libsystemd/sd-journal/journal-verify.c b/src/libsystemd/sd-journal/journal-verify.c index 8c38396eac..6bc0796f05 100644 --- a/src/libsystemd/sd-journal/journal-verify.c +++ b/src/libsystemd/sd-journal/journal-verify.c @@ -153,12 +153,12 @@ static int journal_file_object_verify(JournalFile *f, uint64_t offset, Object *o compression = o->object.flags & OBJECT_COMPRESSION_MASK; if (compression) { _cleanup_free_ void *b = NULL; - size_t alloc = 0, b_size; + size_t b_size; r = decompress_blob(compression, o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload), - &b, &alloc, &b_size, 0); + &b, &b_size, 0); if (r < 0) { error_errno(offset, r, "%s decompression failed: %m", object_compressed_to_string(compression)); diff --git a/src/libsystemd/sd-journal/sd-journal.c b/src/libsystemd/sd-journal/sd-journal.c index c90b4c926e..fce0ae0f87 100644 --- a/src/libsystemd/sd-journal/sd-journal.c +++ b/src/libsystemd/sd-journal/sd-journal.c @@ -2321,7 +2321,7 @@ _public_ int sd_journal_get_data(sd_journal *j, const char *field, const void ** #if HAVE_COMPRESSION r = decompress_startswith(compression, o->data.payload, l, - &f->compress_buffer, &f->compress_buffer_size, + &f->compress_buffer, field, field_length, '='); if (r < 0) log_debug_errno(r, "Cannot decompress %s object of length %"PRIu64" at offset "OFSfmt": %m", @@ -2332,7 +2332,7 @@ _public_ int sd_journal_get_data(sd_journal *j, const char *field, const void ** r = decompress_blob(compression, o->data.payload, l, - &f->compress_buffer, &f->compress_buffer_size, &rsize, + &f->compress_buffer, &rsize, j->data_threshold); if (r < 0) return r; @@ -2389,9 +2389,11 @@ static int return_data(sd_journal *j, JournalFile *f, Object *o, const void **da size_t rsize; int r; - r = decompress_blob(compression, - o->data.payload, l, &f->compress_buffer, - &f->compress_buffer_size, &rsize, j->data_threshold); + r = decompress_blob( + compression, + o->data.payload, l, + &f->compress_buffer, &rsize, + j->data_threshold); if (r < 0) return r; @@ -3143,7 +3145,7 @@ _public_ int sd_journal_enumerate_fields(sd_journal *j, const char **field) { if (sz > j->data_threshold) sz = j->data_threshold; - if (!GREEDY_REALLOC(j->fields_buffer, j->fields_buffer_allocated, sz + 1)) + if (!GREEDY_REALLOC(j->fields_buffer, sz + 1)) return -ENOMEM; memcpy(j->fields_buffer, o->field.payload, sz); diff --git a/src/libsystemd/sd-journal/test-compress-benchmark.c b/src/libsystemd/sd-journal/test-compress-benchmark.c index 001976076e..eb3459e27e 100644 --- a/src/libsystemd/sd-journal/test-compress-benchmark.c +++ b/src/libsystemd/sd-journal/test-compress-benchmark.c @@ -15,7 +15,7 @@ typedef int (compress_t)(const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size); typedef int (decompress_t)(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + void **dst, size_t* dst_size, size_t dst_max); #if HAVE_COMPRESSION @@ -80,7 +80,6 @@ static void test_compress_decompress(const char* label, const char* type, _cleanup_free_ char *text, *buf; _cleanup_free_ void *buf2 = NULL; - size_t buf2_allocated = 0; size_t skipped = 0, compressed = 0, total = 0; text = make_buf(MAX_SIZE, type); @@ -116,9 +115,8 @@ static void test_compress_decompress(const char* label, const char* type, if (j >= size) log_error("%s \"compressed\" %zu -> %zu", label, size, j); - r = decompress(buf, j, &buf2, &buf2_allocated, &k, 0); + r = decompress(buf, j, &buf2, &k, 0); assert_se(r == 0); - assert_se(buf2_allocated >= k); assert_se(k == size); assert_se(memcmp(text, buf2, size) == 0); diff --git a/src/libsystemd/sd-journal/test-compress.c b/src/libsystemd/sd-journal/test-compress.c index ccd4605016..0d5069d477 100644 --- a/src/libsystemd/sd-journal/test-compress.c +++ b/src/libsystemd/sd-journal/test-compress.c @@ -34,10 +34,10 @@ typedef int (compress_blob_t)(const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size); typedef int (decompress_blob_t)(const void *src, uint64_t src_size, - void **dst, size_t *dst_alloc_size, + void **dst, size_t* dst_size, size_t dst_max); typedef int (decompress_sw_t)(const void *src, uint64_t src_size, - void **buffer, size_t *buffer_size, + void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); @@ -45,14 +45,16 @@ typedef int (compress_stream_t)(int fdf, int fdt, uint64_t max_bytes); typedef int (decompress_stream_t)(int fdf, int fdt, uint64_t max_size); #if HAVE_COMPRESSION -_unused_ static void test_compress_decompress(const char *compression, - compress_blob_t compress, - decompress_blob_t decompress, - const char *data, - size_t data_len, - bool may_fail) { +_unused_ static void test_compress_decompress( + const char *compression, + compress_blob_t compress, + decompress_blob_t decompress, + const char *data, + size_t data_len, + bool may_fail) { + char compressed[512]; - size_t csize, usize = 0; + size_t csize; _cleanup_free_ char *decompressed = NULL; int r; @@ -66,26 +68,26 @@ _unused_ static void test_compress_decompress(const char *compression, } else { assert_se(r == 0); r = decompress(compressed, csize, - (void **) &decompressed, &usize, &csize, 0); + (void **) &decompressed, &csize, 0); assert_se(r == 0); assert_se(decompressed); assert_se(memcmp(decompressed, data, data_len) == 0); } r = decompress("garbage", 7, - (void **) &decompressed, &usize, &csize, 0); + (void **) &decompressed, &csize, 0); assert_se(r < 0); /* make sure to have the minimal lz4 compressed size */ r = decompress("00000000\1g", 9, - (void **) &decompressed, &usize, &csize, 0); + (void **) &decompressed, &csize, 0); assert_se(r < 0); r = decompress("\100000000g", 9, - (void **) &decompressed, &usize, &csize, 0); + (void **) &decompressed, &csize, 0); assert_se(r < 0); - memzero(decompressed, usize); + explicit_bzero_safe(decompressed, MALLOC_SIZEOF_SAFE(decompressed)); } _unused_ static void test_decompress_startswith(const char *compression, @@ -97,7 +99,7 @@ _unused_ static void test_decompress_startswith(const char *compression, char *compressed; _cleanup_free_ char *compressed1 = NULL, *compressed2 = NULL, *decompressed = NULL; - size_t csize, usize = 0, len; + size_t csize, len; int r; log_info("/* testing decompress_startswith with %s on %.20s text */", @@ -122,17 +124,17 @@ _unused_ static void test_decompress_startswith(const char *compression, len = strlen(data); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, data, len, '\0'); + r = decompress_sw(compressed, csize, (void **) &decompressed, data, len, '\0'); assert_se(r > 0); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, data, len, 'w'); + r = decompress_sw(compressed, csize, (void **) &decompressed, data, len, 'w'); assert_se(r == 0); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, "barbarbar", 9, ' '); + r = decompress_sw(compressed, csize, (void **) &decompressed, "barbarbar", 9, ' '); assert_se(r == 0); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, data, len - 1, data[len-1]); + r = decompress_sw(compressed, csize, (void **) &decompressed, data, len - 1, data[len-1]); assert_se(r > 0); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, data, len - 1, 'w'); + r = decompress_sw(compressed, csize, (void **) &decompressed, data, len - 1, 'w'); assert_se(r == 0); - r = decompress_sw(compressed, csize, (void **) &decompressed, &usize, data, len, '\0'); + r = decompress_sw(compressed, csize, (void **) &decompressed, data, len, '\0'); assert_se(r > 0); } @@ -152,13 +154,12 @@ _unused_ static void test_decompress_startswith_short(const char *compression, assert_se(r == 0); for (i = 1; i < strlen(TEXT); i++) { - size_t alloc_size = i; _cleanup_free_ void *buf2 = NULL; assert_se(buf2 = malloc(i)); - assert_se(decompress_sw(buf, csize, &buf2, &alloc_size, TEXT, i, TEXT[i]) == 1); - assert_se(decompress_sw(buf, csize, &buf2, &alloc_size, TEXT, i, 'y') == 0); + assert_se(decompress_sw(buf, csize, &buf2, TEXT, i, TEXT[i]) == 1); + assert_se(decompress_sw(buf, csize, &buf2, TEXT, i, 'y') == 0); } } diff --git a/src/libsystemd/sd-netlink/netlink-internal.h b/src/libsystemd/sd-netlink/netlink-internal.h index fd7f07a6c1..49c7dd773d 100644 --- a/src/libsystemd/sd-netlink/netlink-internal.h +++ b/src/libsystemd/sd-netlink/netlink-internal.h @@ -71,14 +71,11 @@ struct sd_netlink { sd_netlink_message **rqueue; unsigned rqueue_size; - size_t rqueue_allocated; sd_netlink_message **rqueue_partial; unsigned rqueue_partial_size; - size_t rqueue_partial_allocated; struct nlmsghdr *rbuffer; - size_t rbuffer_allocated; bool processing:1; diff --git a/src/libsystemd/sd-netlink/netlink-message.c b/src/libsystemd/sd-netlink/netlink-message.c index d7bc1ce14d..22f8a4aa73 100644 --- a/src/libsystemd/sd-netlink/netlink-message.c +++ b/src/libsystemd/sd-netlink/netlink-message.c @@ -1064,7 +1064,7 @@ static int netlink_container_parse(sd_netlink_message *m, struct rtattr *rta, size_t rt_len) { _cleanup_free_ struct netlink_attribute *attributes = NULL; - size_t n_allocated = 0; + size_t n = 0; /* RTA_OK() macro compares with rta->rt_len, which is unsigned short, and * LGTM.com analysis does not like the type difference. Hence, here we @@ -1075,7 +1075,7 @@ static int netlink_container_parse(sd_netlink_message *m, type = RTA_TYPE(rta); - if (!GREEDY_REALLOC0(attributes, n_allocated, type + 1)) + if (!GREEDY_REALLOC0(attributes, type + 1)) return -ENOMEM; if (attributes[type].offset != 0) @@ -1084,10 +1084,13 @@ static int netlink_container_parse(sd_netlink_message *m, attributes[type].offset = (uint8_t *) rta - (uint8_t *) m->hdr; attributes[type].nested = RTA_FLAGS(rta) & NLA_F_NESTED; attributes[type].net_byteorder = RTA_FLAGS(rta) & NLA_F_NET_BYTEORDER; + + if (type + 1U > n) + n = type + 1U; } container->attributes = TAKE_PTR(attributes); - container->n_attributes = n_allocated; + container->n_attributes = n; return 0; } diff --git a/src/libsystemd/sd-netlink/netlink-socket.c b/src/libsystemd/sd-netlink/netlink-socket.c index 7af9a94e3e..273af6383e 100644 --- a/src/libsystemd/sd-netlink/netlink-socket.c +++ b/src/libsystemd/sd-netlink/netlink-socket.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include <malloc.h> #include <netinet/in.h> #include <stdbool.h> #include <unistd.h> @@ -297,16 +298,15 @@ static int socket_recv_message(int fd, struct iovec *iov, uint32_t *ret_mcast_gr */ int socket_read_message(sd_netlink *rtnl) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *first = NULL; + bool multi_part = false, done = false; + size_t len, allocated; struct iovec iov = {}; uint32_t group = 0; - bool multi_part = false, done = false; - size_t len; - int r; unsigned i = 0; + int r; assert(rtnl); assert(rtnl->rbuffer); - assert(rtnl->rbuffer_allocated >= sizeof(struct nlmsghdr)); /* read nothing, just get the pending message size */ r = socket_recv_message(rtnl->fd, &iov, NULL, true); @@ -316,12 +316,11 @@ int socket_read_message(sd_netlink *rtnl) { len = (size_t) r; /* make room for the pending message */ - if (!greedy_realloc((void **)&rtnl->rbuffer, - &rtnl->rbuffer_allocated, - len, sizeof(uint8_t))) + if (!greedy_realloc((void **)&rtnl->rbuffer, len, sizeof(uint8_t))) return -ENOMEM; - iov = IOVEC_MAKE(rtnl->rbuffer, rtnl->rbuffer_allocated); + allocated = MALLOC_SIZEOF_SAFE(rtnl->rbuffer); + iov = IOVEC_MAKE(rtnl->rbuffer, allocated); /* read the pending message */ r = socket_recv_message(rtnl->fd, &iov, &group, false); @@ -330,7 +329,7 @@ int socket_read_message(sd_netlink *rtnl) { else len = (size_t) r; - if (len > rtnl->rbuffer_allocated) + if (len > allocated) /* message did not fit in read buffer */ return -EIO; diff --git a/src/libsystemd/sd-netlink/sd-netlink.c b/src/libsystemd/sd-netlink/sd-netlink.c index a003c25719..25ba700ee2 100644 --- a/src/libsystemd/sd-netlink/sd-netlink.c +++ b/src/libsystemd/sd-netlink/sd-netlink.c @@ -63,8 +63,7 @@ static int sd_netlink_new(sd_netlink **ret) { /* We guarantee that the read buffer has at least space for * a message header */ - if (!greedy_realloc((void**)&rtnl->rbuffer, &rtnl->rbuffer_allocated, - sizeof(struct nlmsghdr), sizeof(uint8_t))) + if (!greedy_realloc((void**)&rtnl->rbuffer, sizeof(struct nlmsghdr), sizeof(uint8_t))) return -ENOMEM; *ret = TAKE_PTR(rtnl); @@ -295,7 +294,7 @@ int rtnl_rqueue_make_room(sd_netlink *rtnl) { "rtnl: exhausted the read queue size (%d)", RTNL_RQUEUE_MAX); - if (!GREEDY_REALLOC(rtnl->rqueue, rtnl->rqueue_allocated, rtnl->rqueue_size + 1)) + if (!GREEDY_REALLOC(rtnl->rqueue, rtnl->rqueue_size + 1)) return -ENOMEM; return 0; @@ -309,8 +308,7 @@ int rtnl_rqueue_partial_make_room(sd_netlink *rtnl) { "rtnl: exhausted the partial read queue size (%d)", RTNL_RQUEUE_MAX); - if (!GREEDY_REALLOC(rtnl->rqueue_partial, rtnl->rqueue_partial_allocated, - rtnl->rqueue_partial_size + 1)) + if (!GREEDY_REALLOC(rtnl->rqueue_partial, rtnl->rqueue_partial_size + 1)) return -ENOMEM; return 0; diff --git a/src/libsystemd/sd-network/sd-network.c b/src/libsystemd/sd-network/sd-network.c index 552ec381b6..7273a77156 100644 --- a/src/libsystemd/sd-network/sd-network.c +++ b/src/libsystemd/sd-network/sd-network.c @@ -340,7 +340,7 @@ static int network_link_get_ifindexes(int ifindex, const char *key, int **ret) { char path[STRLEN("/run/systemd/netif/links/") + DECIMAL_STR_MAX(ifindex) + 1]; _cleanup_free_ int *ifis = NULL; _cleanup_free_ char *s = NULL; - size_t allocated = 0, c = 0; + size_t c = 0; int r; assert_return(ifindex > 0, -EINVAL); @@ -362,7 +362,7 @@ static int network_link_get_ifindexes(int ifindex, const char *key, int **ret) { if (r == 0) break; - if (!GREEDY_REALLOC(ifis, allocated, c + 2)) + if (!GREEDY_REALLOC(ifis, c + 2)) return -ENOMEM; r = ifis[c++] = parse_ifindex(word); diff --git a/src/login/logind-dbus.c b/src/login/logind-dbus.c index 3eb0e8fd4e..61353c7f17 100644 --- a/src/login/logind-dbus.c +++ b/src/login/logind-dbus.c @@ -828,7 +828,7 @@ static int method_create_session(sd_bus_message *message, void *userdata, sd_bus */ if (c != SESSION_GREETER && vtnr > 0 && - vtnr < m->seat0->position_count && + vtnr < MALLOC_ELEMENTSOF(m->seat0->positions) && m->seat0->positions[vtnr] && m->seat0->positions[vtnr]->class != SESSION_GREETER) return sd_bus_error_set(error, BUS_ERROR_SESSION_BUSY, "Already occupied by a session"); diff --git a/src/login/logind-seat.c b/src/login/logind-seat.c index b70afea62e..2d54681745 100644 --- a/src/login/logind-seat.c +++ b/src/login/logind-seat.c @@ -267,13 +267,25 @@ int seat_set_active(Seat *s, Session *session) { return 0; } +static Session* seat_get_position(Seat *s, unsigned pos) { + assert(s); + + if (pos >= MALLOC_ELEMENTSOF(s->positions)) + return NULL; + + return s->positions[pos]; +} + int seat_switch_to(Seat *s, unsigned num) { + Session *session; + /* Public session positions skip 0 (there is only F1-F12). Maybe it * will get reassigned in the future, so return error for now. */ if (num == 0) return -EINVAL; - if (num >= s->position_count || !s->positions[num]) { + session = seat_get_position(s, num); + if (!session) { /* allow switching to unused VTs to trigger auto-activate */ if (seat_has_vts(s) && num < 64) return chvt(num); @@ -281,47 +293,57 @@ int seat_switch_to(Seat *s, unsigned num) { return -EINVAL; } - return session_activate(s->positions[num]); + return session_activate(session); } int seat_switch_to_next(Seat *s) { unsigned start, i; + Session *session; - if (s->position_count == 0) + if (MALLOC_ELEMENTSOF(s->positions) == 0) return -EINVAL; start = 1; if (s->active && s->active->position > 0) start = s->active->position; - for (i = start + 1; i < s->position_count; ++i) - if (s->positions[i]) - return session_activate(s->positions[i]); + for (i = start + 1; i < MALLOC_ELEMENTSOF(s->positions); ++i) { + session = seat_get_position(s, i); + if (session) + return session_activate(session); + } - for (i = 1; i < start; ++i) - if (s->positions[i]) - return session_activate(s->positions[i]); + for (i = 1; i < start; ++i) { + session = seat_get_position(s, i); + if (session) + return session_activate(session); + } return -EINVAL; } int seat_switch_to_previous(Seat *s) { unsigned start, i; + Session *session; - if (s->position_count == 0) + if (MALLOC_ELEMENTSOF(s->positions) == 0) return -EINVAL; start = 1; if (s->active && s->active->position > 0) start = s->active->position; - for (i = start - 1; i > 0; --i) - if (s->positions[i]) - return session_activate(s->positions[i]); + for (i = start - 1; i > 0; --i) { + session = seat_get_position(s, i); + if (session) + return session_activate(session); + } - for (i = s->position_count - 1; i > start; --i) - if (s->positions[i]) - return session_activate(s->positions[i]); + for (i = MALLOC_ELEMENTSOF(s->positions) - 1; i > start; --i) { + session = seat_get_position(s, i); + if (session) + return session_activate(session); + } return -EINVAL; } @@ -468,7 +490,7 @@ void seat_evict_position(Seat *s, Session *session) { if (pos == 0) return; - if (pos < s->position_count && s->positions[pos] == session) { + if (pos < MALLOC_ELEMENTSOF(s->positions) && s->positions[pos] == session) { s->positions[pos] = NULL; /* There might be another session claiming the same @@ -488,7 +510,7 @@ void seat_claim_position(Seat *s, Session *session, unsigned pos) { if (seat_has_vts(s)) pos = session->vtnr; - if (!GREEDY_REALLOC0(s->positions, s->position_count, pos + 1)) + if (!GREEDY_REALLOC0(s->positions, pos + 1)) return; seat_evict_position(s, session); @@ -504,7 +526,7 @@ static void seat_assign_position(Seat *s, Session *session) { if (session->position > 0) return; - for (pos = 1; pos < s->position_count; ++pos) + for (pos = 1; pos < MALLOC_ELEMENTSOF(s->positions); ++pos) if (!s->positions[pos]) break; diff --git a/src/login/logind-seat.h b/src/login/logind-seat.h index ddc45f4870..2d18e7595a 100644 --- a/src/login/logind-seat.h +++ b/src/login/logind-seat.h @@ -19,7 +19,6 @@ struct Seat { LIST_HEAD(Session, sessions); Session **positions; - size_t position_count; bool in_gc_queue:1; bool started:1; diff --git a/src/machine/machine.c b/src/machine/machine.c index 6215b29c27..c0ed24b645 100644 --- a/src/machine/machine.c +++ b/src/machine/machine.c @@ -292,9 +292,9 @@ int machine_load(Machine *m) { (void) deserialize_usec(monotonic, &m->timestamp.monotonic); if (netif) { - size_t allocated = 0, nr = 0; - const char *p; _cleanup_free_ int *ni = NULL; + size_t nr = 0; + const char *p; p = netif; for (;;) { @@ -314,14 +314,13 @@ int machine_load(Machine *m) { if (r < 0) continue; - if (!GREEDY_REALLOC(ni, allocated, nr + 1)) + if (!GREEDY_REALLOC(ni, nr + 1)) return log_oom(); ni[nr++] = r; } - free(m->netif); - m->netif = TAKE_PTR(ni); + free_and_replace(m->netif, ni); m->n_netif = nr; } diff --git a/src/machine/machinectl.c b/src/machine/machinectl.c index 15f7d39921..beab50e315 100644 --- a/src/machine/machinectl.c +++ b/src/machine/machinectl.c @@ -2261,10 +2261,10 @@ static int list_transfers(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_free_ TransferInfo *transfers = NULL; - size_t n_transfers = 0, n_allocated = 0; const char *type, *remote, *local; sd_bus *bus = userdata; uint32_t id, max_id = 0; + size_t n_transfers = 0; double progress; int r; @@ -2281,7 +2281,7 @@ static int list_transfers(int argc, char *argv[], void *userdata) { while ((r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL)) > 0) { size_t l; - if (!GREEDY_REALLOC(transfers, n_allocated, n_transfers + 1)) + if (!GREEDY_REALLOC(transfers, n_transfers + 1)) return log_oom(); transfers[n_transfers].id = id; diff --git a/src/mount/mount-tool.c b/src/mount/mount-tool.c index 8c36dec12a..2e69a99bc6 100644 --- a/src/mount/mount-tool.c +++ b/src/mount/mount-tool.c @@ -723,7 +723,7 @@ static int find_mount_points(const char *what, char ***list) { _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL; _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL; _cleanup_strv_free_ char **l = NULL; - size_t bufsize = 0, n = 0; + size_t n = 0; int r; assert(what); @@ -755,7 +755,7 @@ static int find_mount_points(const char *what, char ***list) { continue; /* one extra slot is needed for the terminating NULL */ - if (!GREEDY_REALLOC0(l, bufsize, n + 2)) + if (!GREEDY_REALLOC0(l, n + 2)) return log_oom(); l[n] = strdup(target); @@ -764,7 +764,7 @@ static int find_mount_points(const char *what, char ***list) { n++; } - if (!GREEDY_REALLOC0(l, bufsize, n + 1)) + if (!GREEDY_REALLOC0(l, n + 1)) return log_oom(); *list = TAKE_PTR(l); diff --git a/src/network/networkctl.c b/src/network/networkctl.c index f36d725d7d..b4e3bfc7ae 100644 --- a/src/network/networkctl.c +++ b/src/network/networkctl.c @@ -716,7 +716,7 @@ static int acquire_link_info(sd_bus *bus, sd_netlink *rtnl, char **patterns, Lin _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL; _cleanup_(link_info_array_freep) LinkInfo *links = NULL; _cleanup_close_ int fd = -1; - size_t allocated = 0, c = 0; + size_t c = 0; int r; assert(rtnl); @@ -742,7 +742,7 @@ static int acquire_link_info(sd_bus *bus, sd_netlink *rtnl, char **patterns, Lin } for (sd_netlink_message *i = reply; i; i = sd_netlink_message_next(i)) { - if (!GREEDY_REALLOC0(links, allocated, c + 2)) /* We keep one trailing one as marker */ + if (!GREEDY_REALLOC0(links, c + 2)) /* We keep one trailing one as marker */ return -ENOMEM; r = decode_link(i, links + c, patterns, matched_patterns); diff --git a/src/network/networkd-dhcp-server.c b/src/network/networkd-dhcp-server.c index 0a396a957f..36707b6e8f 100644 --- a/src/network/networkd-dhcp-server.c +++ b/src/network/networkd-dhcp-server.c @@ -101,8 +101,8 @@ static int link_push_uplink_to_dhcp_server( sd_dhcp_server *s) { _cleanup_free_ struct in_addr *addresses = NULL; - size_t n_addresses = 0, n_allocated = 0; bool use_dhcp_lease_data = true; + size_t n_addresses = 0; assert(link); @@ -131,7 +131,7 @@ static int link_push_uplink_to_dhcp_server( if (in4_addr_is_null(&ia) || in4_addr_is_localhost(&ia)) continue; - if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1)) + if (!GREEDY_REALLOC(addresses, n_addresses + 1)) return log_oom(); addresses[n_addresses++] = ia; @@ -156,7 +156,7 @@ static int link_push_uplink_to_dhcp_server( if (in4_addr_is_null(&ia.in) || in4_addr_is_localhost(&ia.in)) continue; - if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1)) + if (!GREEDY_REALLOC(addresses, n_addresses + 1)) return log_oom(); addresses[n_addresses++] = ia.in; @@ -188,7 +188,7 @@ static int link_push_uplink_to_dhcp_server( int n = sd_dhcp_lease_get_servers(link->dhcp_lease, what, &da); if (n > 0) { - if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + n)) + if (!GREEDY_REALLOC(addresses, n_addresses + n)) return log_oom(); for (int j = 0; j < n; j++) @@ -203,7 +203,11 @@ static int link_push_uplink_to_dhcp_server( return sd_dhcp_server_set_servers(s, what, addresses, n_addresses); } -static int dhcp4_server_parse_dns_server_string_and_warn(Link *l, const char *string, struct in_addr **addresses, size_t *n_allocated, size_t *n_addresses) { +static int dhcp4_server_parse_dns_server_string_and_warn( + const char *string, + struct in_addr **addresses, + size_t *n_addresses) { + for (;;) { _cleanup_free_ char *word = NULL, *server_name = NULL; union in_addr_union address; @@ -229,7 +233,7 @@ static int dhcp4_server_parse_dns_server_string_and_warn(Link *l, const char *st if (in4_addr_is_null(&address.in) || in4_addr_is_localhost(&address.in)) continue; - if (!GREEDY_REALLOC(*addresses, *n_allocated, *n_addresses + 1)) + if (!GREEDY_REALLOC(*addresses, *n_addresses + 1)) return log_oom(); (*addresses)[(*n_addresses)++] = address.in; @@ -240,8 +244,8 @@ static int dhcp4_server_parse_dns_server_string_and_warn(Link *l, const char *st static int dhcp4_server_set_dns_from_resolve_conf(Link *link) { _cleanup_free_ struct in_addr *addresses = NULL; - size_t n_addresses = 0, n_allocated = 0; _cleanup_fclose_ FILE *f = NULL; + size_t n_addresses = 0; int n = 0, r; f = fopen(PRIVATE_UPLINK_RESOLV_CONF, "re"); @@ -273,7 +277,7 @@ static int dhcp4_server_set_dns_from_resolve_conf(Link *link) { if (!a) continue; - r = dhcp4_server_parse_dns_server_string_and_warn(link, a, &addresses, &n_allocated, &n_addresses); + r = dhcp4_server_parse_dns_server_string_and_warn(a, &addresses, &n_addresses); if (r < 0) log_warning_errno(r, "Failed to parse DNS server address '%s', ignoring.", a); } diff --git a/src/network/networkd-radv.c b/src/network/networkd-radv.c index 52c9afcc5e..0eaa4c29c9 100644 --- a/src/network/networkd-radv.c +++ b/src/network/networkd-radv.c @@ -515,7 +515,7 @@ int config_parse_route_prefix_lifetime( static int network_get_ipv6_dns(Network *network, struct in6_addr **ret_addresses, size_t *ret_size) { _cleanup_free_ struct in6_addr *addresses = NULL; - size_t n_addresses = 0, n_allocated = 0; + size_t n_addresses = 0; assert(network); assert(ret_addresses); @@ -534,7 +534,7 @@ static int network_get_ipv6_dns(Network *network, struct in6_addr **ret_addresse in_addr_is_localhost(AF_INET6, addr)) continue; - if (!GREEDY_REALLOC(addresses, n_allocated, n_addresses + 1)) + if (!GREEDY_REALLOC(addresses, n_addresses + 1)) return -ENOMEM; addresses[n_addresses++] = addr->in6; diff --git a/src/network/test-network.c b/src/network/test-network.c index 09e7b99d23..d04a7e35e8 100644 --- a/src/network/test-network.c +++ b/src/network/test-network.c @@ -46,11 +46,11 @@ static void test_deserialize_in_addr(void) { } static void test_deserialize_dhcp_routes(void) { - size_t size, allocated; + size_t size; { _cleanup_free_ struct sd_dhcp_route *routes = NULL; - assert_se(deserialize_dhcp_routes(&routes, &size, &allocated, "") >= 0); + assert_se(deserialize_dhcp_routes(&routes, &size, "") >= 0); assert_se(size == 0); } @@ -59,7 +59,7 @@ static void test_deserialize_dhcp_routes(void) { _cleanup_free_ struct sd_dhcp_route *routes = NULL; const char *routes_string = "192.168.0.0/16,192.168.0.1 10.1.2.0/24,10.1.2.1 0.0.0.0/0,10.0.1.1"; - assert_se(deserialize_dhcp_routes(&routes, &size, &allocated, routes_string) >= 0); + assert_se(deserialize_dhcp_routes(&routes, &size, routes_string) >= 0); assert_se(size == 3); assert_se(routes[0].dst_addr.s_addr == inet_addr("192.168.0.0")); @@ -80,7 +80,7 @@ static void test_deserialize_dhcp_routes(void) { _cleanup_free_ struct sd_dhcp_route *routes = NULL; const char *routes_string = "192.168.0.0/16,192.168.0.1 10.1.2.0#24,10.1.2.1 0.0.0.0/0,10.0.1.1"; - assert_se(deserialize_dhcp_routes(&routes, &size, &allocated, routes_string) >= 0); + assert_se(deserialize_dhcp_routes(&routes, &size, routes_string) >= 0); assert_se(size == 2); assert_se(routes[0].dst_addr.s_addr == inet_addr("192.168.0.0")); @@ -97,7 +97,7 @@ static void test_deserialize_dhcp_routes(void) { _cleanup_free_ struct sd_dhcp_route *routes = NULL; const char *routes_string = "192.168.0.0/55,192.168.0.1 10.1.2.0#24,10.1.2.1 0.0.0.0/0,10.0.1.X"; - assert_se(deserialize_dhcp_routes(&routes, &size, &allocated, routes_string) >= 0); + assert_se(deserialize_dhcp_routes(&routes, &size, routes_string) >= 0); assert_se(size == 0); } } diff --git a/src/nspawn/nspawn-setuid.c b/src/nspawn/nspawn-setuid.c index c224fd0b2f..2639b70934 100644 --- a/src/nspawn/nspawn-setuid.c +++ b/src/nspawn/nspawn-setuid.c @@ -96,7 +96,6 @@ int change_uid_gid(const char *user, bool chown_stdio, char **ret_home) { _cleanup_fclose_ FILE *f = NULL; _cleanup_close_ int fd = -1; unsigned n_gids = 0; - size_t sz = 0; uid_t uid; gid_t gid; pid_t pid; @@ -219,7 +218,7 @@ int change_uid_gid(const char *user, bool chown_stdio, char **ret_home) { if (r == 0) break; - if (!GREEDY_REALLOC(gids, sz, n_gids+1)) + if (!GREEDY_REALLOC(gids, n_gids+1)) return log_oom(); r = parse_gid(word, &gids[n_gids++]); diff --git a/src/partition/repart.c b/src/partition/repart.c index 1ecd9ffea4..341cae33a6 100644 --- a/src/partition/repart.c +++ b/src/partition/repart.c @@ -189,7 +189,7 @@ struct Context { size_t n_partitions; FreeArea **free_areas; - size_t n_free_areas, n_allocated_free_areas; + size_t n_free_areas; uint64_t start, end, total; @@ -312,7 +312,6 @@ static void context_free_free_areas(Context *context) { context->free_areas = mfree(context->free_areas); context->n_free_areas = 0; - context->n_allocated_free_areas = 0; } static Context *context_free(Context *context) { @@ -343,7 +342,7 @@ static int context_add_free_area( assert(context); assert(!after || !after->padding_area); - if (!GREEDY_REALLOC(context->free_areas, context->n_allocated_free_areas, context->n_free_areas + 1)) + if (!GREEDY_REALLOC(context->free_areas, context->n_free_areas + 1)) return -ENOMEM; a = new(FreeArea, 1); diff --git a/src/portable/portabled-image-bus.c b/src/portable/portabled-image-bus.c index 595fe8a60a..23c6e2633a 100644 --- a/src/portable/portabled-image-bus.c +++ b/src/portable/portabled-image-bus.c @@ -1073,8 +1073,8 @@ not_found: int bus_image_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) { _cleanup_hashmap_free_ Hashmap *images = NULL; _cleanup_strv_free_ char **l = NULL; - size_t n_allocated = 0, n = 0; Manager *m = userdata; + size_t n = 0; Image *image; int r; @@ -1097,7 +1097,7 @@ int bus_image_node_enumerator(sd_bus *bus, const char *path, void *userdata, cha if (r < 0) return r; - if (!GREEDY_REALLOC(l, n_allocated, n+2)) { + if (!GREEDY_REALLOC(l, n+2)) { free(p); return -ENOMEM; } diff --git a/src/pstore/pstore.c b/src/pstore/pstore.c index 6ce38f10a3..81538d9cb3 100644 --- a/src/pstore/pstore.c +++ b/src/pstore/pstore.c @@ -101,7 +101,6 @@ typedef struct PStoreEntry { typedef struct PStoreList { PStoreEntry *entries; - size_t n_allocated; size_t n_entries; } PStoreList; @@ -208,7 +207,7 @@ static int write_dmesg(const char *dmesg, size_t size, const char *id) { static void process_dmesg_files(PStoreList *list) { /* Move files, reconstruct dmesg.txt */ _cleanup_free_ char *dmesg = NULL, *dmesg_id = NULL; - size_t dmesg_size = 0, dmesg_allocated = 0; + size_t dmesg_size = 0; bool dmesg_bad = false; PStoreEntry *pe; @@ -303,7 +302,7 @@ static void process_dmesg_files(PStoreList *list) { /* Reconstruction of dmesg is done as a useful courtesy: do not fail, but don't write garbled * output either. */ size_t needed = strlen(pe->dirent.d_name) + strlen(":\n") + pe->content_size + 1; - if (!GREEDY_REALLOC(dmesg, dmesg_allocated, dmesg_size + needed)) { + if (!GREEDY_REALLOC(dmesg, dmesg_size + needed)) { log_oom(); dmesg_bad = true; continue; @@ -348,7 +347,7 @@ static int list_files(PStoreList *list, const char *sourcepath) { continue; } - if (!GREEDY_REALLOC(list->entries, list->n_allocated, list->n_entries + 1)) + if (!GREEDY_REALLOC(list->entries, list->n_entries + 1)) return log_oom(); list->entries[list->n_entries++] = (PStoreEntry) { diff --git a/src/resolve/resolvectl.c b/src/resolve/resolvectl.c index 52bbae3293..e652c82ffc 100644 --- a/src/resolve/resolvectl.c +++ b/src/resolve/resolvectl.c @@ -1963,7 +1963,7 @@ static int status_all(sd_bus *bus, StatusMode mode) { return log_error_errno(r, "Failed to enumerate links: %m"); _cleanup_free_ InterfaceInfo *infos = NULL; - size_t n_allocated = 0, n_infos = 0; + size_t n_infos = 0; for (sd_netlink_message *i = reply; i; i = sd_netlink_message_next(i)) { const char *name; @@ -1988,7 +1988,7 @@ static int status_all(sd_bus *bus, StatusMode mode) { if (r < 0) return rtnl_log_parse_error(r); - if (!GREEDY_REALLOC(infos, n_allocated, n_infos + 1)) + if (!GREEDY_REALLOC(infos, n_infos + 1)) return log_oom(); infos[n_infos++] = (InterfaceInfo) { ifindex, name }; diff --git a/src/resolve/resolved-dns-packet.c b/src/resolve/resolved-dns-packet.c index c93b7c1dde..b37f57fe67 100644 --- a/src/resolve/resolved-dns-packet.c +++ b/src/resolve/resolved-dns-packet.c @@ -1445,8 +1445,8 @@ int dns_packet_read_name( _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder; size_t after_rindex = 0, jump_barrier; _cleanup_free_ char *name = NULL; - size_t n = 0, allocated = 0; bool first = true; + size_t n = 0; int r; assert(p); @@ -1475,7 +1475,7 @@ int dns_packet_read_name( if (r < 0) return r; - if (!GREEDY_REALLOC(name, allocated, n + !first + DNS_LABEL_ESCAPED_MAX)) + if (!GREEDY_REALLOC(name, n + !first + DNS_LABEL_ESCAPED_MAX)) return -ENOMEM; if (first) @@ -1511,7 +1511,7 @@ int dns_packet_read_name( return -EBADMSG; } - if (!GREEDY_REALLOC(name, allocated, n + 1)) + if (!GREEDY_REALLOC(name, n + 1)) return -ENOMEM; name[n] = 0; diff --git a/src/resolve/resolved-etc-hosts.c b/src/resolve/resolved-etc-hosts.c index 65b815c43c..9af3a27bb1 100644 --- a/src/resolve/resolved-etc-hosts.c +++ b/src/resolve/resolved-etc-hosts.c @@ -147,7 +147,7 @@ static int parse_line(EtcHosts *hosts, unsigned nr, const char *line) { bn->name = TAKE_PTR(name); } - if (!GREEDY_REALLOC(bn->addresses, bn->n_allocated, bn->n_addresses + 1)) + if (!GREEDY_REALLOC(bn->addresses, bn->n_addresses + 1)) return log_oom(); bn->addresses[bn->n_addresses++] = &item->address; diff --git a/src/resolve/resolved-etc-hosts.h b/src/resolve/resolved-etc-hosts.h index 459b310185..c85926a3dc 100644 --- a/src/resolve/resolved-etc-hosts.h +++ b/src/resolve/resolved-etc-hosts.h @@ -15,7 +15,7 @@ typedef struct EtcHostsItemByName { char *name; struct in_addr_data **addresses; - size_t n_addresses, n_allocated; + size_t n_addresses; } EtcHostsItemByName; int etc_hosts_parse(EtcHosts *hosts, FILE *f); diff --git a/src/resolve/test-resolved-etc-hosts.c b/src/resolve/test-resolved-etc-hosts.c index 045952e825..6706885ebd 100644 --- a/src/resolve/test-resolved-etc-hosts.c +++ b/src/resolve/test-resolved-etc-hosts.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <arpa/inet.h> +#include <malloc.h> #include <netinet/in.h> #include <sys/socket.h> @@ -77,19 +78,19 @@ static void test_parse_etc_hosts(void) { EtcHostsItemByName *bn; assert_se(bn = hashmap_get(hosts.by_name, "some.where")); assert_se(bn->n_addresses == 3); - assert_se(bn->n_allocated >= 3); + assert_se(MALLOC_ELEMENTSOF(bn->addresses) >= 3); assert_se(address_equal_4(bn->addresses[0], inet_addr("1.2.3.4"))); assert_se(address_equal_4(bn->addresses[1], inet_addr("1.2.3.5"))); assert_se(address_equal_6(bn->addresses[2], {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5})); assert_se(bn = hashmap_get(hosts.by_name, "dash")); assert_se(bn->n_addresses == 1); - assert_se(bn->n_allocated >= 1); + assert_se(MALLOC_ELEMENTSOF(bn->addresses) >= 1); assert_se(address_equal_4(bn->addresses[0], inet_addr("1.2.3.6"))); assert_se(bn = hashmap_get(hosts.by_name, "dash-dash.where-dash")); assert_se(bn->n_addresses == 1); - assert_se(bn->n_allocated >= 1); + assert_se(MALLOC_ELEMENTSOF(bn->addresses) >= 1); assert_se(address_equal_4(bn->addresses[0], inet_addr("1.2.3.6"))); /* See https://tools.ietf.org/html/rfc1035#section-2.3.1 */ @@ -98,7 +99,7 @@ static void test_parse_etc_hosts(void) { assert_se(bn = hashmap_get(hosts.by_name, "before.comment")); assert_se(bn->n_addresses == 4); - assert_se(bn->n_allocated >= 4); + assert_se(MALLOC_ELEMENTSOF(bn->addresses) >= 4); assert_se(address_equal_4(bn->addresses[0], inet_addr("1.2.3.9"))); assert_se(address_equal_4(bn->addresses[1], inet_addr("1.2.3.10"))); assert_se(address_equal_4(bn->addresses[2], inet_addr("1.2.3.11"))); @@ -118,7 +119,7 @@ static void test_parse_etc_hosts(void) { assert_se(bn = hashmap_get(hosts.by_name, "some.other")); assert_se(bn->n_addresses == 1); - assert_se(bn->n_allocated >= 1); + assert_se(MALLOC_ELEMENTSOF(bn->addresses) >= 1); assert_se(address_equal_6(bn->addresses[0], {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5})); assert_se( set_contains(hosts.no_address, "some.where")); diff --git a/src/shared/bitmap.c b/src/shared/bitmap.c index dcf67fbbd8..6cf08b898f 100644 --- a/src/shared/bitmap.c +++ b/src/shared/bitmap.c @@ -39,7 +39,7 @@ Bitmap* bitmap_copy(Bitmap *b) { if (!ret->bitmaps) return mfree(ret); - ret->n_bitmaps = ret->bitmaps_allocated = b->n_bitmaps; + ret->n_bitmaps = b->n_bitmaps; return ret; } @@ -81,7 +81,7 @@ int bitmap_set(Bitmap *b, unsigned n) { offset = BITMAP_NUM_TO_OFFSET(n); if (offset >= b->n_bitmaps) { - if (!GREEDY_REALLOC0(b->bitmaps, b->bitmaps_allocated, offset + 1)) + if (!GREEDY_REALLOC0(b->bitmaps, offset + 1)) return -ENOMEM; b->n_bitmaps = offset + 1; @@ -147,7 +147,6 @@ void bitmap_clear(Bitmap *b) { b->bitmaps = mfree(b->bitmaps); b->n_bitmaps = 0; - b->bitmaps_allocated = 0; } bool bitmap_iterate(const Bitmap *b, Iterator *i, unsigned *n) { diff --git a/src/shared/bitmap.h b/src/shared/bitmap.h index 5c7651c68d..e77e2e1f88 100644 --- a/src/shared/bitmap.h +++ b/src/shared/bitmap.h @@ -9,7 +9,6 @@ typedef struct Bitmap { uint64_t *bitmaps; size_t n_bitmaps; - size_t bitmaps_allocated; } Bitmap; Bitmap* bitmap_new(void); diff --git a/src/shared/bootspec.c b/src/shared/bootspec.c index 17c28c6e01..354eb6828d 100644 --- a/src/shared/bootspec.c +++ b/src/shared/bootspec.c @@ -254,7 +254,6 @@ static int boot_entries_find( size_t *n_entries) { _cleanup_strv_free_ char **files = NULL; - size_t n_allocated = *n_entries; char **f; int r; @@ -268,7 +267,7 @@ static int boot_entries_find( return log_error_errno(r, "Failed to list files in \"%s\": %m", dir); STRV_FOREACH(f, files) { - if (!GREEDY_REALLOC0(*entries, n_allocated, *n_entries + 1)) + if (!GREEDY_REALLOC0(*entries, *n_entries + 1)) return log_oom(); r = boot_entry_load(root, *f, *entries + *n_entries); @@ -463,7 +462,6 @@ static int boot_entries_find_unified( size_t *n_entries) { _cleanup_(closedirp) DIR *d = NULL; - size_t n_allocated = *n_entries; struct dirent *de; int r; @@ -491,7 +489,7 @@ static int boot_entries_find_unified( if (!endswith_no_case(de->d_name, ".efi")) continue; - if (!GREEDY_REALLOC0(*entries, n_allocated, *n_entries + 1)) + if (!GREEDY_REALLOC0(*entries, *n_entries + 1)) return log_oom(); fd = openat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK); @@ -749,7 +747,6 @@ int boot_entries_augment_from_loader( "auto-reboot-to-firmware-setup", "Reboot Into Firmware Interface", }; - size_t n_allocated; char **i; assert(config); @@ -757,8 +754,6 @@ int boot_entries_augment_from_loader( /* Let's add the entries discovered by the boot loader to the end of our list, unless they are * already included there. */ - n_allocated = config->n_entries; - STRV_FOREACH(i, found_by_loader) { _cleanup_free_ char *c = NULL, *t = NULL, *p = NULL; char **a, **b; @@ -785,7 +780,7 @@ int boot_entries_augment_from_loader( if (!p) return log_oom(); - if (!GREEDY_REALLOC0(config->entries, n_allocated, config->n_entries + 1)) + if (!GREEDY_REALLOC0(config->entries, config->n_entries + 1)) return log_oom(); config->entries[config->n_entries++] = (BootEntry) { diff --git a/src/shared/bpf-program.c b/src/shared/bpf-program.c index a8a34521fd..ec8437d583 100644 --- a/src/shared/bpf-program.c +++ b/src/shared/bpf-program.c @@ -133,7 +133,7 @@ int bpf_program_add_instructions(BPFProgram *p, const struct bpf_insn *instructi if (p->kernel_fd >= 0) /* don't allow modification after we uploaded things to the kernel */ return -EBUSY; - if (!GREEDY_REALLOC(p->instructions, p->allocated, p->n_instructions + count)) + if (!GREEDY_REALLOC(p->instructions, p->n_instructions + count)) return -ENOMEM; memcpy(p->instructions + p->n_instructions, instructions, sizeof(struct bpf_insn) * count); diff --git a/src/shared/bpf-program.h b/src/shared/bpf-program.h index 86fd338c93..edde86c119 100644 --- a/src/shared/bpf-program.h +++ b/src/shared/bpf-program.h @@ -17,7 +17,6 @@ struct BPFProgram { uint32_t prog_type; size_t n_instructions; - size_t allocated; struct bpf_insn *instructions; char *attached_path; diff --git a/src/shared/bus-message-util.c b/src/shared/bus-message-util.c index 14a4a4cfd6..53f63508eb 100644 --- a/src/shared/bus-message-util.c +++ b/src/shared/bus-message-util.c @@ -137,7 +137,7 @@ int bus_message_read_dns_servers( size_t *ret_n_dns) { struct in_addr_full **dns = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; int r; assert(message); @@ -160,7 +160,7 @@ int bus_message_read_dns_servers( if (r == 0) break; - if (!GREEDY_REALLOC(dns, allocated, n+1)) { + if (!GREEDY_REALLOC(dns, n+1)) { r = -ENOMEM; goto clear; } diff --git a/src/shared/bus-unit-procs.c b/src/shared/bus-unit-procs.c index b76125e551..6f4a71138c 100644 --- a/src/shared/bus-unit-procs.c +++ b/src/shared/bus-unit-procs.c @@ -255,7 +255,7 @@ static int dump_extra_processes( _cleanup_free_ pid_t *pids = NULL; _cleanup_hashmap_free_ Hashmap *names = NULL; struct CGroupInfo *cg; - size_t n_allocated = 0, n = 0, k; + size_t n = 0, k; int width, r; /* Prints the extra processes, i.e. those that are in cgroups we haven't displayed yet. We show them as @@ -275,7 +275,7 @@ static int dump_extra_processes( if (r < 0) return r; - if (!GREEDY_REALLOC(pids, n_allocated, n + hashmap_size(cg->pids))) + if (!GREEDY_REALLOC(pids, n + hashmap_size(cg->pids))) return -ENOMEM; HASHMAP_FOREACH_KEY(name, pidp, cg->pids) { diff --git a/src/shared/cgroup-show.c b/src/shared/cgroup-show.c index f7c24f8860..c7e63be508 100644 --- a/src/shared/cgroup-show.c +++ b/src/shared/cgroup-show.c @@ -82,12 +82,12 @@ static int show_cgroup_one_by_path( bool more, OutputFlags flags) { - char *fn; - _cleanup_fclose_ FILE *f = NULL; - size_t n = 0, n_allocated = 0; _cleanup_free_ pid_t *pids = NULL; + _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *p = NULL; + size_t n = 0; pid_t pid; + char *fn; int r; r = cg_mangle_path(path, &p); @@ -104,10 +104,9 @@ static int show_cgroup_one_by_path( if (!(flags & OUTPUT_KERNEL_THREADS) && is_kernel_thread(pid) > 0) continue; - if (!GREEDY_REALLOC(pids, n_allocated, n + 1)) + if (!GREEDY_REALLOC(pids, n + 1)) return -ENOMEM; - assert(n < n_allocated); pids[n++] = pid; } diff --git a/src/shared/cpu-set-util.c b/src/shared/cpu-set-util.c index 2c3b5bb034..e3e69635a6 100644 --- a/src/shared/cpu-set-util.c +++ b/src/shared/cpu-set-util.c @@ -22,14 +22,14 @@ char* cpu_set_to_string(const CPUSet *a) { _cleanup_free_ char *str = NULL; - size_t allocated = 0, len = 0; + size_t len = 0; int i, r; for (i = 0; (size_t) i < a->allocated * 8; i++) { if (!CPU_ISSET_S(i, a->allocated, a->set)) continue; - if (!GREEDY_REALLOC(str, allocated, len + 1 + DECIMAL_STR_MAX(int))) + if (!GREEDY_REALLOC(str, len + 1 + DECIMAL_STR_MAX(int))) return NULL; r = sprintf(str + len, len > 0 ? " %d" : "%d", i); @@ -43,8 +43,8 @@ char* cpu_set_to_string(const CPUSet *a) { char *cpu_set_to_range_string(const CPUSet *set) { unsigned range_start = 0, range_end; _cleanup_free_ char *str = NULL; - size_t allocated = 0, len = 0; bool in_range = false; + size_t len = 0; int r; for (unsigned i = 0; i < set->allocated * 8; i++) @@ -58,7 +58,7 @@ char *cpu_set_to_range_string(const CPUSet *set) { } else if (in_range) { in_range = false; - if (!GREEDY_REALLOC(str, allocated, len + 2 + 2 * DECIMAL_STR_MAX(unsigned))) + if (!GREEDY_REALLOC(str, len + 2 + 2 * DECIMAL_STR_MAX(unsigned))) return NULL; if (range_end > range_start) @@ -70,7 +70,7 @@ char *cpu_set_to_range_string(const CPUSet *set) { } if (in_range) { - if (!GREEDY_REALLOC(str, allocated, len + 2 + 2 * DECIMAL_STR_MAX(int))) + if (!GREEDY_REALLOC(str, len + 2 + 2 * DECIMAL_STR_MAX(int))) return NULL; if (range_end > range_start) diff --git a/src/shared/dissect-image.c b/src/shared/dissect-image.c index 3cf00adb6f..a8402c1dcd 100644 --- a/src/shared/dissect-image.c +++ b/src/shared/dissect-image.c @@ -1780,7 +1780,6 @@ typedef struct DecryptedPartition { struct DecryptedImage { DecryptedPartition *decrypted; size_t n_decrypted; - size_t n_allocated; }; #endif @@ -1876,7 +1875,7 @@ static int decrypt_partition( if (r < 0) return r; - if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1)) + if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1)) return -ENOMEM; r = sym_crypt_init(&cd, m->node); @@ -2028,7 +2027,7 @@ static int verity_partition( if (r < 0) return r; - if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1)) + if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1)) return -ENOMEM; /* If activating fails because the device already exists, check the metadata and reuse it if it matches. diff --git a/src/shared/dns-domain.c b/src/shared/dns-domain.c index 716c010076..216e1a0647 100644 --- a/src/shared/dns-domain.c +++ b/src/shared/dns-domain.c @@ -407,7 +407,7 @@ int dns_label_undo_idna(const char *encoded, size_t encoded_size, char *decoded, int dns_name_concat(const char *a, const char *b, DNSLabelFlags flags, char **_ret) { _cleanup_free_ char *ret = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; const char *p; bool first = true; int r; @@ -439,7 +439,7 @@ int dns_name_concat(const char *a, const char *b, DNSLabelFlags flags, char **_r } if (_ret) { - if (!GREEDY_REALLOC(ret, allocated, n + !first + DNS_LABEL_ESCAPED_MAX)) + if (!GREEDY_REALLOC(ret, n + !first + DNS_LABEL_ESCAPED_MAX)) return -ENOMEM; r = dns_label_escape(label, r, ret + n + !first, DNS_LABEL_ESCAPED_MAX); @@ -471,12 +471,12 @@ finish: if (_ret) { if (n == 0) { /* Nothing appended? If so, generate at least a single dot, to indicate the DNS root domain */ - if (!GREEDY_REALLOC(ret, allocated, 2)) + if (!GREEDY_REALLOC(ret, 2)) return -ENOMEM; ret[n++] = '.'; } else { - if (!GREEDY_REALLOC(ret, allocated, n + 1)) + if (!GREEDY_REALLOC(ret, n + 1)) return -ENOMEM; } diff --git a/src/shared/efi-loader.c b/src/shared/efi-loader.c index ee32b0b097..c250bc2d57 100644 --- a/src/shared/efi-loader.c +++ b/src/shared/efi-loader.c @@ -493,7 +493,6 @@ int efi_get_boot_options(uint16_t **options) { _cleanup_closedir_ DIR *dir = NULL; _cleanup_free_ uint16_t *list = NULL; struct dirent *de; - size_t alloc = 0; int count = 0; assert(options); @@ -521,7 +520,7 @@ int efi_get_boot_options(uint16_t **options) { if (id < 0) continue; - if (!GREEDY_REALLOC(list, alloc, count + 1)) + if (!GREEDY_REALLOC(list, count + 1)) return -ENOMEM; list[count++] = id; diff --git a/src/shared/format-table.c b/src/shared/format-table.c index 76cf3343db..8b1240d63a 100644 --- a/src/shared/format-table.c +++ b/src/shared/format-table.c @@ -136,7 +136,6 @@ struct Table { size_t cell_height_max; /* Maximum number of lines per cell. (If there are more, ellipsis is shown. If SIZE_MAX then no limit is set, the default. == 0 is not allowed.) */ TableData **data; - size_t n_allocated; size_t *display_map; /* List of columns to show (by their index). It's fine if columns are listed multiple times or not at all */ size_t n_display_map; @@ -453,7 +452,7 @@ int table_add_cell_full( return -ENOMEM; } - if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns))) + if (!GREEDY_REALLOC(t->data, MAX(t->n_cells + 1, t->n_columns))) return -ENOMEM; if (ret_cell) @@ -510,7 +509,7 @@ int table_dup_cell(Table *t, TableCell *cell) { if (i >= t->n_cells) return -ENXIO; - if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns))) + if (!GREEDY_REALLOC(t->data, MAX(t->n_cells + 1, t->n_columns))) return -ENOMEM; t->data[t->n_cells++] = table_data_ref(t->data[i]); @@ -1094,19 +1093,18 @@ static int table_set_display_all(Table *t) { } int table_set_display_internal(Table *t, size_t first_column, ...) { - size_t allocated, column; + size_t column; va_list ap; assert(t); - allocated = t->n_display_map; column = first_column; va_start(ap, first_column); for (;;) { assert(column < t->n_columns); - if (!GREEDY_REALLOC(t->display_map, allocated, MAX(t->n_columns, t->n_display_map+1))) { + if (!GREEDY_REALLOC(t->display_map, MAX(t->n_columns, t->n_display_map+1))) { va_end(ap); return -ENOMEM; } @@ -1124,19 +1122,18 @@ int table_set_display_internal(Table *t, size_t first_column, ...) { } int table_set_sort_internal(Table *t, size_t first_column, ...) { - size_t allocated, column; + size_t column; va_list ap; assert(t); - allocated = t->n_sort_map; column = first_column; va_start(ap, first_column); for (;;) { assert(column < t->n_columns); - if (!GREEDY_REALLOC(t->sort_map, allocated, MAX(t->n_columns, t->n_sort_map+1))) { + if (!GREEDY_REALLOC(t->sort_map, MAX(t->n_columns, t->n_sort_map+1))) { va_end(ap); return -ENOMEM; } diff --git a/src/shared/install.c b/src/shared/install.c index 119980663f..3723ec031c 100644 --- a/src/shared/install.c +++ b/src/shared/install.c @@ -2166,10 +2166,10 @@ int unit_file_unmask( _cleanup_(lookup_paths_free) LookupPaths paths = {}; _cleanup_set_free_free_ Set *remove_symlinks_to = NULL; _cleanup_strv_free_ char **todo = NULL; - size_t n_todo = 0, n_allocated = 0; const char *config_path; - char **i; + size_t n_todo = 0; bool dry_run; + char **i; int r, q; assert(scope >= 0); @@ -2203,7 +2203,7 @@ int unit_file_unmask( if (r == 0) continue; - if (!GREEDY_REALLOC0(todo, n_allocated, n_todo + 2)) + if (!GREEDY_REALLOC0(todo, n_todo + 2)) return -ENOMEM; todo[n_todo] = strdup(*i); @@ -2259,8 +2259,8 @@ int unit_file_link( _cleanup_(lookup_paths_free) LookupPaths paths = {}; _cleanup_strv_free_ char **todo = NULL; - size_t n_todo = 0, n_allocated = 0; const char *config_path; + size_t n_todo = 0; char **i; int r, q; @@ -2303,7 +2303,7 @@ int unit_file_link( if (q > 0) continue; - if (!GREEDY_REALLOC0(todo, n_allocated, n_todo + 2)) + if (!GREEDY_REALLOC0(todo, n_todo + 2)) return -ENOMEM; todo[n_todo] = strdup(*i); @@ -2360,7 +2360,7 @@ int unit_file_revert( _cleanup_set_free_free_ Set *remove_symlinks_to = NULL; _cleanup_(lookup_paths_free) LookupPaths paths = {}; _cleanup_strv_free_ char **todo = NULL; - size_t n_todo = 0, n_allocated = 0; + size_t n_todo = 0; char **i; int r, q; @@ -2421,7 +2421,7 @@ int unit_file_revert( if (r < 0) return r; if (r > 0) { - if (!GREEDY_REALLOC0(todo, n_allocated, n_todo + 2)) + if (!GREEDY_REALLOC0(todo, n_todo + 2)) return -ENOMEM; todo[n_todo++] = TAKE_PTR(dropin); @@ -2450,7 +2450,7 @@ int unit_file_revert( if (r < 0) return r; if (r > 0) { - if (!GREEDY_REALLOC0(todo, n_allocated, n_todo + 2)) + if (!GREEDY_REALLOC0(todo, n_todo + 2)) return -ENOMEM; todo[n_todo++] = TAKE_PTR(path); @@ -2946,7 +2946,6 @@ static int presets_find_config(UnitFileScope scope, const char *root_dir, char * static int read_presets(UnitFileScope scope, const char *root_dir, UnitFilePresets *presets) { _cleanup_(unit_file_presets_freep) UnitFilePresets ps = {}; - size_t n_allocated = 0; _cleanup_strv_free_ char **files = NULL; char **p; int r; @@ -3025,7 +3024,7 @@ static int read_presets(UnitFileScope scope, const char *root_dir, UnitFilePrese } if (rule.action) { - if (!GREEDY_REALLOC(ps.rules, n_allocated, ps.n_rules + 1)) + if (!GREEDY_REALLOC(ps.rules, ps.n_rules + 1)) return -ENOMEM; ps.rules[ps.n_rules++] = rule; diff --git a/src/shared/journal-importer.c b/src/shared/journal-importer.c index b2785f0552..0d82acc25c 100644 --- a/src/shared/journal-importer.c +++ b/src/shared/journal-importer.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> +#include <malloc.h> #include <unistd.h> #include "alloc-util.h" @@ -37,7 +38,7 @@ void journal_importer_cleanup(JournalImporter *imp) { static char* realloc_buffer(JournalImporter *imp, size_t size) { char *b, *old = imp->buf; - b = GREEDY_REALLOC(imp->buf, imp->size, size); + b = GREEDY_REALLOC(imp->buf, size); if (!b) return NULL; @@ -53,8 +54,7 @@ static int get_line(JournalImporter *imp, char **line, size_t *size) { assert(imp); assert(imp->state == IMPORTER_STATE_LINE); assert(imp->offset <= imp->filled); - assert(imp->filled <= imp->size); - assert(!imp->buf || imp->size > 0); + assert(imp->filled <= MALLOC_SIZEOF_SAFE(imp->buf)); assert(imp->fd >= 0); for (;;) { @@ -80,22 +80,22 @@ static int get_line(JournalImporter *imp, char **line, size_t *size) { /* We know that imp->filled is at most DATA_SIZE_MAX, so if we reallocate it, we'll increase the size at least a bit. */ assert_cc(DATA_SIZE_MAX < ENTRY_SIZE_MAX); - if (imp->size - imp->filled < LINE_CHUNK && + if (MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled < LINE_CHUNK && !realloc_buffer(imp, MIN(imp->filled + LINE_CHUNK, ENTRY_SIZE_MAX))) return log_oom(); assert(imp->buf); - assert(imp->size - imp->filled >= LINE_CHUNK || - imp->size == ENTRY_SIZE_MAX); + assert(MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled >= LINE_CHUNK || + MALLOC_SIZEOF_SAFE(imp->buf) >= ENTRY_SIZE_MAX); n = read(imp->fd, imp->buf + imp->filled, - imp->size - imp->filled); + MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled); if (n < 0) { if (errno != EAGAIN) log_error_errno(errno, "read(%d, ..., %zu): %m", imp->fd, - imp->size - imp->filled); + MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled); return -errno; } else if (n == 0) return 0; @@ -116,9 +116,7 @@ static int fill_fixed_size(JournalImporter *imp, void **data, size_t size) { assert(IN_SET(imp->state, IMPORTER_STATE_DATA_START, IMPORTER_STATE_DATA, IMPORTER_STATE_DATA_FINISH)); assert(size <= DATA_SIZE_MAX); assert(imp->offset <= imp->filled); - assert(imp->filled <= imp->size); - assert(imp->buf || imp->size == 0); - assert(!imp->buf || imp->size > 0); + assert(imp->filled <= MALLOC_SIZEOF_SAFE(imp->buf)); assert(imp->fd >= 0); assert(data); @@ -133,11 +131,11 @@ static int fill_fixed_size(JournalImporter *imp, void **data, size_t size) { return log_oom(); n = read(imp->fd, imp->buf + imp->filled, - imp->size - imp->filled); + MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled); if (n < 0) { if (errno != EAGAIN) log_error_errno(errno, "read(%d, ..., %zu): %m", imp->fd, - imp->size - imp->filled); + MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled); return -errno; } else if (n == 0) return 0; @@ -431,7 +429,7 @@ int journal_importer_push_data(JournalImporter *imp, const char *data, size_t si return log_error_errno(SYNTHETIC_ERRNO(ENOMEM), "Failed to store received data of size %zu " "(in addition to existing %zu bytes with %zu filled): %s", - size, imp->size, imp->filled, + size, MALLOC_SIZEOF_SAFE(imp->buf), imp->filled, strerror_safe(ENOMEM)); memcpy(imp->buf + imp->filled, data, size); @@ -452,18 +450,21 @@ void journal_importer_drop_iovw(JournalImporter *imp) { if (remain == 0) /* no brainer */ imp->offset = imp->scanned = imp->filled = 0; - else if (imp->offset > imp->size - imp->filled && + else if (imp->offset > MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled && imp->offset > remain) { memcpy(imp->buf, imp->buf + imp->offset, remain); imp->offset = imp->scanned = 0; imp->filled = remain; } - target = imp->size; + target = MALLOC_SIZEOF_SAFE(imp->buf); while (target > 16 * LINE_CHUNK && imp->filled < target / 2) target /= 2; - if (target < imp->size) { + if (target < MALLOC_SIZEOF_SAFE(imp->buf)) { char *tmp; + size_t old_size; + + old_size = MALLOC_SIZEOF_SAFE(imp->buf); tmp = realloc(imp->buf, target); if (!tmp) @@ -471,9 +472,8 @@ void journal_importer_drop_iovw(JournalImporter *imp) { target); else { log_debug("Reallocated buffer from %zu to %zu bytes", - imp->size, target); + old_size, target); imp->buf = tmp; - imp->size = target; } } } diff --git a/src/shared/journal-importer.h b/src/shared/journal-importer.h index e0073fcea8..7eb2169217 100644 --- a/src/shared/journal-importer.h +++ b/src/shared/journal-importer.h @@ -31,7 +31,6 @@ typedef struct JournalImporter { char *name; char *buf; - size_t size; /* total size of the buffer */ size_t offset; /* offset to the beginning of live data in the buffer */ size_t scanned; /* number of bytes since the beginning of data without a newline */ size_t filled; /* total number of bytes in the buffer */ diff --git a/src/shared/json.c b/src/shared/json.c index ef1e937645..ea4b46ff26 100644 --- a/src/shared/json.c +++ b/src/shared/json.c @@ -2399,7 +2399,7 @@ static int unhex_ucs2(const char *c, uint16_t *ret) { static int json_parse_string(const char **p, char **ret) { _cleanup_free_ char *s = NULL; - size_t n = 0, allocated = 0; + size_t n = 0; const char *c; assert(p); @@ -2471,7 +2471,7 @@ static int json_parse_string(const char **p, char **ret) { c += 5; - if (!GREEDY_REALLOC(s, allocated, n + 5)) + if (!GREEDY_REALLOC(s, n + 5)) return -ENOMEM; if (!utf16_is_surrogate(x)) @@ -2500,7 +2500,7 @@ static int json_parse_string(const char **p, char **ret) { } else return -EINVAL; - if (!GREEDY_REALLOC(s, allocated, n + 2)) + if (!GREEDY_REALLOC(s, n + 2)) return -ENOMEM; s[n++] = ch; @@ -2512,7 +2512,7 @@ static int json_parse_string(const char **p, char **ret) { if (len < 0) return len; - if (!GREEDY_REALLOC(s, allocated, n + len + 1)) + if (!GREEDY_REALLOC(s, n + len + 1)) return -ENOMEM; memcpy(s + n, c, len); @@ -2825,7 +2825,7 @@ typedef enum JsonExpect { typedef struct JsonStack { JsonExpect expect; JsonVariant **elements; - size_t n_elements, n_elements_allocated; + size_t n_elements; unsigned line_before; unsigned column_before; size_t n_suppress; /* When building: if > 0, suppress this many subsequent elements. If == SIZE_MAX, suppress all subsequent elements */ @@ -2847,7 +2847,7 @@ static int json_parse_internal( unsigned *column, bool continue_end) { - size_t n_stack = 1, n_stack_allocated = 0, i; + size_t n_stack = 1, i; unsigned line_buffer = 0, column_buffer = 0; void *tokenizer_state = NULL; JsonStack *stack = NULL; @@ -2859,7 +2859,7 @@ static int json_parse_internal( p = *input; - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack)) + if (!GREEDY_REALLOC(stack, n_stack)) return -ENOMEM; stack[0] = (JsonStack) { @@ -2933,7 +2933,7 @@ static int json_parse_internal( goto finish; } - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) { + if (!GREEDY_REALLOC(stack, n_stack+1)) { r = -ENOMEM; goto finish; } @@ -2984,7 +2984,7 @@ static int json_parse_internal( goto finish; } - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) { + if (!GREEDY_REALLOC(stack, n_stack+1)) { r = -ENOMEM; goto finish; } @@ -3168,7 +3168,7 @@ static int json_parse_internal( (void) json_variant_set_source(&add, source, line_token, column_token); - if (!GREEDY_REALLOC(current->elements, current->n_elements_allocated, current->n_elements + 1)) { + if (!GREEDY_REALLOC(current->elements, current->n_elements + 1)) { r = -ENOMEM; goto finish; } @@ -3229,12 +3229,12 @@ int json_parse_file_at(FILE *f, int dir_fd, const char *path, JsonParseFlags fla int json_buildv(JsonVariant **ret, va_list ap) { JsonStack *stack = NULL; - size_t n_stack = 1, n_stack_allocated = 0, i; + size_t n_stack = 1, i; int r; assert_return(ret, -EINVAL); - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack)) + if (!GREEDY_REALLOC(stack, n_stack)) return -ENOMEM; stack[0] = (JsonStack) { @@ -3517,7 +3517,7 @@ int json_buildv(JsonVariant **ret, va_list ap) { goto finish; } - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) { + if (!GREEDY_REALLOC(stack, n_stack+1)) { r = -ENOMEM; goto finish; } @@ -3714,7 +3714,7 @@ int json_buildv(JsonVariant **ret, va_list ap) { goto finish; } - if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) { + if (!GREEDY_REALLOC(stack, n_stack+1)) { r = -ENOMEM; goto finish; } @@ -3810,7 +3810,7 @@ int json_buildv(JsonVariant **ret, va_list ap) { /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */ if (add && current->n_suppress == 0) { - if (!GREEDY_REALLOC(current->elements, current->n_elements_allocated, current->n_elements + 1)) { + if (!GREEDY_REALLOC(current->elements, current->n_elements + 1)) { r = -ENOMEM; goto finish; } diff --git a/src/shared/local-addresses.c b/src/shared/local-addresses.c index 9dec7a7e1a..66e452adad 100644 --- a/src/shared/local-addresses.c +++ b/src/shared/local-addresses.c @@ -67,7 +67,7 @@ int local_addresses( _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL; _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL; _cleanup_free_ struct local_address *list = NULL; - size_t n_list = 0, n_allocated = 0; + size_t n_list = 0; sd_netlink_message *m; int r; @@ -121,7 +121,7 @@ int local_addresses( if (flags & IFA_F_DEPRECATED) continue; - if (!GREEDY_REALLOC0(list, n_allocated, n_list+1)) + if (!GREEDY_REALLOC0(list, n_list+1)) return -ENOMEM; a = list + n_list; @@ -175,7 +175,6 @@ int local_addresses( static int add_local_gateway( struct local_address **list, size_t *n_list, - size_t *n_allocated, int af, int ifindex, uint32_t metric, @@ -183,13 +182,12 @@ static int add_local_gateway( assert(list); assert(n_list); - assert(n_allocated); assert(via); if (af != AF_UNSPEC && af != via->family) return 0; - if (!GREEDY_REALLOC(*list, *n_allocated, *n_list + 1)) + if (!GREEDY_REALLOC(*list, *n_list + 1)) return -ENOMEM; (*list)[(*n_list)++] = (struct local_address) { @@ -211,7 +209,7 @@ int local_gateways( _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL; _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL; _cleanup_free_ struct local_address *list = NULL; - size_t n_list = 0, n_allocated = 0; + size_t n_list = 0; int r; if (context) @@ -299,7 +297,7 @@ int local_gateways( if (r >= 0) { via.family = family; via.address = gateway; - r = add_local_gateway(&list, &n_list, &n_allocated, af, ifi, metric, &via); + r = add_local_gateway(&list, &n_list, af, ifi, metric, &via); if (r < 0) return r; @@ -313,7 +311,7 @@ int local_gateways( if (r < 0 && r != -ENODATA) return r; if (r >= 0) { - r = add_local_gateway(&list, &n_list, &n_allocated, af, ifi, metric, &via); + r = add_local_gateway(&list, &n_list, af, ifi, metric, &via); if (r < 0) return r; @@ -335,7 +333,7 @@ int local_gateways( if (ifindex > 0 && mr->ifindex != ifindex) continue; - r = add_local_gateway(&list, &n_list, &n_allocated, af, ifi, metric, &mr->gateway); + r = add_local_gateway(&list, &n_list, af, ifi, metric, &mr->gateway); if (r < 0) return r; } @@ -358,7 +356,7 @@ int local_outbounds( struct local_address **ret) { _cleanup_free_ struct local_address *list = NULL, *gateways = NULL; - size_t n_list = 0, n_allocated = 0; + size_t n_list = 0; int r, n_gateways; /* Determines our default outbound addresses, i.e. the "primary" local addresses we use to talk to IP @@ -457,7 +455,7 @@ int local_outbounds( if (in4_addr_is_null(&sa.in.sin_addr)) /* Auto-binding didn't work. :-( */ continue; - if (!GREEDY_REALLOC(list, n_allocated, n_list+1)) + if (!GREEDY_REALLOC(list, n_list+1)) return -ENOMEM; list[n_list++] = (struct local_address) { @@ -472,7 +470,7 @@ int local_outbounds( if (in6_addr_is_null(&sa.in6.sin6_addr)) continue; - if (!GREEDY_REALLOC(list, n_allocated, n_list+1)) + if (!GREEDY_REALLOC(list, n_list+1)) return -ENOMEM; list[n_list++] = (struct local_address) { diff --git a/src/shared/sleep-config.c b/src/shared/sleep-config.c index 53280cf40a..6bb5d80a95 100644 --- a/src/shared/sleep-config.c +++ b/src/shared/sleep-config.c @@ -512,7 +512,6 @@ int read_fiemap(int fd, struct fiemap **ret) { uint32_t result_extents = 0; uint64_t fiemap_start = 0, fiemap_length; const size_t n_extra = DIV_ROUND_UP(sizeof(struct fiemap), sizeof(struct fiemap_extent)); - size_t fiemap_allocated = n_extra, result_fiemap_allocated = n_extra; if (fstat(fd, &statinfo) < 0) return log_debug_errno(errno, "Cannot determine file size: %m"); @@ -551,8 +550,7 @@ int read_fiemap(int fd, struct fiemap **ret) { /* Resize fiemap to allow us to read in the extents, result fiemap has to hold all * the extents for the whole file. Add space for the initial struct fiemap. */ - if (!greedy_realloc0((void**) &fiemap, &fiemap_allocated, - n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent))) + if (!greedy_realloc0((void**) &fiemap, n_extra + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent))) return -ENOMEM; fiemap->fm_extent_count = fiemap->fm_mapped_extents; @@ -562,7 +560,7 @@ int read_fiemap(int fd, struct fiemap **ret) { return log_debug_errno(errno, "Failed to read extents: %m"); /* Resize result_fiemap to allow us to copy in the extents */ - if (!greedy_realloc((void**) &result_fiemap, &result_fiemap_allocated, + if (!greedy_realloc((void**) &result_fiemap, n_extra + result_extents + fiemap->fm_mapped_extents, sizeof(struct fiemap_extent))) return -ENOMEM; diff --git a/src/shared/specifier.c b/src/shared/specifier.c index ef164b3942..f4c73b2741 100644 --- a/src/shared/specifier.c +++ b/src/shared/specifier.c @@ -30,18 +30,18 @@ #define POSSIBLE_SPECIFIERS ALPHANUMERICAL "%" int specifier_printf(const char *text, size_t max_length, const Specifier table[], const void *userdata, char **ret) { - size_t l, allocated = 0; _cleanup_free_ char *result = NULL; - char *t; - const char *f; bool percent = false; + const char *f; + size_t l; + char *t; int r; assert(text); assert(table); l = strlen(text); - if (!GREEDY_REALLOC(result, allocated, l + 1)) + if (!GREEDY_REALLOC(result, l + 1)) return -ENOMEM; t = result; @@ -67,7 +67,7 @@ int specifier_printf(const char *text, size_t max_length, const Specifier table[ j = t - result; k = strlen(w); - if (!GREEDY_REALLOC(result, allocated, j + k + l + 1)) + if (!GREEDY_REALLOC(result, j + k + l + 1)) return -ENOMEM; memcpy(result + j, w, k); t = result + j + k; @@ -98,13 +98,6 @@ int specifier_printf(const char *text, size_t max_length, const Specifier table[ } *(t++) = 0; - /* Try to deallocate unused bytes, but don't sweat it too much */ - if ((size_t)(t - result) < allocated) { - t = realloc(result, t - result); - if (t) - result = t; - } - *ret = TAKE_PTR(result); return 0; } diff --git a/src/shared/varlink.c b/src/shared/varlink.c index daac6fd1b0..e77b144779 100644 --- a/src/shared/varlink.c +++ b/src/shared/varlink.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include <malloc.h> #include <sys/poll.h> #include "alloc-util.h" @@ -113,13 +114,11 @@ struct Varlink { int fd; char *input_buffer; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */ - size_t input_buffer_allocated; size_t input_buffer_index; size_t input_buffer_size; size_t input_buffer_unscanned; char *output_buffer; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */ - size_t output_buffer_allocated; size_t output_buffer_index; size_t output_buffer_size; @@ -506,14 +505,14 @@ static int varlink_read(Varlink *v) { assert(v->fd >= 0); - if (v->input_buffer_allocated <= v->input_buffer_index + v->input_buffer_size) { + if (MALLOC_SIZEOF_SAFE(v->input_buffer) <= v->input_buffer_index + v->input_buffer_size) { size_t add; add = MIN(VARLINK_BUFFER_MAX - v->input_buffer_size, VARLINK_READ_SIZE); if (v->input_buffer_index == 0) { - if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_allocated, v->input_buffer_size + add)) + if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_size + add)) return -ENOMEM; } else { @@ -526,13 +525,11 @@ static int varlink_read(Varlink *v) { memcpy(b, v->input_buffer + v->input_buffer_index, v->input_buffer_size); free_and_replace(v->input_buffer, b); - - v->input_buffer_allocated = v->input_buffer_size + add; v->input_buffer_index = 0; } } - rs = v->input_buffer_allocated - (v->input_buffer_index + v->input_buffer_size); + rs = MALLOC_SIZEOF_SAFE(v->input_buffer) - (v->input_buffer_index + v->input_buffer_size); bool prefer_read = v->prefer_read_write; if (!prefer_read) { @@ -577,7 +574,7 @@ static int varlink_parse_message(Varlink *v) { return 0; assert(v->input_buffer_unscanned <= v->input_buffer_size); - assert(v->input_buffer_index + v->input_buffer_size <= v->input_buffer_allocated); + assert(v->input_buffer_index + v->input_buffer_size <= MALLOC_SIZEOF_SAFE(v->input_buffer)); begin = v->input_buffer + v->input_buffer_index; @@ -1257,12 +1254,12 @@ static int varlink_enqueue_json(Varlink *v, JsonVariant *m) { free_and_replace(v->output_buffer, text); - v->output_buffer_size = v->output_buffer_allocated = r + 1; + v->output_buffer_size = r + 1; v->output_buffer_index = 0; } else if (v->output_buffer_index == 0) { - if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_allocated, v->output_buffer_size + r + 1)) + if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_size + r + 1)) return -ENOMEM; memcpy(v->output_buffer + v->output_buffer_size, text, r + 1); @@ -1279,7 +1276,7 @@ static int varlink_enqueue_json(Varlink *v, JsonVariant *m) { memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, r + 1); free_and_replace(v->output_buffer, n); - v->output_buffer_allocated = v->output_buffer_size = new_size; + v->output_buffer_size = new_size; v->output_buffer_index = 0; } diff --git a/src/systemctl/systemctl-list-jobs.c b/src/systemctl/systemctl-list-jobs.c index 7ac0496382..a050e09c17 100644 --- a/src/systemctl/systemctl-list-jobs.c +++ b/src/systemctl/systemctl-list-jobs.c @@ -131,7 +131,6 @@ int list_jobs(int argc, char *argv[], void *userdata) { _cleanup_free_ struct job_info *jobs = NULL; const char *name, *type, *state; bool skipped = false; - size_t size = 0; unsigned c = 0; sd_bus *bus; uint32_t id; @@ -157,7 +156,7 @@ int list_jobs(int argc, char *argv[], void *userdata) { continue; } - if (!GREEDY_REALLOC(jobs, size, c + 1)) + if (!GREEDY_REALLOC(jobs, c + 1)) return log_oom(); jobs[c++] = job; diff --git a/src/systemctl/systemctl-list-machines.c b/src/systemctl/systemctl-list-machines.c index 2e891b103c..1a2f2d7153 100644 --- a/src/systemctl/systemctl-list-machines.c +++ b/src/systemctl/systemctl-list-machines.c @@ -93,7 +93,6 @@ static int get_machine_list( struct machine_info *machine_infos = NULL; _cleanup_strv_free_ char **m = NULL; _cleanup_free_ char *hn = NULL; - size_t sz = 0; char **i; int c = 0, r; @@ -102,7 +101,7 @@ static int get_machine_list( return log_oom(); if (output_show_machine(hn, patterns)) { - if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) + if (!GREEDY_REALLOC0(machine_infos, c+1)) return log_oom(); machine_infos[c].is_host = true; @@ -126,7 +125,7 @@ static int get_machine_list( if (!streq_ptr(class, "container")) continue; - if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) { + if (!GREEDY_REALLOC0(machine_infos, c+1)) { free_machines_list(machine_infos, c); return log_oom(); } diff --git a/src/systemctl/systemctl-list-unit-files.c b/src/systemctl/systemctl-list-unit-files.c index 1bf2fc18f3..fd10e7965b 100644 --- a/src/systemctl/systemctl-list-unit-files.c +++ b/src/systemctl/systemctl-list-unit-files.c @@ -136,7 +136,6 @@ static int output_unit_file_list(const UnitFileList *units, unsigned c) { int list_unit_files(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_free_ UnitFileList *units = NULL; - size_t size = 0; unsigned c = 0; const char *state; char *path; @@ -234,7 +233,7 @@ int list_unit_files(int argc, char *argv[], void *userdata) { while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) { - if (!GREEDY_REALLOC(units, size, c + 1)) + if (!GREEDY_REALLOC(units, c + 1)) return log_oom(); units[c] = (struct UnitFileList) { diff --git a/src/systemctl/systemctl-list-units.c b/src/systemctl/systemctl-list-units.c index 135d8388a3..1efb569971 100644 --- a/src/systemctl/systemctl-list-units.c +++ b/src/systemctl/systemctl-list-units.c @@ -432,7 +432,6 @@ int list_sockets(int argc, char *argv[], void *userdata) { _cleanup_free_ UnitInfo *unit_infos = NULL; _cleanup_free_ struct socket_info *socket_infos = NULL; unsigned cs = 0; - size_t size = 0; int r, n; sd_bus *bus; @@ -468,7 +467,7 @@ int list_sockets(int argc, char *argv[], void *userdata) { goto cleanup; } - if (!GREEDY_REALLOC(socket_infos, size, cs + c)) { + if (!GREEDY_REALLOC(socket_infos, cs + c)) { r = log_oom(); goto cleanup; } @@ -695,7 +694,6 @@ int list_timers(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **timers_with_suffix = NULL; _cleanup_free_ struct timer_info *timer_infos = NULL; _cleanup_free_ UnitInfo *unit_infos = NULL; - size_t size = 0; int n, c = 0; dual_timestamp nw; sd_bus *bus; @@ -736,7 +734,7 @@ int list_timers(int argc, char *argv[], void *userdata) { get_last_trigger(bus, u->unit_path, &last); - if (!GREEDY_REALLOC(timer_infos, size, c+1)) { + if (!GREEDY_REALLOC(timer_infos, c+1)) { r = log_oom(); goto cleanup; } diff --git a/src/systemctl/systemctl-util.c b/src/systemctl/systemctl-util.c index d1490c906d..99f1394bcf 100644 --- a/src/systemctl/systemctl-util.c +++ b/src/systemctl/systemctl-util.c @@ -158,7 +158,6 @@ int get_unit_list( _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; - size_t size = c; int r; bool fallback = false; @@ -218,7 +217,7 @@ int get_unit_list( if (!output_show_unit(&u, fallback ? patterns : NULL)) continue; - if (!GREEDY_REALLOC(*unit_infos, size, c+1)) + if (!GREEDY_REALLOC(*unit_infos, c+1)) return log_oom(); (*unit_infos)[c++] = u; @@ -261,17 +260,16 @@ int expand_unit_names(sd_bus *bus, char **names, const char* suffix, char ***ret if (expanded) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_free_ UnitInfo *unit_infos = NULL; - size_t allocated, n; + size_t n; r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply); if (r < 0) return r; n = strv_length(mangled); - allocated = n + 1; for (int i = 0; i < r; i++) { - if (!GREEDY_REALLOC(mangled, allocated, n+2)) + if (!GREEDY_REALLOC(mangled, n+2)) return log_oom(); mangled[n] = strdup(unit_infos[i].id); diff --git a/src/test/test-alloc-util.c b/src/test/test-alloc-util.c index 3b77dd98ca..2baae0cb9b 100644 --- a/src/test/test-alloc-util.c +++ b/src/test/test-alloc-util.c @@ -24,31 +24,31 @@ static void test_alloca(void) { static void test_GREEDY_REALLOC(void) { _cleanup_free_ int *a = NULL, *b = NULL; - size_t n_allocated = 0, i, j; + size_t i, j; /* Give valgrind a chance to verify our realloc() operations */ for (i = 0; i < 20480; i++) { - assert_se(GREEDY_REALLOC(a, n_allocated, i + 1)); - assert_se(n_allocated >= i + 1); - assert_se(malloc_usable_size(a) >= (i + 1) * sizeof(int)); + assert_se(GREEDY_REALLOC(a, i + 1)); + assert_se(MALLOC_ELEMENTSOF(a) >= i + 1); + assert_se(MALLOC_SIZEOF_SAFE(a) >= (i + 1) * sizeof(int)); a[i] = (int) i; - assert_se(GREEDY_REALLOC(a, n_allocated, i / 2)); - assert_se(n_allocated >= i / 2); - assert_se(malloc_usable_size(a) >= (i / 2) * sizeof(int)); + assert_se(GREEDY_REALLOC(a, i / 2)); + assert_se(MALLOC_ELEMENTSOF(a) >= i / 2); + assert_se(MALLOC_SIZEOF_SAFE(a) >= (i / 2) * sizeof(int)); } for (j = 0; j < i / 2; j++) assert_se(a[j] == (int) j); - for (i = 30, n_allocated = 0; i < 20480; i += 7) { - assert_se(GREEDY_REALLOC(b, n_allocated, i + 1)); - assert_se(n_allocated >= i + 1); - assert_se(malloc_usable_size(b) >= (i + 1) * sizeof(int)); + for (i = 30; i < 20480; i += 7) { + assert_se(GREEDY_REALLOC(b, i + 1)); + assert_se(MALLOC_ELEMENTSOF(b) >= i + 1); + assert_se(MALLOC_SIZEOF_SAFE(b) >= (i + 1) * sizeof(int)); b[i] = (int) i; - assert_se(GREEDY_REALLOC(b, n_allocated, i / 2)); - assert_se(n_allocated >= i / 2); - assert_se(malloc_usable_size(b) >= (i / 2) * sizeof(int)); + assert_se(GREEDY_REALLOC(b, i / 2)); + assert_se(MALLOC_ELEMENTSOF(b) >= i / 2); + assert_se(MALLOC_SIZEOF_SAFE(b) >= (i / 2) * sizeof(int)); } for (j = 30; j < i / 2; j += 7) @@ -58,8 +58,8 @@ static void test_GREEDY_REALLOC(void) { static void test_memdup_multiply_and_greedy_realloc(void) { static const int org[] = { 1, 2, 3 }; _cleanup_free_ int *dup; + size_t i; int *p; - size_t i, allocated = 3; dup = memdup_suffix0_multiply(org, sizeof(int), 3); assert_se(dup); @@ -75,16 +75,18 @@ static void test_memdup_multiply_and_greedy_realloc(void) { assert_se(dup[1] == 2); assert_se(dup[2] == 3); + memzero(dup + 3, malloc_usable_size(dup) - sizeof(int) * 3); + p = dup; - assert_se(greedy_realloc0((void**) &dup, &allocated, 2, sizeof(int)) == p); + assert_se(GREEDY_REALLOC0(dup, 2) == p); - p = (int *) greedy_realloc0((void**) &dup, &allocated, 10, sizeof(int)); + p = GREEDY_REALLOC0(dup, 10); assert_se(p == dup); - assert_se(allocated >= 10); + assert_se(MALLOC_ELEMENTSOF(p) >= 10); assert_se(p[0] == 1); assert_se(p[1] == 2); assert_se(p[2] == 3); - for (i = 3; i < allocated; i++) + for (i = 3; i < MALLOC_ELEMENTSOF(p); i++) assert_se(p[i] == 0); } @@ -139,14 +141,15 @@ static void test_auto_erase_memory(void) { /* print address of p2, else e.g. clang-11 will optimize it out */ log_debug("p1: %p p2: %p", &p1, &p2); - assert_se(p1 = new(uint8_t, 1024)); - assert_se(p2 = new(uint8_t, 1024)); + assert_se(p1 = new(uint8_t, 4703)); /* use prime size, to ensure that there will be free space at the + * end of the allocation, since malloc() enforces alignment */ + assert_se(p2 = new(uint8_t, 4703)); - assert_se(genuine_random_bytes(p1, 1024, RANDOM_BLOCK) == 0); + assert_se(genuine_random_bytes(p1, 4703, RANDOM_BLOCK) == 0); /* before we exit the scope, do something with this data, so that the compiler won't optimize this away */ - memcpy(p2, p1, 1024); - for (size_t i = 0; i < 1024; i++) + memcpy(p2, p1, 4703); + for (size_t i = 0; i < 4703; i++) assert_se(p1[i] == p2[i]); } diff --git a/src/test/test-nss-hosts.c b/src/test/test-nss-hosts.c index 42ed53adc3..eddb047951 100644 --- a/src/test/test-nss-hosts.c +++ b/src/test/test-nss-hosts.c @@ -354,15 +354,13 @@ static void test_byaddr(void *handle, static int make_addresses(struct local_address **addresses) { int n; - size_t n_alloc; _cleanup_free_ struct local_address *addrs = NULL; n = local_addresses(NULL, 0, AF_UNSPEC, &addrs); if (n < 0) log_info_errno(n, "Failed to query local addresses: %m"); - n_alloc = n; /* we _can_ do that */ - assert_se(GREEDY_REALLOC(addrs, n_alloc, n + 3)); + assert_se(GREEDY_REALLOC(addrs, n + 3)); addrs[n++] = (struct local_address) { .family = AF_INET, .address.in = { htobe32(0x7F000001) } }; @@ -406,7 +404,6 @@ static int parse_argv(int argc, char **argv, _cleanup_strv_free_ char **modules = NULL, **names = NULL; _cleanup_free_ struct local_address *addrs = NULL; - size_t n_allocated = 0; const char *p; int r, n = 0; @@ -446,7 +443,7 @@ static int parse_argv(int argc, char **argv, if (r < 0) return r; } else { - assert_se(GREEDY_REALLOC0(addrs, n_allocated, n + 1)); + assert_se(GREEDY_REALLOC0(addrs, n + 1)); addrs[n++] = (struct local_address) { .family = family, .address = address }; diff --git a/src/tmpfiles/tmpfiles.c b/src/tmpfiles/tmpfiles.c index 1e09c256b0..3eac712b0b 100644 --- a/src/tmpfiles/tmpfiles.c +++ b/src/tmpfiles/tmpfiles.c @@ -148,7 +148,6 @@ typedef struct Item { typedef struct ItemArray { Item *items; size_t n_items; - size_t allocated; struct ItemArray *parent; Set *children; @@ -2952,7 +2951,7 @@ static int parse_line( } } - if (!GREEDY_REALLOC(existing->items, existing->allocated, existing->n_items + 1)) + if (!GREEDY_REALLOC(existing->items, existing->n_items + 1)) return log_oom(); existing->items[existing->n_items++] = i; diff --git a/src/udev/cdrom_id/cdrom_id.c b/src/udev/cdrom_id/cdrom_id.c index f2d54b297d..df0ee6a3bb 100644 --- a/src/udev/cdrom_id/cdrom_id.c +++ b/src/udev/cdrom_id/cdrom_id.c @@ -89,7 +89,6 @@ typedef struct Context { Feature *drive_features; size_t n_drive_feature; - size_t n_allocated; Feature media_feature; bool has_media; @@ -137,7 +136,7 @@ static int set_drive_feature(Context *c, Feature f) { if (drive_has_feature(c, f)) return 0; - if (!GREEDY_REALLOC(c->drive_features, c->n_allocated, c->n_drive_feature + 1)) + if (!GREEDY_REALLOC(c->drive_features, c->n_drive_feature + 1)) return -ENOMEM; c->drive_features[c->n_drive_feature++] = f; diff --git a/src/udev/udevadm-info.c b/src/udev/udevadm-info.c index 33fdecca50..fa7f04f14c 100644 --- a/src/udev/udevadm-info.c +++ b/src/udev/udevadm-info.c @@ -66,8 +66,8 @@ static int sysattr_compare(const SysAttr *a, const SysAttr *b) { static int print_all_attributes(sd_device *device, bool is_parent) { _cleanup_free_ SysAttr *sysattrs = NULL; - size_t n_items = 0, n_allocated = 0; const char *name, *value; + size_t n_items = 0; value = NULL; (void) sd_device_get_devpath(device, &value); @@ -105,7 +105,7 @@ static int print_all_attributes(sd_device *device, bool is_parent) { if (len > 0) continue; - if (!GREEDY_REALLOC(sysattrs, n_allocated, n_items + 1)) + if (!GREEDY_REALLOC(sysattrs, n_items + 1)) return log_oom(); sysattrs[n_items] = (SysAttr) { diff --git a/src/xdg-autostart-generator/xdg-autostart-service.c b/src/xdg-autostart-generator/xdg-autostart-service.c index 00d8b76539..5068c0ebb3 100644 --- a/src/xdg-autostart-generator/xdg-autostart-service.c +++ b/src/xdg-autostart-generator/xdg-autostart-service.c @@ -188,7 +188,6 @@ static int strv_strndup_unescape_and_push( const char *filename, unsigned line, char ***sv, - size_t *n_allocated, size_t *n, const char *start, const char *end) { @@ -207,7 +206,7 @@ static int strv_strndup_unescape_and_push( if (r < 0) return r; - if (!greedy_realloc((void**) sv, n_allocated, *n + 2, sizeof(char*))) /* One extra for NULL */ + if (!GREEDY_REALLOC(*sv, *n + 2)) /* One extra for NULL */ return log_oom(); (*sv)[*n] = TAKE_PTR(copy); @@ -243,10 +242,10 @@ static int xdg_config_parse_strv( return 0; } - size_t n = 0, n_allocated = 0; + size_t n = 0; _cleanup_strv_free_ char **sv = NULL; - if (!GREEDY_REALLOC0(sv, n_allocated, 1)) + if (!GREEDY_REALLOC0(sv, 1)) return log_oom(); /* We cannot use strv_split because it does not handle escaping correctly. */ @@ -265,7 +264,7 @@ static int xdg_config_parse_strv( if (*end == ';') { r = strv_strndup_unescape_and_push(unit, filename, line, - &sv, &n_allocated, &n, + &sv, &n, start, end); if (r < 0) return r; @@ -276,7 +275,7 @@ static int xdg_config_parse_strv( /* Handle the trailing entry after the last separator */ r = strv_strndup_unescape_and_push(unit, filename, line, - &sv, &n_allocated, &n, + &sv, &n, start, end); if (r < 0) return r; |