Mirror of strace – the linux syscall tracer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmalloc.c 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*
  2. * Copyright (c) 2015 Dmitry V. Levin <ldv@altlinux.org>
  3. * Copyright (c) 2015-2019 The strace developers.
  4. * All rights reserved.
  5. *
  6. * SPDX-License-Identifier: LGPL-2.1-or-later
  7. */
  8. #ifdef HAVE_CONFIG_H
  9. # include "config.h"
  10. #endif
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "error_prints.h"
  14. #include "xmalloc.h"
  15. static void
  16. die_out_of_memory(void)
  17. {
  18. static int recursed;
  19. if (recursed)
  20. exit(1);
  21. recursed = 1;
  22. error_msg_and_die("Out of memory");
  23. }
  24. void *
  25. xmalloc(size_t size)
  26. {
  27. void *p = malloc(size);
  28. if (!p)
  29. die_out_of_memory();
  30. return p;
  31. }
  32. void *
  33. xcalloc(size_t nmemb, size_t size)
  34. {
  35. void *p = calloc(nmemb, size);
  36. if (!p)
  37. die_out_of_memory();
  38. return p;
  39. }
  40. #define HALF_SIZE_T (((size_t) 1) << (sizeof(size_t) * 4))
  41. void *
  42. xreallocarray(void *ptr, size_t nmemb, size_t size)
  43. {
  44. size_t bytes = nmemb * size;
  45. if ((nmemb | size) >= HALF_SIZE_T &&
  46. size && bytes / size != nmemb)
  47. die_out_of_memory();
  48. void *p = realloc(ptr, bytes);
  49. if (!p)
  50. die_out_of_memory();
  51. return p;
  52. }
  53. void *
  54. xgrowarray(void *const ptr, size_t *const nmemb, const size_t memb_size)
  55. {
  56. /* this is the same value as glibc DEFAULT_MXFAST */
  57. enum { DEFAULT_ALLOC_SIZE = 64 * SIZEOF_LONG / 4 };
  58. size_t grow_memb;
  59. if (ptr == NULL)
  60. grow_memb = *nmemb ? 0 :
  61. (DEFAULT_ALLOC_SIZE + memb_size - 1) / memb_size;
  62. else
  63. grow_memb = (*nmemb >> 1) + 1;
  64. if ((*nmemb + grow_memb) < *nmemb)
  65. die_out_of_memory();
  66. *nmemb += grow_memb;
  67. return xreallocarray(ptr, *nmemb, memb_size);
  68. }
  69. char *
  70. xstrdup(const char *str)
  71. {
  72. if (!str)
  73. return NULL;
  74. char *p = strdup(str);
  75. if (!p)
  76. die_out_of_memory();
  77. return p;
  78. }
  79. char *
  80. xstrndup(const char *str, size_t n)
  81. {
  82. char *p;
  83. if (!str)
  84. return NULL;
  85. #ifdef HAVE_STRNDUP
  86. p = strndup(str, n);
  87. #else
  88. p = xmalloc(n + 1);
  89. #endif
  90. if (!p)
  91. die_out_of_memory();
  92. #ifndef HAVE_STRNDUP
  93. strncpy(p, str, n);
  94. p[n] = '\0';
  95. #endif
  96. return p;
  97. }