Compatibility fixes in reallocarr(3)

Make this work on !NetBSD platforms:
- replace __CTASSERT() with platform agnostic solution SQRT_SIZE_MAX
- include nbtool_config.h for cross builds to get definition of __RCSID()
- restore errno in the last rare code path for platforms affecting errno(2)
  in memcpy(2)

While there: rename parameter name 'num' to 'number' to be in sync with
the calloc(3) parameter naming.

Reported by scole_mail at the current-users ml.
This commit is contained in:
kamil 2015-07-28 17:13:34 +00:00
parent f9da13407d
commit 638c990b9a
2 changed files with 21 additions and 10 deletions

View File

@ -1,4 +1,4 @@
.\" $NetBSD: reallocarr.3,v 1.3 2015/02/19 23:08:21 wiz Exp $
.\" $NetBSD: reallocarr.3,v 1.4 2015/07/28 17:13:34 kamil Exp $
.\"
.\" Copyright (c) 2015 The NetBSD Foundation, Inc.
.\" All rights reserved.
@ -37,7 +37,7 @@
.Ft int
.Fo reallocarr
.Fa "void *ptr"
.Fa "size_t num"
.Fa "size_t number"
.Fa "size_t size"
.Fc
.Sh DESCRIPTION

View File

@ -1,4 +1,4 @@
/* $NetBSD: reallocarr.c,v 1.2 2015/07/16 00:03:59 kamil Exp $ */
/* $NetBSD: reallocarr.c,v 1.3 2015/07/28 17:13:34 kamil Exp $ */
/*-
* Copyright (c) 2015 Joerg Sonnenberger <joerg@NetBSD.org>.
@ -29,8 +29,12 @@
* SUCH DAMAGE.
*/
#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
__RCSID("$NetBSD: reallocarr.c,v 1.2 2015/07/16 00:03:59 kamil Exp $");
__RCSID("$NetBSD: reallocarr.c,v 1.3 2015/07/28 17:13:34 kamil Exp $");
#include "namespace.h"
#include <errno.h>
@ -40,16 +44,17 @@ __RCSID("$NetBSD: reallocarr.c,v 1.2 2015/07/16 00:03:59 kamil Exp $");
#include <stdlib.h>
#include <string.h>
__CTASSERT(65535 < SIZE_MAX / 65535);
#ifdef _LIBC
#ifdef __weak_alias
__weak_alias(reallocarr, _reallocarr)
#endif
#endif
#define SQRT_SIZE_MAX (1UL << (sizeof(size_t) << 2))
#if !HAVE_REALLOCARR
int
reallocarr(void *ptr, size_t num, size_t size)
reallocarr(void *ptr, size_t number, size_t size)
{
int saved_errno, result;
void *optr;
@ -57,16 +62,21 @@ reallocarr(void *ptr, size_t num, size_t size)
saved_errno = errno;
memcpy(&optr, ptr, sizeof(ptr));
if (num == 0 || size == 0) {
if (number == 0 || size == 0) {
free(optr);
nptr = NULL;
memcpy(ptr, &nptr, sizeof(ptr));
errno = saved_errno;
return 0;
}
if ((num >= 65535 || size >= 65535) && num > SIZE_MAX / size)
if ((number >= SQRT_SIZE_MAX || size >= SQRT_SIZE_MAX) &&
number > SIZE_MAX / size) {
errno = saved_errno;
return EOVERFLOW;
nptr = realloc(optr, num * size);
}
nptr = realloc(optr, number * size);
if (nptr == NULL) {
result = errno;
} else {
@ -76,3 +86,4 @@ reallocarr(void *ptr, size_t num, size_t size)
errno = saved_errno;
return result;
}
#endif