guardedalloc_overflow_test.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Apache License, Version 2.0 */
  2. #include "testing/testing.h"
  3. #include "MEM_guardedalloc.h"
  4. /* We expect to abort on integer overflow, to prevent possible exploits. */
  5. #ifdef _WIN32
  6. #define ABORT_PREDICATE ::testing::ExitedWithCode(3)
  7. #else
  8. #define ABORT_PREDICATE ::testing::KilledBySignal(SIGABRT)
  9. #endif
  10. namespace {
  11. void MallocArray(size_t len, size_t size)
  12. {
  13. void *mem = MEM_malloc_arrayN(len, size, "MallocArray");
  14. if (mem) {
  15. MEM_freeN(mem);
  16. }
  17. }
  18. void CallocArray(size_t len, size_t size)
  19. {
  20. void *mem = MEM_calloc_arrayN(len, size, "CallocArray");
  21. if (mem) {
  22. MEM_freeN(mem);
  23. }
  24. }
  25. } // namespace
  26. TEST(guardedalloc, LockfreeIntegerOverflow)
  27. {
  28. MallocArray(1, SIZE_MAX);
  29. CallocArray(SIZE_MAX, 1);
  30. MallocArray(SIZE_MAX / 2, 2);
  31. CallocArray(SIZE_MAX / 1234567, 1234567);
  32. EXPECT_EXIT(MallocArray(SIZE_MAX, 2), ABORT_PREDICATE, "");
  33. EXPECT_EXIT(CallocArray(7, SIZE_MAX), ABORT_PREDICATE, "");
  34. EXPECT_EXIT(MallocArray(SIZE_MAX, 12345567), ABORT_PREDICATE, "");
  35. EXPECT_EXIT(CallocArray(SIZE_MAX, SIZE_MAX), ABORT_PREDICATE, "");
  36. }
  37. TEST(guardedalloc, GuardedIntegerOverflow)
  38. {
  39. MEM_use_guarded_allocator();
  40. MallocArray(1, SIZE_MAX);
  41. CallocArray(SIZE_MAX, 1);
  42. MallocArray(SIZE_MAX / 2, 2);
  43. CallocArray(SIZE_MAX / 1234567, 1234567);
  44. EXPECT_EXIT(MallocArray(SIZE_MAX, 2), ABORT_PREDICATE, "");
  45. EXPECT_EXIT(CallocArray(7, SIZE_MAX), ABORT_PREDICATE, "");
  46. EXPECT_EXIT(MallocArray(SIZE_MAX, 12345567), ABORT_PREDICATE, "");
  47. EXPECT_EXIT(CallocArray(SIZE_MAX, SIZE_MAX), ABORT_PREDICATE, "");
  48. }