Blame lib/malloc/scratch_buffer_set_array_size.c

Packit 8f70b4
/* Variable-sized buffer with on-stack default allocation.
Packit 8f70b4
   Copyright (C) 2015-2018 Free Software Foundation, Inc.
Packit 8f70b4
   This file is part of the GNU C Library.
Packit 8f70b4
Packit 8f70b4
   The GNU C Library is free software; you can redistribute it and/or
Packit 8f70b4
   modify it under the terms of the GNU General Public
Packit 8f70b4
   License as published by the Free Software Foundation; either
Packit 8f70b4
   version 3 of the License, or (at your option) any later version.
Packit 8f70b4
Packit 8f70b4
   The GNU C Library is distributed in the hope that it will be useful,
Packit 8f70b4
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 8f70b4
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit 8f70b4
   General Public License for more details.
Packit 8f70b4
Packit 8f70b4
   You should have received a copy of the GNU General Public
Packit 8f70b4
   License along with the GNU C Library; if not, see
Packit 8f70b4
   <https://www.gnu.org/licenses/>.  */
Packit 8f70b4
Packit 8f70b4
#ifndef _LIBC
Packit 8f70b4
# include <libc-config.h>
Packit 8f70b4
#endif
Packit 8f70b4
Packit 8f70b4
#include <scratch_buffer.h>
Packit 8f70b4
#include <errno.h>
Packit 8f70b4
#include <limits.h>
Packit 8f70b4
Packit 8f70b4
bool
Packit 8f70b4
__libc_scratch_buffer_set_array_size (struct scratch_buffer *buffer,
Packit 8f70b4
				      size_t nelem, size_t size)
Packit 8f70b4
{
Packit 8f70b4
  size_t new_length = nelem * size;
Packit 8f70b4
Packit 8f70b4
  /* Avoid overflow check if both values are small. */
Packit 8f70b4
  if ((nelem | size) >> (sizeof (size_t) * CHAR_BIT / 2) != 0
Packit 8f70b4
      && nelem != 0 && size != new_length / nelem)
Packit 8f70b4
    {
Packit 8f70b4
      /* Overflow.  Discard the old buffer, but it must remain valid
Packit 8f70b4
	 to free.  */
Packit 8f70b4
      scratch_buffer_free (buffer);
Packit 8f70b4
      scratch_buffer_init (buffer);
Packit 8f70b4
      __set_errno (ENOMEM);
Packit 8f70b4
      return false;
Packit 8f70b4
    }
Packit 8f70b4
Packit 8f70b4
  if (new_length <= buffer->length)
Packit 8f70b4
    return true;
Packit 8f70b4
Packit 8f70b4
  /* Discard old buffer.  */
Packit 8f70b4
  scratch_buffer_free (buffer);
Packit 8f70b4
Packit 8f70b4
  char *new_ptr = malloc (new_length);
Packit 8f70b4
  if (new_ptr == NULL)
Packit 8f70b4
    {
Packit 8f70b4
      /* Buffer must remain valid to free.  */
Packit 8f70b4
      scratch_buffer_init (buffer);
Packit 8f70b4
      return false;
Packit 8f70b4
    }
Packit 8f70b4
Packit 8f70b4
  /* Install new heap-based buffer.  */
Packit 8f70b4
  buffer->data = new_ptr;
Packit 8f70b4
  buffer->length = new_length;
Packit 8f70b4
  return true;
Packit 8f70b4
}
Packit 8f70b4
libc_hidden_def (__libc_scratch_buffer_set_array_size)