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.

66 lines
1.5KB

  1. /*
  2. * This file is a part of SMalloc.
  3. * SMalloc is MIT licensed.
  4. * Copyright (c) 2017 Andrey Rys.
  5. */
  6. #include "smalloc_i.h"
  7. static int smalloc_check_bounds(struct smalloc_pool *spool, struct smalloc_hdr *shdr)
  8. {
  9. if (!spool) return 0;
  10. if (CHAR_PTR(shdr) >= CHAR_PTR(spool->pool)
  11. && CHAR_PTR(shdr) <= (CHAR_PTR(spool->pool)+spool->pool_size))
  12. return 1;
  13. return 0;
  14. }
  15. static int smalloc_valid_tag(struct smalloc_hdr *shdr)
  16. {
  17. char *s;
  18. uintptr_t r = smalloc_mktag(shdr);
  19. size_t x;
  20. if (shdr->tag == r) {
  21. s = CHAR_PTR(HEADER_TO_USER(shdr));
  22. s += shdr->usz;
  23. for (x = 0; x < sizeof(struct smalloc_hdr); x += sizeof(uintptr_t)) {
  24. r = smalloc_uinthash(r);
  25. if (memcmp(s+x, &r, sizeof(uintptr_t)) != 0) return 0;
  26. }
  27. s += x; x = 0;
  28. while (x < shdr->rsz - shdr->usz) {
  29. if (s[x] != '\xFF') return 0;
  30. x++;
  31. }
  32. return 1;
  33. }
  34. return 0;
  35. }
  36. static void smalloc_do_crash(struct smalloc_pool *spool, const void *p)
  37. {
  38. char *c = NULL;
  39. *c = 'X';
  40. }
  41. smalloc_ub_handler smalloc_UB = smalloc_do_crash;
  42. void sm_set_ub_handler(smalloc_ub_handler handler)
  43. {
  44. if (!handler) smalloc_UB = smalloc_do_crash;
  45. else smalloc_UB = handler;
  46. }
  47. int smalloc_is_alloc(struct smalloc_pool *spool, struct smalloc_hdr *shdr)
  48. {
  49. if (!smalloc_check_bounds(spool, shdr)) return 0;
  50. if (shdr->rsz == 0) return 0;
  51. if (shdr->rsz > SIZE_MAX) return 0;
  52. if (shdr->usz > SIZE_MAX) return 0;
  53. if (shdr->usz > shdr->rsz) return 0;
  54. if (shdr->rsz % HEADER_SZ) return 0;
  55. if (!smalloc_valid_tag(shdr)) return 0;
  56. return 1;
  57. }