tst-aligned_alloc-lib.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Module used for improved aligned_alloc testing.
  2. Copyright (C) 2024-2026 Free Software Foundation, Inc.
  3. Copyright The GNU Toolchain Authors.
  4. This file is part of the GNU C Library.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public License as
  7. published by the Free Software Foundation; either version 2.1 of the
  8. License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; see the file COPYING.LIB. If
  15. not, see <https://www.gnu.org/licenses/>. */
  16. #include <libc-symbols.h>
  17. #include <stdlib.h>
  18. #include <time.h>
  19. extern void *__libc_malloc (size_t size);
  20. extern void *__libc_calloc (size_t n, size_t size);
  21. __thread unsigned int seed = 0;
  22. int aligned_alloc_count = 0;
  23. int libc_malloc_count = 0;
  24. int libc_calloc_count = 0;
  25. static void *
  26. get_random_alloc (size_t size)
  27. {
  28. void *retval;
  29. size_t align;
  30. struct timespec tp;
  31. if (seed == 0)
  32. {
  33. clock_gettime (CLOCK_REALTIME, &tp);
  34. seed = tp.tv_nsec;
  35. }
  36. switch (rand_r (&seed) % 3)
  37. {
  38. case 1:
  39. /* Get a random alignment value. Biased towards the smaller
  40. * values up to 16384. Must be a power of 2. */
  41. align = 1 << rand_r (&seed) % 15;
  42. retval = aligned_alloc (align, size);
  43. aligned_alloc_count++;
  44. break;
  45. case 2:
  46. retval = __libc_calloc (1, size);
  47. libc_calloc_count++;
  48. break;
  49. default:
  50. retval = __libc_malloc (size);
  51. libc_malloc_count++;
  52. break;
  53. }
  54. return retval;
  55. }
  56. void *
  57. __random_malloc (size_t size)
  58. {
  59. return get_random_alloc (size);
  60. }
  61. strong_alias (__random_malloc, malloc)