Path: blob/main/core/coreutils/src/compat/recallocarray.c
1067 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*/16#include "compat.h"1718#include <errno.h>19#include <stdlib.h>20#include <stdint.h>21#include <string.h>22#include <unistd.h>2324/*25* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX26* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW27*/28#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))2930void *31recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)32{33size_t oldsize, newsize;34void *newptr;3536if (ptr == NULL)37return calloc(newnmemb, size);3839if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&40newnmemb > 0 && SIZE_MAX / newnmemb < size) {41errno = ENOMEM;42return NULL;43}44newsize = newnmemb * size;4546if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&47oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {48errno = EINVAL;49return NULL;50}51oldsize = oldnmemb * size;5253/*54* Don't bother too much if we're shrinking just a bit,55* we do not shrink for series of small steps, oh well.56*/57if (newsize <= oldsize) {58size_t d = oldsize - newsize;5960if (d < oldsize / 2 && d < getpagesize()) {61memset((char *)ptr + newsize, 0, d);62return ptr;63}64}6566newptr = malloc(newsize);67if (newptr == NULL)68return NULL;6970if (newsize > oldsize) {71memcpy(newptr, ptr, oldsize);72memset((char *)newptr + oldsize, 0, newsize - oldsize);73} else74memcpy(newptr, ptr, newsize);7576explicit_bzero(ptr, oldsize);77free(ptr);7879return newptr;80}818283