Blame lib/malloc/scratch_buffer_grow_preserve.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 <string.h>
Packit 8f70b4
Packit 8f70b4
bool
Packit 8f70b4
__libc_scratch_buffer_grow_preserve (struct scratch_buffer *buffer)
Packit 8f70b4
{
Packit 8f70b4
  size_t new_length = 2 * buffer->length;
Packit 8f70b4
  void *new_ptr;
Packit 8f70b4
Packit 8f70b4
  if (buffer->data == buffer->__space)
Packit 8f70b4
    {
Packit 8f70b4
      /* Move buffer to the heap.  No overflow is possible because
Packit 8f70b4
	 buffer->length describes a small buffer on the stack.  */
Packit 8f70b4
      new_ptr = malloc (new_length);
Packit 8f70b4
      if (new_ptr == NULL)
Packit 8f70b4
	return false;
Packit 8f70b4
      memcpy (new_ptr, buffer->__space, buffer->length);
Packit 8f70b4
    }
Packit 8f70b4
  else
Packit 8f70b4
    {
Packit 8f70b4
      /* Buffer was already on the heap.  Check for overflow.  */
Packit 8f70b4
      if (__glibc_likely (new_length >= buffer->length))
Packit 8f70b4
	new_ptr = realloc (buffer->data, new_length);
Packit 8f70b4
      else
Packit 8f70b4
	{
Packit 8f70b4
	  __set_errno (ENOMEM);
Packit 8f70b4
	  new_ptr = NULL;
Packit 8f70b4
	}
Packit 8f70b4
Packit 8f70b4
      if (__glibc_unlikely (new_ptr == NULL))
Packit 8f70b4
	{
Packit 8f70b4
	  /* Deallocate, but buffer must remain valid to free.  */
Packit 8f70b4
	  free (buffer->data);
Packit 8f70b4
	  scratch_buffer_init (buffer);
Packit 8f70b4
	  return false;
Packit 8f70b4
	}
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_grow_preserve)