hipack-alloc.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * hipack-alloc.c
  3. * Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
  4. *
  5. * Distributed under terms of the MIT license.
  6. */
  7. #include "hipack.h"
  8. #include <sys/types.h>
  9. #include <stdlib.h>
  10. #include <errno.h>
  11. void* (*hipack_alloc) (void*, size_t) = hipack_alloc_stdlib;
  12. void*
  13. hipack_alloc_stdlib (void *optr, size_t size)
  14. {
  15. if (size) {
  16. optr = optr ? realloc (optr, size) : malloc (size);
  17. if (!optr) {
  18. fprintf (stderr, "aborted: %s\n", strerror (errno));
  19. fflush (stderr);
  20. abort ();
  21. }
  22. } else {
  23. free (optr);
  24. optr = NULL;
  25. }
  26. return optr;
  27. }
  28. /*
  29. * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
  30. * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
  31. */
  32. #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
  33. void*
  34. hipack_alloc_array_extra (void *optr, size_t nmemb, size_t size, size_t extra)
  35. {
  36. if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
  37. nmemb > 0 && SIZE_MAX / nmemb < size) {
  38. fprintf (stderr, "aborted: %s\n", strerror (ENOMEM));
  39. fflush (stderr);
  40. abort ();
  41. }
  42. return (*hipack_alloc) (optr, size * nmemb + extra);
  43. }