🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.2 KiB

  1. #include "config.h"
  2. #include "almalloc.h"
  3. #include <cstdlib>
  4. #include <cstring>
  5. #ifdef HAVE_MALLOC_H
  6. #include <malloc.h>
  7. #endif
  8. #ifdef HAVE_WINDOWS_H
  9. #include <windows.h>
  10. #else
  11. #include <unistd.h>
  12. #endif
  13. #ifdef __GNUC__
  14. #define LIKELY(x) __builtin_expect(!!(x), !0)
  15. #define UNLIKELY(x) __builtin_expect(!!(x), 0)
  16. #else
  17. #define LIKELY(x) (!!(x))
  18. #define UNLIKELY(x) (!!(x))
  19. #endif
  20. void *al_malloc(size_t alignment, size_t size)
  21. {
  22. #if defined(HAVE_ALIGNED_ALLOC)
  23. size = (size+(alignment-1))&~(alignment-1);
  24. return aligned_alloc(alignment, size);
  25. #elif defined(HAVE_POSIX_MEMALIGN)
  26. void *ret;
  27. if(posix_memalign(&ret, alignment, size) == 0)
  28. return ret;
  29. return nullptr;
  30. #elif defined(HAVE__ALIGNED_MALLOC)
  31. return _aligned_malloc(size, alignment);
  32. #else
  33. char *ret = static_cast<char*>(malloc(size+alignment));
  34. if(ret != nullptr)
  35. {
  36. *(ret++) = 0x00;
  37. while(((ptrdiff_t)ret&(alignment-1)) != 0)
  38. *(ret++) = 0x55;
  39. }
  40. return ret;
  41. #endif
  42. }
  43. void *al_calloc(size_t alignment, size_t size)
  44. {
  45. void *ret = al_malloc(alignment, size);
  46. if(ret) memset(ret, 0, size);
  47. return ret;
  48. }
  49. void al_free(void *ptr) noexcept
  50. {
  51. #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
  52. free(ptr);
  53. #elif defined(HAVE__ALIGNED_MALLOC)
  54. _aligned_free(ptr);
  55. #else
  56. if(ptr != nullptr)
  57. {
  58. char *finder = static_cast<char*>(ptr);
  59. do {
  60. --finder;
  61. } while(*finder == 0x55);
  62. free(finder);
  63. }
  64. #endif
  65. }
  66. size_t al_get_page_size() noexcept
  67. {
  68. static size_t psize = 0;
  69. if(UNLIKELY(!psize))
  70. {
  71. #ifdef HAVE_SYSCONF
  72. #if defined(_SC_PAGESIZE)
  73. if(!psize) psize = sysconf(_SC_PAGESIZE);
  74. #elif defined(_SC_PAGE_SIZE)
  75. if(!psize) psize = sysconf(_SC_PAGE_SIZE);
  76. #endif
  77. #endif /* HAVE_SYSCONF */
  78. #ifdef _WIN32
  79. if(!psize)
  80. {
  81. SYSTEM_INFO sysinfo{};
  82. GetSystemInfo(&sysinfo);
  83. psize = sysinfo.dwPageSize;
  84. }
  85. #endif
  86. if(!psize) psize = DEF_ALIGN;
  87. }
  88. return psize;
  89. }
  90. int al_is_sane_alignment_allocator() noexcept
  91. {
  92. #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN) || defined(HAVE__ALIGNED_MALLOC)
  93. return 1;
  94. #else
  95. return 0;
  96. #endif
  97. }