Path: blob/main/contrib/libfido2/openbsd-compat/recallocarray.c
39507 views
/* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto Exp $ */1/*2* Copyright (c) 2008, 2017 Otto Moerbeek <[email protected]>3*4* Permission to use, copy, modify, and distribute this software for any5* purpose with or without fee is hereby granted, provided that the above6* copyright notice and this permission notice appear in all copies.7*8* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES9* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF10* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR11* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES12* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN13* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF14* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.15*/1617/* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */1819#include "openbsd-compat.h"2021#if !defined(HAVE_RECALLOCARRAY)2223#include <errno.h>24#include <stdlib.h>25#include <stdint.h>26#include <string.h>27#ifdef HAVE_UNISTD_H28#include <unistd.h>29#endif3031/*32* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX33* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW34*/35#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))3637void *38recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)39{40size_t oldsize, newsize;41void *newptr;4243if (ptr == NULL)44return calloc(newnmemb, size);4546if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&47newnmemb > 0 && SIZE_MAX / newnmemb < size) {48errno = ENOMEM;49return NULL;50}51newsize = newnmemb * size;5253if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&54oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {55errno = EINVAL;56return NULL;57}58oldsize = oldnmemb * size;5960/*61* Don't bother too much if we're shrinking just a bit,62* we do not shrink for series of small steps, oh well.63*/64if (newsize <= oldsize) {65size_t d = oldsize - newsize;6667if (d < oldsize / 2 && d < (size_t)getpagesize()) {68memset((char *)ptr + newsize, 0, d);69return ptr;70}71}7273newptr = malloc(newsize);74if (newptr == NULL)75return NULL;7677if (newsize > oldsize) {78memcpy(newptr, ptr, oldsize);79memset((char *)newptr + oldsize, 0, newsize - oldsize);80} else81memcpy(newptr, ptr, newsize);8283explicit_bzero(ptr, oldsize);84free(ptr);8586return newptr;87}88/* DEF_WEAK(recallocarray); */8990#endif /* !defined(HAVE_RECALLOCARRAY) */919293