60 changes: 41 additions & 19 deletions src/login/logind-seat.c
Expand Up @@ -267,61 +267,83 @@ 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);

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;
}
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand All @@ -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;

Expand Down
1 change: 0 additions & 1 deletion src/login/logind-seat.h
Expand Up @@ -19,7 +19,6 @@ struct Seat {
LIST_HEAD(Session, sessions);

Session **positions;
size_t position_count;

bool in_gc_queue:1;
bool started:1;
Expand Down
9 changes: 4 additions & 5 deletions src/machine/machine.c
Expand Up @@ -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 (;;) {
Expand All @@ -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;
}

Expand Down
4 changes: 2 additions & 2 deletions src/machine/machinectl.c
Expand Up @@ -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;

Expand All @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions src/mount/mount-tool.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/network/networkctl.c
Expand Up @@ -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);
Expand All @@ -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);
Expand Down
20 changes: 12 additions & 8 deletions src/network/networkd-dhcp-server.c
Expand Up @@ -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);

Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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++)
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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");
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 2 additions & 2 deletions src/network/networkd-radv.c
Expand Up @@ -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);
Expand All @@ -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;
Expand Down
10 changes: 5 additions & 5 deletions src/network/test-network.c
Expand Up @@ -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);
}

Expand All @@ -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"));
Expand All @@ -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"));
Expand All @@ -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);
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/nspawn/nspawn-setuid.c
Expand Up @@ -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;
Expand Down Expand Up @@ -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++]);
Expand Down
5 changes: 2 additions & 3 deletions src/partition/repart.c
Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/portable/portabled-image-bus.c
Expand Up @@ -1073,8 +1073,8 @@ int bus_image_object_find(
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;

Expand All @@ -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;
}
Expand Down
7 changes: 3 additions & 4 deletions src/pstore/pstore.c
Expand Up @@ -101,7 +101,6 @@ typedef struct PStoreEntry {

typedef struct PStoreList {
PStoreEntry *entries;
size_t n_allocated;
size_t n_entries;
} PStoreList;

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/resolve/resolvectl.c
Expand Up @@ -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;
Expand All @@ -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 };
Expand Down
6 changes: 3 additions & 3 deletions src/resolve/resolved-dns-packet.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/resolve/resolved-etc-hosts.c
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/resolve/resolved-etc-hosts.h
Expand Up @@ -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);
Expand Down
11 changes: 6 additions & 5 deletions 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>

Expand Down Expand Up @@ -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 */
Expand All @@ -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")));
Expand All @@ -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"));
Expand Down
5 changes: 2 additions & 3 deletions src/shared/bitmap.c
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
1 change: 0 additions & 1 deletion src/shared/bitmap.h
Expand Up @@ -9,7 +9,6 @@
typedef struct Bitmap {
uint64_t *bitmaps;
size_t n_bitmaps;
size_t bitmaps_allocated;
} Bitmap;

Bitmap* bitmap_new(void);
Expand Down
11 changes: 3 additions & 8 deletions src/shared/bootspec.c
Expand Up @@ -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;

Expand All @@ -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);
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -749,16 +747,13 @@ int boot_entries_augment_from_loader(
"auto-reboot-to-firmware-setup", "Reboot Into Firmware Interface",
};

size_t n_allocated;
char **i;

assert(config);

