From 6b69b52a475ccaa9fda520a33c1e4ac066e5bbb4 Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Mon, 19 Dec 2022 11:19:19 +0000 Subject: calloc: consolidate ENOMEM handling We can simplify the error paths in calloc and call memset() outside of the RCU critical section. --- mwrap_core.h | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/mwrap_core.h b/mwrap_core.h index b382018..14e5d79 100644 --- a/mwrap_core.h +++ b/mwrap_core.h @@ -662,8 +662,7 @@ void *malloc(size_t size) p = hdr2ptr(h); } update_stats_rcu_unlock(l); - if (caa_unlikely(!p)) errno = ENOMEM; - return p; + if (p) return p; enomem: errno = ENOMEM; return 0; @@ -674,14 +673,10 @@ void *calloc(size_t nmemb, size_t size) size_t asize; size_t generation = 0; - if (__builtin_mul_overflow(size, nmemb, &size)) { - errno = ENOMEM; - return 0; - } - if (__builtin_add_overflow(size, sizeof(struct alloc_hdr), &asize)) { - errno = ENOMEM; - return 0; - } + if (__builtin_mul_overflow(size, nmemb, &size)) + goto enomem; + if (__builtin_add_overflow(size, sizeof(struct alloc_hdr), &asize)) + goto enomem; struct alloc_hdr *h; SRC_LOC_BT(bt); struct src_loc *l = update_stats_rcu_lock(&generation, size, &bt.sl); @@ -689,11 +684,12 @@ void *calloc(size_t nmemb, size_t size) if (p) { alloc_insert_rcu(l, h, size, h, generation); p = hdr2ptr(h); - memset(p, 0, size); } update_stats_rcu_unlock(l); - if (caa_unlikely(!p)) errno = ENOMEM; - return p; + if (p) return memset(p, 0, size); +enomem: + errno = ENOMEM; + return 0; } void *realloc(void *ptr, size_t size) -- cgit v1.2.3-24-ge0c7