globalAllocator.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include "globalAllocator.h"
  2. #include <malloc.h>
  3. #include <pikaAllocator/freeListAllocator.h>
  4. #include <fstream>
  5. #include <logs/assert.h>
  6. void *DefaultAllocator(size_t size)
  7. {
  8. return malloc(size);
  9. }
  10. void DefaultFree(void *ptr)
  11. {
  12. free(ptr);
  13. }
  14. void *DisabeledAllocator(size_t size)
  15. {
  16. return 0;
  17. }
  18. void DisabeledFree(void *ptr)
  19. {
  20. (void)ptr;
  21. }
  22. pika::memory::FreeListAllocator *currentCustomAllocator = {};
  23. void *CustomAllocator(size_t size)
  24. {
  25. return currentCustomAllocator->allocate(size);
  26. }
  27. void CustomFree(void *ptr)
  28. {
  29. currentCustomAllocator->free(ptr);
  30. }
  31. void* (*GlobalAllocateFunction)(size_t) = DefaultAllocator;
  32. void (*GlobalFree)(void *) = DefaultFree;
  33. namespace pika
  34. {
  35. namespace memory
  36. {
  37. int pushed = 0;
  38. void setGlobalAllocatorToStandard()
  39. {
  40. PIKA_PERMA_ASSERT(!pushed, "Can't edit allocators while you pushed custom allocators to standard");
  41. GlobalAllocateFunction = DefaultAllocator;
  42. GlobalFree = DefaultFree;
  43. }
  44. void dissableAllocators()
  45. {
  46. PIKA_PERMA_ASSERT(!pushed, "Can't edit allocators while you pushed custom allocators to standard");
  47. GlobalAllocateFunction = DisabeledAllocator;
  48. GlobalFree = DisabeledFree;
  49. }
  50. void setGlobalAllocator(pika::memory::FreeListAllocator *allocator)
  51. {
  52. PIKA_PERMA_ASSERT(!pushed, "Can't edit allocators while you pushed custom allocators to standard");
  53. currentCustomAllocator = allocator;
  54. GlobalAllocateFunction = CustomAllocator;
  55. GlobalFree = CustomFree;
  56. }
  57. void pushCustomAllocatorsToStandard()
  58. {
  59. pushed++;
  60. GlobalAllocateFunction = DefaultAllocator;
  61. GlobalFree = DefaultFree;
  62. }
  63. //can be pushed and popped only once
  64. void popCustomAllocatorsToStandard()
  65. {
  66. pushed--;
  67. PIKA_PERMA_ASSERT(pushed>=0, "pop underflow on popCustomAllocatorsToStandard");
  68. GlobalAllocateFunction = CustomAllocator;
  69. GlobalFree = CustomFree;
  70. }
  71. }
  72. }
  73. void *operator new (size_t count)
  74. {
  75. return GlobalAllocateFunction(count);
  76. }
  77. void *operator new[](size_t count)
  78. {
  79. return GlobalAllocateFunction(count);
  80. }
  81. void operator delete (void *ptr)
  82. {
  83. GlobalFree(ptr);
  84. }
  85. void operator delete[](void *ptr)
  86. {
  87. GlobalFree(ptr);
  88. }