bug18240.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* Test integer wraparound in hcreate.
  2. Copyright (C) 2016-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <limits.h>
  17. #include <search.h>
  18. #include <stdbool.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <sys/resource.h>
  22. static void
  23. test_size (size_t size)
  24. {
  25. int res = hcreate (size);
  26. if (res == 0)
  27. {
  28. if (errno == ENOMEM)
  29. return;
  30. printf ("error: hcreate (%zu): %m\n", size);
  31. exit (1);
  32. }
  33. char *keys[100];
  34. for (int i = 0; i < 100; ++i)
  35. {
  36. if (asprintf (keys + i, "%d", i) < 0)
  37. {
  38. printf ("error: asprintf: %m\n");
  39. exit (1);
  40. }
  41. ENTRY e = { keys[i], (char *) "value" };
  42. if (hsearch (e, ENTER) == NULL)
  43. {
  44. printf ("error: hsearch (\"%s\"): %m\n", keys[i]);
  45. exit (1);
  46. }
  47. }
  48. hdestroy ();
  49. for (int i = 0; i < 100; ++i)
  50. free (keys[i]);
  51. }
  52. static int
  53. do_test (void)
  54. {
  55. /* Limit the size of the process, so that memory allocation will
  56. fail without impacting the entire system. */
  57. {
  58. struct rlimit limit;
  59. if (getrlimit (RLIMIT_AS, &limit) != 0)
  60. {
  61. printf ("getrlimit (RLIMIT_AS) failed: %m\n");
  62. return 1;
  63. }
  64. long target = 100 * 1024 * 1024;
  65. if (limit.rlim_cur == RLIM_INFINITY || limit.rlim_cur > target)
  66. {
  67. limit.rlim_cur = target;
  68. if (setrlimit (RLIMIT_AS, &limit) != 0)
  69. {
  70. printf ("setrlimit (RLIMIT_AS) failed: %m\n");
  71. return 1;
  72. }
  73. }
  74. }
  75. test_size (500);
  76. test_size (-1);
  77. test_size (-3);
  78. test_size (INT_MAX - 2);
  79. test_size (INT_MAX - 1);
  80. test_size (INT_MAX);
  81. test_size (((unsigned) INT_MAX) + 1);
  82. test_size (UINT_MAX - 2);
  83. test_size (UINT_MAX - 1);
  84. test_size (UINT_MAX);
  85. return 0;
  86. }
  87. #define TEST_FUNCTION do_test ()
  88. #include "../test-skeleton.c"