/* 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;
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/shared/bpf-program.c
Expand Up @@ -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);
Expand Down
1 change: 0 additions & 1 deletion src/shared/bpf-program.h
Expand Up @@ -17,7 +17,6 @@ struct BPFProgram {
uint32_t prog_type;

size_t n_instructions;
size_t allocated;
struct bpf_insn *instructions;

char *attached_path;
Expand Down
4 changes: 2 additions & 2 deletions src/shared/bus-message-util.c
Expand Up @@ -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);
Expand All @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/shared/bus-unit-procs.c
Expand Up @@ -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
Expand All @@ -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) {
Expand Down
9 changes: 4 additions & 5 deletions src/shared/cgroup-show.c
Expand Up @@ -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);
Expand All @@ -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;
}

Expand Down
10 changes: 5 additions & 5 deletions src/shared/cpu-set-util.c
Expand Up @@ -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);
Expand All @@ -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++)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions src/shared/dissect-image.c
Expand Up @@ -1780,7 +1780,6 @@ typedef struct DecryptedPartition {
struct DecryptedImage {
DecryptedPartition *decrypted;
size_t n_decrypted;
size_t n_allocated;
};
#endif

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions src/shared/dns-domain.c
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -471,12 +471,12 @@ int dns_name_concat(const char *a, const char *b, DNSLabelFlags flags, char **_r
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;
}

Expand Down
3 changes: 1 addition & 2 deletions src/shared/efi-loader.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
15 changes: 6 additions & 9 deletions src/shared/format-table.c
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down
19 changes: 9 additions & 10 deletions src/shared/install.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
38 changes: 19 additions & 19 deletions 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"
Expand Down Expand Up @@ -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;

Expand All @@ -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 (;;) {
Expand All @@ -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;
Expand All @@ -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);

Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -452,28 +450,30 @@ 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)
log_warning("Failed to reallocate buffer to (smaller) size %zu",
target);
else {
log_debug("Reallocated buffer from %zu to %zu bytes",
imp->size, target);
old_size, target);
imp->buf = tmp;
imp->size = target;
}
}
}
Expand Down
1 change: 0 additions & 1 deletion src/shared/journal-importer.h
Expand Up @@ -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 */
Expand Down
30 changes: 15 additions & 15 deletions src/shared/json.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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 */
Expand All @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
22 changes: 10 additions & 12 deletions src/shared/local-addresses.c
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -175,21 +175,19 @@ 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,
const RouteVia *via) {

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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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;

Expand All @@ -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;

Expand All @@ -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;
}
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down
6 changes: 2 additions & 4 deletions src/shared/sleep-config.c
Expand Up @@ -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");
Expand Down Expand Up @@ -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;
Expand All @@ -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;

Expand Down
17 changes: 5 additions & 12 deletions src/shared/specifier.c
Expand Up @@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
19 changes: 8 additions & 11 deletions 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"
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand All @@ -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;
}

Expand Down
3 changes: 1 addition & 2 deletions src/systemctl/systemctl-list-jobs.c
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
5 changes: 2 additions & 3 deletions src/systemctl/systemctl-list-machines.c
Expand Up @@ -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;

Expand All @@ -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;
Expand All @@ -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();
}
Expand Down
3 changes: 1 addition & 2 deletions src/systemctl/systemctl-list-unit-files.c
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 2 additions & 4 deletions src/systemctl/systemctl-list-units.c
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
8 changes: 3 additions & 5 deletions src/systemctl/systemctl-util.c
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
51 changes: 27 additions & 24 deletions src/test/test-alloc-util.c
Expand Up @@ -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)
Expand All @@ -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);
Expand All @@ -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);
}

Expand Down Expand Up @@ -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]);
}

Expand Down
7 changes: 2 additions & 5 deletions src/test/test-nss-hosts.c
Expand Up @@ -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) } };
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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 };
Expand Down
3 changes: 1 addition & 2 deletions src/tmpfiles/tmpfiles.c
Expand Up @@ -148,7 +148,6 @@ typedef struct Item {
typedef struct ItemArray {
Item *items;
size_t n_items;
size_t allocated;

struct ItemArray *parent;
Set *children;
Expand Down Expand Up @@ -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;
Expand Down
3 changes: 1 addition & 2 deletions src/udev/cdrom_id/cdrom_id.c
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions src/udev/udevadm-info.c
Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down
11 changes: 5 additions & 6 deletions src/xdg-autostart-generator/xdg-autostart-service.c
Expand Up @@ -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) {
Expand All @@ -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);
Expand Down Expand Up @@ -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. */
Expand All @@ -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;
Expand All @@ -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;
Expand Down