tst-tcfree4.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Test that malloc tcache catches double free.
  2. Copyright (C) 2025-2026 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. <https://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <error.h>
  17. #include <limits.h>
  18. #include <malloc.h>
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <sys/signal.h>
  23. /* Test for a double free where the size information gets overwritten by a
  24. * terminating null byte. */
  25. static int
  26. do_test (void)
  27. {
  28. /* The payload is exactly 0x19 Bytes long:
  29. * 0x18 bytes 'B' and one terminating null byte
  30. */
  31. const char *payload = "BBBBBBBBBBBBBBBBBBBBBBBB";
  32. char *volatile first_chunk
  33. = malloc (strlen (payload)); // <-- off by one error
  34. char *volatile second_chunk = malloc (0x118);
  35. // free the second chunk the first time now it is in the tcache with tc_idx =
  36. free (second_chunk);
  37. // change the the size of the second_chunk using the terminating null byte if
  38. // the PAYLOAD
  39. strcpy (first_chunk, payload);
  40. // now the second_chunk has a new size
  41. // calling free a second time will not trigger the double free detection
  42. free (second_chunk);
  43. printf ("FAIL: tcache double free not detected\n");
  44. return 1;
  45. }
  46. #define TEST_FUNCTION do_test
  47. #define EXPECTED_SIGNAL SIGABRT
  48. #include <support/test-driver.c>