mock_allocator.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #pragma once
  6. #include "wasm_export.h"
  7. #include <functional>
  8. template<int MaxAllocCount>
  9. class MockAllocator
  10. {
  11. private:
  12. RuntimeInitArgs init_args;
  13. public:
  14. MockAllocator()
  15. {
  16. memset(&init_args, 0, sizeof(RuntimeInitArgs));
  17. init_args.mem_alloc_type = Alloc_With_Allocator;
  18. init_args.mem_alloc_option.allocator.malloc_func = (void *)my_malloc;
  19. init_args.mem_alloc_option.allocator.realloc_func = (void *)realloc;
  20. init_args.mem_alloc_option.allocator.free_func = (void *)free;
  21. /* Set count to INT32_MIN so the initialization will not fail */
  22. alloc_count = INT32_MIN;
  23. wasm_runtime_full_init(&init_args);
  24. reset_count();
  25. }
  26. ~MockAllocator() { wasm_runtime_destroy(); }
  27. void reset_count() { alloc_count = 0; }
  28. protected:
  29. static int32_t alloc_count;
  30. static void *my_malloc(int32_t size)
  31. {
  32. if (alloc_count >= MaxAllocCount) {
  33. return nullptr;
  34. }
  35. alloc_count++;
  36. return malloc(size);
  37. }
  38. };
  39. template<int MaxAllocCount>
  40. int32_t MockAllocator<MaxAllocCount>::alloc_count = 0;
  41. class DumpAllocUsage : public MockAllocator<INT32_MAX>
  42. {
  43. public:
  44. DumpAllocUsage()
  45. : MockAllocator<INT32_MAX>()
  46. {}
  47. ~DumpAllocUsage()
  48. {
  49. std::cout << "Alloc usage count: " << alloc_count << std::endl;
  50. }
  51. };
  52. template<int AllocRequired>
  53. void
  54. LIMIT_MALLOC_COUNT(std::function<void()> func)
  55. {
  56. {
  57. MockAllocator<AllocRequired> allocator;
  58. func();
  59. }
  60. if (AllocRequired > 1)
  61. LIMIT_MALLOC_COUNT<AllocRequired - 1>(func);
  62. }
  63. template<>
  64. void
  65. LIMIT_MALLOC_COUNT<0>(std::function<void()> func)
  66. {
  67. {
  68. MockAllocator<0> allocator;
  69. func();
  70. }
  71. }