Memory.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include "il2cpp-config.h"
  2. #if IL2CPP_TARGET_POSIX || IL2CPP_TARGET_N3DS && !RUNTIME_TINY
  3. #include "os/Memory.h"
  4. #include <stdint.h>
  5. #include <stdlib.h>
  6. namespace il2cpp
  7. {
  8. namespace os
  9. {
  10. namespace Memory
  11. {
  12. void* AlignedAlloc(size_t size, size_t alignment)
  13. {
  14. #if IL2CPP_TARGET_ANDROID || IL2CPP_TARGET_PSP2
  15. return memalign(alignment, size);
  16. #else
  17. void* ptr = NULL;
  18. alignment = alignment < sizeof(void*) ? sizeof(void*) : alignment;
  19. posix_memalign(&ptr, alignment, size);
  20. return ptr;
  21. #endif
  22. }
  23. void* AlignedReAlloc(void* memory, size_t newSize, size_t alignment)
  24. {
  25. void* newMemory = realloc(memory, newSize);
  26. // Fast path: realloc returned aligned memory
  27. if ((reinterpret_cast<uintptr_t>(newMemory) & (alignment - 1)) == 0)
  28. return newMemory;
  29. // Slow path: realloc returned non-aligned memory
  30. void* alignedMemory = AlignedAlloc(newSize, alignment);
  31. memcpy(alignedMemory, newMemory, newSize);
  32. free(newMemory);
  33. return alignedMemory;
  34. }
  35. void AlignedFree(void* memory)
  36. {
  37. free(memory);
  38. }
  39. }
  40. }
  41. }
  42. #endif