From: claudio Date: Tue, 23 May 2023 12:41:28 +0000 (+0000) Subject: Avoid calling malloc with a zero length argument. X-Git-Url: http://artulab.com/gitweb/?a=commitdiff_plain;h=e2fc702335c2e6aa08781bd346ec98c392615337;p=openbsd Avoid calling malloc with a zero length argument. ibuf_open() will return an error in this case while ibuf_dynamic() accepts a 0 len argument and just initialized the buffer and length to zero. A later ibuf_realloc() call will take care of allocating the buffer. Additionally switch from malloc() to calloc() when allocating the buffer this way the buffer is initalized and in ibuf_reserve() an addtional memset() is used to make sure that the reserved data is zeroed. OK tb@ --- diff --git a/lib/libutil/imsg-buffer.c b/lib/libutil/imsg-buffer.c index 7abea4e0deb..ef0a1151f2a 100644 --- a/lib/libutil/imsg-buffer.c +++ b/lib/libutil/imsg-buffer.c @@ -1,4 +1,4 @@ -/* $OpenBSD: imsg-buffer.c,v 1.14 2022/04/23 08:57:52 tobias Exp $ */ +/* $OpenBSD: imsg-buffer.c,v 1.15 2023/05/23 12:41:28 claudio Exp $ */ /* * Copyright (c) 2003, 2004 Henning Brauer @@ -38,9 +38,13 @@ ibuf_open(size_t len) { struct ibuf *buf; + if (len == 0) { + errno = EINVAL; + return (NULL); + } if ((buf = calloc(1, sizeof(struct ibuf))) == NULL) return (NULL); - if ((buf->buf = malloc(len)) == NULL) { + if ((buf->buf = calloc(len, 1)) == NULL) { free(buf); return (NULL); } @@ -55,14 +59,22 @@ ibuf_dynamic(size_t len, size_t max) { struct ibuf *buf; - if (max < len) + if (max < len) { + errno = EINVAL; return (NULL); + } - if ((buf = ibuf_open(len)) == NULL) + if ((buf = calloc(1, sizeof(struct ibuf))) == NULL) return (NULL); - - if (max > 0) - buf->max = max; + if (len > 0) { + if ((buf->buf = calloc(len, 1)) == NULL) { + free(buf); + return (NULL); + } + } + buf->size = len; + buf->max = max; + buf->fd = -1; return (buf); } @@ -120,6 +132,7 @@ ibuf_reserve(struct ibuf *buf, size_t len) b = buf->buf + buf->wpos; buf->wpos += len; + memset(b, 0, len); return (b); }