Memory.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "il2cpp-config.h"
  2. #include "os/Memory.h"
  3. #include "utils/Memory.h"
  4. #include <cstdlib>
  5. namespace il2cpp
  6. {
  7. namespace utils
  8. {
  9. struct MonoMemoryCallbacks
  10. {
  11. int version;
  12. void *(*malloc_func)(size_t size);
  13. void *(*realloc_func)(void *mem, size_t count);
  14. void(*free_func)(void *mem);
  15. void *(*calloc_func)(size_t count, size_t size);
  16. };
  17. extern "C"
  18. {
  19. int32_t mono_set_allocator_vtable(MonoMemoryCallbacks* callbacks);
  20. }
  21. static MonoMemoryCallbacks s_MonoCallbacks =
  22. {
  23. 1, //MONO_ALLOCATOR_VTABLE_VERSION
  24. NULL,
  25. NULL,
  26. NULL,
  27. NULL
  28. };
  29. static Il2CppMemoryCallbacks s_Callbacks =
  30. {
  31. malloc,
  32. os::Memory::AlignedAlloc,
  33. free,
  34. os::Memory::AlignedFree,
  35. calloc,
  36. realloc,
  37. os::Memory::AlignedReAlloc
  38. };
  39. void Memory::SetMemoryCallbacks(Il2CppMemoryCallbacks* callbacks)
  40. {
  41. memcpy(&s_Callbacks, callbacks, sizeof(Il2CppMemoryCallbacks));
  42. #if IL2CPP_MONO_DEBUGGER
  43. // The debugger uses Mono code, so we need to remap the callbacks
  44. // for Mono allocations and frees to the same ones IL2CPP is using.
  45. s_MonoCallbacks.malloc_func = callbacks->malloc_func;
  46. s_MonoCallbacks.realloc_func = callbacks->realloc_func;
  47. s_MonoCallbacks.free_func = callbacks->free_func;
  48. s_MonoCallbacks.calloc_func = callbacks->calloc_func;
  49. int32_t installed = mono_set_allocator_vtable(&s_MonoCallbacks);
  50. IL2CPP_ASSERT(installed != 0);
  51. NO_UNUSED_WARNING(installed);
  52. #endif
  53. }
  54. void* Memory::Malloc(size_t size)
  55. {
  56. return s_Callbacks.malloc_func(size);
  57. }
  58. void* Memory::AlignedMalloc(size_t size, size_t alignment)
  59. {
  60. return s_Callbacks.aligned_malloc_func(size, alignment);
  61. }
  62. void Memory::Free(void* memory)
  63. {
  64. return s_Callbacks.free_func(memory);
  65. }
  66. void Memory::AlignedFree(void* memory)
  67. {
  68. return s_Callbacks.aligned_free_func(memory);
  69. }
  70. void* Memory::Calloc(size_t count, size_t size)
  71. {
  72. return s_Callbacks.calloc_func(count, size);
  73. }
  74. void* Memory::Realloc(void* memory, size_t newSize)
  75. {
  76. return s_Callbacks.realloc_func(memory, newSize);
  77. }
  78. void* Memory::AlignedRealloc(void* memory, size_t newSize, size_t alignment)
  79. {
  80. return s_Callbacks.aligned_realloc_func(memory, newSize, alignment);
  81. }
  82. } /* namespace utils */
  83. } /* namespace il2cpp */