From ff2f2a312b89cb7a21b7d54584c0700132ae0ed6 Mon Sep 17 00:00:00 2001 From: pancake Date: Sat, 30 Mar 2024 12:07:33 +0100 Subject: [PATCH] Fix #22767 - Some UB when malloc(0) in RBuffer api ##crash --- libr/core/cio.c | 8 +++++--- libr/util/buf_bytes.c | 18 +++++++++++++++--- libr/util/mem.c | 9 ++++++--- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/libr/core/cio.c b/libr/core/cio.c index 89fb71077d..1108aed780 100644 --- a/libr/core/cio.c +++ b/libr/core/cio.c @@ -159,9 +159,11 @@ R_API ut8* r_core_transform_op(RCore *core, const char *arg, char op) { len = xlen; } else { // use clipboard as key const ut8 *tmp = r_buf_data (core->yank_buf, &len); - str = r_mem_dup (tmp, len); - if (!str) { - goto beach; + if (tmp && len > 0) { + str = r_mem_dup (tmp, len); + if (!str) { + goto beach; + } } } } else { diff --git a/libr/util/buf_bytes.c b/libr/util/buf_bytes.c index 55e8e6fe03..fbe42c8d5c 100644 --- a/libr/util/buf_bytes.c +++ b/libr/util/buf_bytes.c @@ -1,4 +1,4 @@ -/* radare - LGPL - Copyright 2009-2020 - ret2libc */ +/* radare - LGPL - Copyright 2009-2024 - ret2libc */ #include @@ -35,14 +35,26 @@ static bool buf_bytes_init(RBuffer *b, const void *user) { priv->buf = (ut8 *)u->data_steal; priv->is_bufowner = u->steal; } else { - priv->buf = malloc (priv->length); +#if 0 + size_t length = priv->length > 0? priv->length: 1; + priv->buf = malloc (length); if (!priv->buf) { free (priv); return false; } - if (priv->length) { + if (priv->length > 0) { memmove (priv->buf, u->data, priv->length); } +#else + if (priv->length > 0) { + priv->buf = malloc (priv->length); + if (!priv->buf) { + free (priv); + return false; + } + memmove (priv->buf, u->data, priv->length); + } +#endif priv->is_bufowner = true; } b->priv = priv; diff --git a/libr/util/mem.c b/libr/util/mem.c index 15b98881db..72f5865b49 100644 --- a/libr/util/mem.c +++ b/libr/util/mem.c @@ -303,9 +303,12 @@ R_API bool r_mem_protect(void *ptr, int size, const char *prot) { R_API void *r_mem_dup(const void *s, int l) { r_return_val_if_fail (s, NULL); - void *d = malloc (l); - if (d != NULL) { - memcpy (d, s, l); + void *d = NULL; + if (l > 0) { + d = malloc (l); + if (d != NULL) { + memcpy (d, s, l); + } } return d; }