mimalloc-internal.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. /* ----------------------------------------------------------------------------
  2. Copyright (c) 2018-2021, Microsoft Research, Daan Leijen
  3. This is free software; you can redistribute it and/or modify it under the
  4. terms of the MIT license. A copy of the license can be found in the file
  5. "LICENSE" at the root of this distribution.
  6. -----------------------------------------------------------------------------*/
  7. #pragma once
  8. #ifndef MIMALLOC_INTERNAL_H
  9. #define MIMALLOC_INTERNAL_H
  10. #include "mimalloc-types.h"
  11. #if (MI_DEBUG>0)
  12. #define mi_trace_message(...) _mi_trace_message(__VA_ARGS__)
  13. #else
  14. #define mi_trace_message(...)
  15. #endif
  16. #define MI_CACHE_LINE 64
  17. #if defined(_MSC_VER)
  18. #pragma warning(disable:4127) // suppress constant conditional warning (due to MI_SECURE paths)
  19. #define mi_decl_noinline __declspec(noinline)
  20. #define mi_decl_thread __declspec(thread)
  21. #define mi_decl_cache_align __declspec(align(MI_CACHE_LINE))
  22. #elif (defined(__GNUC__) && (__GNUC__>=3)) // includes clang and icc
  23. #define mi_decl_noinline __attribute__((noinline))
  24. #define mi_decl_thread __thread
  25. #define mi_decl_cache_align __attribute__((aligned(MI_CACHE_LINE)))
  26. #else
  27. #define mi_decl_noinline
  28. #define mi_decl_thread __thread // hope for the best :-)
  29. #define mi_decl_cache_align
  30. #endif
  31. // "options.c"
  32. void _mi_fputs(mi_output_fun* out, void* arg, const char* prefix, const char* message);
  33. void _mi_fprintf(mi_output_fun* out, void* arg, const char* fmt, ...);
  34. void _mi_warning_message(const char* fmt, ...);
  35. void _mi_verbose_message(const char* fmt, ...);
  36. void _mi_trace_message(const char* fmt, ...);
  37. void _mi_options_init(void);
  38. void _mi_error_message(int err, const char* fmt, ...);
  39. // random.c
  40. void _mi_random_init(mi_random_ctx_t* ctx);
  41. void _mi_random_split(mi_random_ctx_t* ctx, mi_random_ctx_t* new_ctx);
  42. uintptr_t _mi_random_next(mi_random_ctx_t* ctx);
  43. uintptr_t _mi_heap_random_next(mi_heap_t* heap);
  44. uintptr_t _os_random_weak(uintptr_t extra_seed);
  45. static inline uintptr_t _mi_random_shuffle(uintptr_t x);
  46. // init.c
  47. extern mi_decl_cache_align mi_stats_t _mi_stats_main;
  48. extern mi_decl_cache_align const mi_page_t _mi_page_empty;
  49. bool _mi_is_main_thread(void);
  50. bool _mi_preloading(); // true while the C runtime is not ready
  51. // os.c
  52. size_t _mi_os_page_size(void);
  53. void _mi_os_init(void); // called from process init
  54. void* _mi_os_alloc(size_t size, mi_stats_t* stats); // to allocate thread local data
  55. void _mi_os_free(void* p, size_t size, mi_stats_t* stats); // to free thread local data
  56. size_t _mi_os_good_alloc_size(size_t size);
  57. // memory.c
  58. void* _mi_mem_alloc_aligned(size_t size, size_t alignment, bool* commit, bool* large, bool* is_pinned, bool* is_zero, size_t* id, mi_os_tld_t* tld);
  59. void _mi_mem_free(void* p, size_t size, size_t id, bool fully_committed, bool any_reset, mi_os_tld_t* tld);
  60. bool _mi_mem_reset(void* p, size_t size, mi_os_tld_t* tld);
  61. bool _mi_mem_unreset(void* p, size_t size, bool* is_zero, mi_os_tld_t* tld);
  62. bool _mi_mem_commit(void* p, size_t size, bool* is_zero, mi_os_tld_t* tld);
  63. bool _mi_mem_protect(void* addr, size_t size);
  64. bool _mi_mem_unprotect(void* addr, size_t size);
  65. void _mi_mem_collect(mi_os_tld_t* tld);
  66. // "segment.c"
  67. mi_page_t* _mi_segment_page_alloc(mi_heap_t* heap, size_t block_wsize, mi_segments_tld_t* tld, mi_os_tld_t* os_tld);
  68. void _mi_segment_page_free(mi_page_t* page, bool force, mi_segments_tld_t* tld);
  69. void _mi_segment_page_abandon(mi_page_t* page, mi_segments_tld_t* tld);
  70. uint8_t* _mi_segment_page_start(const mi_segment_t* segment, const mi_page_t* page, size_t block_size, size_t* page_size, size_t* pre_size); // page start for any page
  71. void _mi_segment_huge_page_free(mi_segment_t* segment, mi_page_t* page, mi_block_t* block);
  72. void _mi_segment_thread_collect(mi_segments_tld_t* tld);
  73. void _mi_abandoned_reclaim_all(mi_heap_t* heap, mi_segments_tld_t* tld);
  74. void _mi_abandoned_await_readers(void);
  75. // "page.c"
  76. void* _mi_malloc_generic(mi_heap_t* heap, size_t size) mi_attr_noexcept mi_attr_malloc;
  77. void _mi_page_retire(mi_page_t* page); // free the page if there are no other pages with many free blocks
  78. void _mi_page_unfull(mi_page_t* page);
  79. void _mi_page_free(mi_page_t* page, mi_page_queue_t* pq, bool force); // free the page
  80. void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq); // abandon the page, to be picked up by another thread...
  81. void _mi_heap_delayed_free(mi_heap_t* heap);
  82. void _mi_heap_collect_retired(mi_heap_t* heap, bool force);
  83. void _mi_page_use_delayed_free(mi_page_t* page, mi_delayed_t delay, bool override_never);
  84. size_t _mi_page_queue_append(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_queue_t* append);
  85. void _mi_deferred_free(mi_heap_t* heap, bool force);
  86. void _mi_page_free_collect(mi_page_t* page,bool force);
  87. void _mi_page_reclaim(mi_heap_t* heap, mi_page_t* page); // callback from segments
  88. size_t _mi_bin_size(uint8_t bin); // for stats
  89. uint8_t _mi_bin(size_t size); // for stats
  90. // "heap.c"
  91. void _mi_heap_destroy_pages(mi_heap_t* heap);
  92. void _mi_heap_collect_abandon(mi_heap_t* heap);
  93. void _mi_heap_set_default_direct(mi_heap_t* heap);
  94. // "stats.c"
  95. void _mi_stats_done(mi_stats_t* stats);
  96. mi_msecs_t _mi_clock_now(void);
  97. mi_msecs_t _mi_clock_end(mi_msecs_t start);
  98. mi_msecs_t _mi_clock_start(void);
  99. // "alloc.c"
  100. void* _mi_page_malloc(mi_heap_t* heap, mi_page_t* page, size_t size) mi_attr_noexcept; // called from `_mi_malloc_generic`
  101. void* _mi_heap_malloc_zero(mi_heap_t* heap, size_t size, bool zero);
  102. void* _mi_heap_realloc_zero(mi_heap_t* heap, void* p, size_t newsize, bool zero);
  103. mi_block_t* _mi_page_ptr_unalign(const mi_segment_t* segment, const mi_page_t* page, const void* p);
  104. bool _mi_free_delayed_block(mi_block_t* block);
  105. void _mi_block_zero_init(const mi_page_t* page, void* p, size_t size);
  106. #if MI_DEBUG>1
  107. bool _mi_page_is_valid(mi_page_t* page);
  108. #endif
  109. // ------------------------------------------------------
  110. // Branches
  111. // ------------------------------------------------------
  112. #if defined(__GNUC__) || defined(__clang__)
  113. #define mi_unlikely(x) __builtin_expect((x),0)
  114. #define mi_likely(x) __builtin_expect((x),1)
  115. #else
  116. #define mi_unlikely(x) (x)
  117. #define mi_likely(x) (x)
  118. #endif
  119. #ifndef __has_builtin
  120. #define __has_builtin(x) 0
  121. #endif
  122. /* -----------------------------------------------------------
  123. Error codes passed to `_mi_fatal_error`
  124. All are recoverable but EFAULT is a serious error and aborts by default in secure mode.
  125. For portability define undefined error codes using common Unix codes:
  126. <https://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html>
  127. ----------------------------------------------------------- */
  128. #include <errno.h>
  129. #ifndef EAGAIN // double free
  130. #define EAGAIN (11)
  131. #endif
  132. #ifndef ENOMEM // out of memory
  133. #define ENOMEM (12)
  134. #endif
  135. #ifndef EFAULT // corrupted free-list or meta-data
  136. #define EFAULT (14)
  137. #endif
  138. #ifndef EINVAL // trying to free an invalid pointer
  139. #define EINVAL (22)
  140. #endif
  141. #ifndef EOVERFLOW // count*size overflow
  142. #define EOVERFLOW (75)
  143. #endif
  144. /* -----------------------------------------------------------
  145. Inlined definitions
  146. ----------------------------------------------------------- */
  147. #define UNUSED(x) (void)(x)
  148. #if (MI_DEBUG>0)
  149. #define UNUSED_RELEASE(x)
  150. #else
  151. #define UNUSED_RELEASE(x) UNUSED(x)
  152. #endif
  153. #define MI_INIT4(x) x(),x(),x(),x()
  154. #define MI_INIT8(x) MI_INIT4(x),MI_INIT4(x)
  155. #define MI_INIT16(x) MI_INIT8(x),MI_INIT8(x)
  156. #define MI_INIT32(x) MI_INIT16(x),MI_INIT16(x)
  157. #define MI_INIT64(x) MI_INIT32(x),MI_INIT32(x)
  158. #define MI_INIT128(x) MI_INIT64(x),MI_INIT64(x)
  159. #define MI_INIT256(x) MI_INIT128(x),MI_INIT128(x)
  160. // Is `x` a power of two? (0 is considered a power of two)
  161. static inline bool _mi_is_power_of_two(uintptr_t x) {
  162. return ((x & (x - 1)) == 0);
  163. }
  164. // Align upwards
  165. static inline uintptr_t _mi_align_up(uintptr_t sz, size_t alignment) {
  166. mi_assert_internal(alignment != 0);
  167. uintptr_t mask = alignment - 1;
  168. if ((alignment & mask) == 0) { // power of two?
  169. return ((sz + mask) & ~mask);
  170. }
  171. else {
  172. return (((sz + mask)/alignment)*alignment);
  173. }
  174. }
  175. // Divide upwards: `s <= _mi_divide_up(s,d)*d < s+d`.
  176. static inline uintptr_t _mi_divide_up(uintptr_t size, size_t divider) {
  177. mi_assert_internal(divider != 0);
  178. return (divider == 0 ? size : ((size + divider - 1) / divider));
  179. }
  180. // Is memory zero initialized?
  181. static inline bool mi_mem_is_zero(void* p, size_t size) {
  182. for (size_t i = 0; i < size; i++) {
  183. if (((uint8_t*)p)[i] != 0) return false;
  184. }
  185. return true;
  186. }
  187. // Align a byte size to a size in _machine words_,
  188. // i.e. byte size == `wsize*sizeof(void*)`.
  189. static inline size_t _mi_wsize_from_size(size_t size) {
  190. mi_assert_internal(size <= SIZE_MAX - sizeof(uintptr_t));
  191. return (size + sizeof(uintptr_t) - 1) / sizeof(uintptr_t);
  192. }
  193. // Does malloc satisfy the alignment constraints already?
  194. static inline bool mi_malloc_satisfies_alignment(size_t alignment, size_t size) {
  195. return (alignment == sizeof(void*) || (alignment == MI_MAX_ALIGN_SIZE && size > (MI_MAX_ALIGN_SIZE/2)));
  196. }
  197. // Overflow detecting multiply
  198. #if __has_builtin(__builtin_umul_overflow) || __GNUC__ >= 5
  199. #include <limits.h> // UINT_MAX, ULONG_MAX
  200. #if defined(_CLOCK_T) // for Illumos
  201. #undef _CLOCK_T
  202. #endif
  203. static inline bool mi_mul_overflow(size_t count, size_t size, size_t* total) {
  204. #if (SIZE_MAX == UINT_MAX)
  205. return __builtin_umul_overflow(count, size, total);
  206. #elif (SIZE_MAX == ULONG_MAX)
  207. return __builtin_umull_overflow(count, size, total);
  208. #else
  209. return __builtin_umulll_overflow(count, size, total);
  210. #endif
  211. }
  212. #else /* __builtin_umul_overflow is unavailable */
  213. static inline bool mi_mul_overflow(size_t count, size_t size, size_t* total) {
  214. #define MI_MUL_NO_OVERFLOW ((size_t)1 << (4*sizeof(size_t))) // sqrt(SIZE_MAX)
  215. *total = count * size;
  216. return ((size >= MI_MUL_NO_OVERFLOW || count >= MI_MUL_NO_OVERFLOW)
  217. && size > 0 && (SIZE_MAX / size) < count);
  218. }
  219. #endif
  220. // Safe multiply `count*size` into `total`; return `true` on overflow.
  221. static inline bool mi_count_size_overflow(size_t count, size_t size, size_t* total) {
  222. if (count==1) { // quick check for the case where count is one (common for C++ allocators)
  223. *total = size;
  224. return false;
  225. }
  226. else if (mi_unlikely(mi_mul_overflow(count, size, total))) {
  227. _mi_error_message(EOVERFLOW, "allocation request is too large (%zu * %zu bytes)\n", count, size);
  228. *total = SIZE_MAX;
  229. return true;
  230. }
  231. else return false;
  232. }
  233. /* ----------------------------------------------------------------------------------------
  234. The thread local default heap: `_mi_get_default_heap` returns the thread local heap.
  235. On most platforms (Windows, Linux, FreeBSD, NetBSD, etc), this just returns a
  236. __thread local variable (`_mi_heap_default`). With the initial-exec TLS model this ensures
  237. that the storage will always be available (allocated on the thread stacks).
  238. On some platforms though we cannot use that when overriding `malloc` since the underlying
  239. TLS implementation (or the loader) will call itself `malloc` on a first access and recurse.
  240. We try to circumvent this in an efficient way:
  241. - macOSX : we use an unused TLS slot from the OS allocated slots (MI_TLS_SLOT). On OSX, the
  242. loader itself calls `malloc` even before the modules are initialized.
  243. - OpenBSD: we use an unused slot from the pthread block (MI_TLS_PTHREAD_SLOT_OFS).
  244. - DragonFly: the uniqueid use is buggy but kept for reference.
  245. ------------------------------------------------------------------------------------------- */
  246. extern const mi_heap_t _mi_heap_empty; // read-only empty heap, initial value of the thread local default heap
  247. extern bool _mi_process_is_initialized;
  248. mi_heap_t* _mi_heap_main_get(void); // statically allocated main backing heap
  249. #if defined(MI_MALLOC_OVERRIDE)
  250. #if defined(__APPLE__) // macOS
  251. #define MI_TLS_SLOT 89 // seems unused?
  252. // other possible unused ones are 9, 29, __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY4 (94), __PTK_FRAMEWORK_GC_KEY9 (112) and __PTK_FRAMEWORK_OLDGC_KEY9 (89)
  253. // see <https://github.com/rweichler/substrate/blob/master/include/pthread_machdep.h>
  254. #elif defined(__OpenBSD__)
  255. // use end bytes of a name; goes wrong if anyone uses names > 23 characters (ptrhread specifies 16)
  256. // see <https://github.com/openbsd/src/blob/master/lib/libc/include/thread_private.h#L371>
  257. #define MI_TLS_PTHREAD_SLOT_OFS (6*sizeof(int) + 4*sizeof(void*) + 24)
  258. #elif defined(__DragonFly__)
  259. #warning "mimalloc is not working correctly on DragonFly yet."
  260. //#define MI_TLS_PTHREAD_SLOT_OFS (4 + 1*sizeof(void*)) // offset `uniqueid` (also used by gdb?) <https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/lib/libthread_xu/thread/thr_private.h#L458>
  261. #endif
  262. #endif
  263. #if defined(MI_TLS_SLOT)
  264. static inline void* mi_tls_slot(size_t slot) mi_attr_noexcept; // forward declaration
  265. #elif defined(MI_TLS_PTHREAD_SLOT_OFS)
  266. #include <pthread.h>
  267. static inline mi_heap_t** mi_tls_pthread_heap_slot(void) {
  268. pthread_t self = pthread_self();
  269. #if defined(__DragonFly__)
  270. if (self==NULL) {
  271. mi_heap_t* pheap_main = _mi_heap_main_get();
  272. return &pheap_main;
  273. }
  274. #endif
  275. return (mi_heap_t**)((uint8_t*)self + MI_TLS_PTHREAD_SLOT_OFS);
  276. }
  277. #elif defined(MI_TLS_PTHREAD)
  278. #include <pthread.h>
  279. extern pthread_key_t _mi_heap_default_key;
  280. #endif
  281. // Default heap to allocate from (if not using TLS- or pthread slots).
  282. // Do not use this directly but use through `mi_heap_get_default()` (or the unchecked `mi_get_default_heap`).
  283. // This thread local variable is only used when neither MI_TLS_SLOT, MI_TLS_PTHREAD, or MI_TLS_PTHREAD_SLOT_OFS are defined.
  284. // However, on the Apple M1 we do use the address of this variable as the unique thread-id (issue #356).
  285. extern mi_decl_thread mi_heap_t* _mi_heap_default; // default heap to allocate from
  286. static inline mi_heap_t* mi_get_default_heap(void) {
  287. #if defined(MI_TLS_SLOT)
  288. mi_heap_t* heap = (mi_heap_t*)mi_tls_slot(MI_TLS_SLOT);
  289. return (mi_unlikely(heap == NULL) ? (mi_heap_t*)&_mi_heap_empty : heap);
  290. #elif defined(MI_TLS_PTHREAD_SLOT_OFS)
  291. mi_heap_t* heap = *mi_tls_pthread_heap_slot();
  292. return (mi_unlikely(heap == NULL) ? (mi_heap_t*)&_mi_heap_empty : heap);
  293. #elif defined(MI_TLS_PTHREAD)
  294. mi_heap_t* heap = (mi_unlikely(_mi_heap_default_key == (pthread_key_t)(-1)) ? _mi_heap_main_get() : (mi_heap_t*)pthread_getspecific(_mi_heap_default_key));
  295. return (mi_unlikely(heap == NULL) ? (mi_heap_t*)&_mi_heap_empty : heap);
  296. #else
  297. #if defined(MI_TLS_RECURSE_GUARD)
  298. if (mi_unlikely(!_mi_process_is_initialized)) return _mi_heap_main_get();
  299. #endif
  300. return _mi_heap_default;
  301. #endif
  302. }
  303. static inline bool mi_heap_is_default(const mi_heap_t* heap) {
  304. return (heap == mi_get_default_heap());
  305. }
  306. static inline bool mi_heap_is_backing(const mi_heap_t* heap) {
  307. return (heap->tld->heap_backing == heap);
  308. }
  309. static inline bool mi_heap_is_initialized(mi_heap_t* heap) {
  310. mi_assert_internal(heap != NULL);
  311. return (heap != &_mi_heap_empty);
  312. }
  313. static inline uintptr_t _mi_ptr_cookie(const void* p) {
  314. extern mi_heap_t _mi_heap_main;
  315. mi_assert_internal(_mi_heap_main.cookie != 0);
  316. return ((uintptr_t)p ^ _mi_heap_main.cookie);
  317. }
  318. /* -----------------------------------------------------------
  319. Pages
  320. ----------------------------------------------------------- */
  321. static inline mi_page_t* _mi_heap_get_free_small_page(mi_heap_t* heap, size_t size) {
  322. mi_assert_internal(size <= (MI_SMALL_SIZE_MAX + MI_PADDING_SIZE));
  323. const size_t idx = _mi_wsize_from_size(size);
  324. mi_assert_internal(idx < MI_PAGES_DIRECT);
  325. return heap->pages_free_direct[idx];
  326. }
  327. // Get the page belonging to a certain size class
  328. static inline mi_page_t* _mi_get_free_small_page(size_t size) {
  329. return _mi_heap_get_free_small_page(mi_get_default_heap(), size);
  330. }
  331. // Segment that contains the pointer
  332. static inline mi_segment_t* _mi_ptr_segment(const void* p) {
  333. // mi_assert_internal(p != NULL);
  334. return (mi_segment_t*)((uintptr_t)p & ~MI_SEGMENT_MASK);
  335. }
  336. // Segment belonging to a page
  337. static inline mi_segment_t* _mi_page_segment(const mi_page_t* page) {
  338. mi_segment_t* segment = _mi_ptr_segment(page);
  339. mi_assert_internal(segment == NULL || page == &segment->pages[page->segment_idx]);
  340. return segment;
  341. }
  342. // used internally
  343. static inline uintptr_t _mi_segment_page_idx_of(const mi_segment_t* segment, const void* p) {
  344. // if (segment->page_size > MI_SEGMENT_SIZE) return &segment->pages[0]; // huge pages
  345. ptrdiff_t diff = (uint8_t*)p - (uint8_t*)segment;
  346. mi_assert_internal(diff >= 0 && (size_t)diff < MI_SEGMENT_SIZE);
  347. uintptr_t idx = (uintptr_t)diff >> segment->page_shift;
  348. mi_assert_internal(idx < segment->capacity);
  349. mi_assert_internal(segment->page_kind <= MI_PAGE_MEDIUM || idx == 0);
  350. return idx;
  351. }
  352. // Get the page containing the pointer
  353. static inline mi_page_t* _mi_segment_page_of(const mi_segment_t* segment, const void* p) {
  354. uintptr_t idx = _mi_segment_page_idx_of(segment, p);
  355. return &((mi_segment_t*)segment)->pages[idx];
  356. }
  357. // Quick page start for initialized pages
  358. static inline uint8_t* _mi_page_start(const mi_segment_t* segment, const mi_page_t* page, size_t* page_size) {
  359. const size_t bsize = page->xblock_size;
  360. mi_assert_internal(bsize > 0 && (bsize%sizeof(void*)) == 0);
  361. return _mi_segment_page_start(segment, page, bsize, page_size, NULL);
  362. }
  363. // Get the page containing the pointer
  364. static inline mi_page_t* _mi_ptr_page(void* p) {
  365. return _mi_segment_page_of(_mi_ptr_segment(p), p);
  366. }
  367. // Get the block size of a page (special cased for huge objects)
  368. static inline size_t mi_page_block_size(const mi_page_t* page) {
  369. const size_t bsize = page->xblock_size;
  370. mi_assert_internal(bsize > 0);
  371. if (mi_likely(bsize < MI_HUGE_BLOCK_SIZE)) {
  372. return bsize;
  373. }
  374. else {
  375. size_t psize;
  376. _mi_segment_page_start(_mi_page_segment(page), page, bsize, &psize, NULL);
  377. return psize;
  378. }
  379. }
  380. // Get the usable block size of a page without fixed padding.
  381. // This may still include internal padding due to alignment and rounding up size classes.
  382. static inline size_t mi_page_usable_block_size(const mi_page_t* page) {
  383. return mi_page_block_size(page) - MI_PADDING_SIZE;
  384. }
  385. // Thread free access
  386. static inline mi_block_t* mi_page_thread_free(const mi_page_t* page) {
  387. return (mi_block_t*)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free) & ~3);
  388. }
  389. static inline mi_delayed_t mi_page_thread_free_flag(const mi_page_t* page) {
  390. return (mi_delayed_t)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free) & 3);
  391. }
  392. // Heap access
  393. static inline mi_heap_t* mi_page_heap(const mi_page_t* page) {
  394. return (mi_heap_t*)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xheap));
  395. }
  396. static inline void mi_page_set_heap(mi_page_t* page, mi_heap_t* heap) {
  397. mi_assert_internal(mi_page_thread_free_flag(page) != MI_DELAYED_FREEING);
  398. mi_atomic_store_release(&page->xheap,(uintptr_t)heap);
  399. }
  400. // Thread free flag helpers
  401. static inline mi_block_t* mi_tf_block(mi_thread_free_t tf) {
  402. return (mi_block_t*)(tf & ~0x03);
  403. }
  404. static inline mi_delayed_t mi_tf_delayed(mi_thread_free_t tf) {
  405. return (mi_delayed_t)(tf & 0x03);
  406. }
  407. static inline mi_thread_free_t mi_tf_make(mi_block_t* block, mi_delayed_t delayed) {
  408. return (mi_thread_free_t)((uintptr_t)block | (uintptr_t)delayed);
  409. }
  410. static inline mi_thread_free_t mi_tf_set_delayed(mi_thread_free_t tf, mi_delayed_t delayed) {
  411. return mi_tf_make(mi_tf_block(tf),delayed);
  412. }
  413. static inline mi_thread_free_t mi_tf_set_block(mi_thread_free_t tf, mi_block_t* block) {
  414. return mi_tf_make(block, mi_tf_delayed(tf));
  415. }
  416. // are all blocks in a page freed?
  417. // note: needs up-to-date used count, (as the `xthread_free` list may not be empty). see `_mi_page_collect_free`.
  418. static inline bool mi_page_all_free(const mi_page_t* page) {
  419. mi_assert_internal(page != NULL);
  420. return (page->used == 0);
  421. }
  422. // are there any available blocks?
  423. static inline bool mi_page_has_any_available(const mi_page_t* page) {
  424. mi_assert_internal(page != NULL && page->reserved > 0);
  425. return (page->used < page->reserved || (mi_page_thread_free(page) != NULL));
  426. }
  427. // are there immediately available blocks, i.e. blocks available on the free list.
  428. static inline bool mi_page_immediate_available(const mi_page_t* page) {
  429. mi_assert_internal(page != NULL);
  430. return (page->free != NULL);
  431. }
  432. // is more than 7/8th of a page in use?
  433. static inline bool mi_page_mostly_used(const mi_page_t* page) {
  434. if (page==NULL) return true;
  435. uint16_t frac = page->reserved / 8U;
  436. return (page->reserved - page->used <= frac);
  437. }
  438. static inline mi_page_queue_t* mi_page_queue(const mi_heap_t* heap, size_t size) {
  439. return &((mi_heap_t*)heap)->pages[_mi_bin(size)];
  440. }
  441. //-----------------------------------------------------------
  442. // Page flags
  443. //-----------------------------------------------------------
  444. static inline bool mi_page_is_in_full(const mi_page_t* page) {
  445. return page->flags.x.in_full;
  446. }
  447. static inline void mi_page_set_in_full(mi_page_t* page, bool in_full) {
  448. page->flags.x.in_full = in_full;
  449. }
  450. static inline bool mi_page_has_aligned(const mi_page_t* page) {
  451. return page->flags.x.has_aligned;
  452. }
  453. static inline void mi_page_set_has_aligned(mi_page_t* page, bool has_aligned) {
  454. page->flags.x.has_aligned = has_aligned;
  455. }
  456. /* -------------------------------------------------------------------
  457. Encoding/Decoding the free list next pointers
  458. This is to protect against buffer overflow exploits where the
  459. free list is mutated. Many hardened allocators xor the next pointer `p`
  460. with a secret key `k1`, as `p^k1`. This prevents overwriting with known
  461. values but might be still too weak: if the attacker can guess
  462. the pointer `p` this can reveal `k1` (since `p^k1^p == k1`).
  463. Moreover, if multiple blocks can be read as well, the attacker can
  464. xor both as `(p1^k1) ^ (p2^k1) == p1^p2` which may reveal a lot
  465. about the pointers (and subsequently `k1`).
  466. Instead mimalloc uses an extra key `k2` and encodes as `((p^k2)<<<k1)+k1`.
  467. Since these operations are not associative, the above approaches do not
  468. work so well any more even if the `p` can be guesstimated. For example,
  469. for the read case we can subtract two entries to discard the `+k1` term,
  470. but that leads to `((p1^k2)<<<k1) - ((p2^k2)<<<k1)` at best.
  471. We include the left-rotation since xor and addition are otherwise linear
  472. in the lowest bit. Finally, both keys are unique per page which reduces
  473. the re-use of keys by a large factor.
  474. We also pass a separate `null` value to be used as `NULL` or otherwise
  475. `(k2<<<k1)+k1` would appear (too) often as a sentinel value.
  476. ------------------------------------------------------------------- */
  477. static inline bool mi_is_in_same_segment(const void* p, const void* q) {
  478. return (_mi_ptr_segment(p) == _mi_ptr_segment(q));
  479. }
  480. static inline bool mi_is_in_same_page(const void* p, const void* q) {
  481. mi_segment_t* segmentp = _mi_ptr_segment(p);
  482. mi_segment_t* segmentq = _mi_ptr_segment(q);
  483. if (segmentp != segmentq) return false;
  484. uintptr_t idxp = _mi_segment_page_idx_of(segmentp, p);
  485. uintptr_t idxq = _mi_segment_page_idx_of(segmentq, q);
  486. return (idxp == idxq);
  487. }
  488. static inline uintptr_t mi_rotl(uintptr_t x, uintptr_t shift) {
  489. shift %= MI_INTPTR_BITS;
  490. return (shift==0 ? x : ((x << shift) | (x >> (MI_INTPTR_BITS - shift))));
  491. }
  492. static inline uintptr_t mi_rotr(uintptr_t x, uintptr_t shift) {
  493. shift %= MI_INTPTR_BITS;
  494. return (shift==0 ? x : ((x >> shift) | (x << (MI_INTPTR_BITS - shift))));
  495. }
  496. static inline void* mi_ptr_decode(const void* null, const mi_encoded_t x, const uintptr_t* keys) {
  497. void* p = (void*)(mi_rotr(x - keys[0], keys[0]) ^ keys[1]);
  498. return (mi_unlikely(p==null) ? NULL : p);
  499. }
  500. static inline mi_encoded_t mi_ptr_encode(const void* null, const void* p, const uintptr_t* keys) {
  501. uintptr_t x = (uintptr_t)(mi_unlikely(p==NULL) ? null : p);
  502. return mi_rotl(x ^ keys[1], keys[0]) + keys[0];
  503. }
  504. static inline mi_block_t* mi_block_nextx( const void* null, const mi_block_t* block, const uintptr_t* keys ) {
  505. #ifdef MI_ENCODE_FREELIST
  506. return (mi_block_t*)mi_ptr_decode(null, block->next, keys);
  507. #else
  508. UNUSED(keys); UNUSED(null);
  509. return (mi_block_t*)block->next;
  510. #endif
  511. }
  512. static inline void mi_block_set_nextx(const void* null, mi_block_t* block, const mi_block_t* next, const uintptr_t* keys) {
  513. #ifdef MI_ENCODE_FREELIST
  514. block->next = mi_ptr_encode(null, next, keys);
  515. #else
  516. UNUSED(keys); UNUSED(null);
  517. block->next = (mi_encoded_t)next;
  518. #endif
  519. }
  520. static inline mi_block_t* mi_block_next(const mi_page_t* page, const mi_block_t* block) {
  521. #ifdef MI_ENCODE_FREELIST
  522. mi_block_t* next = mi_block_nextx(page,block,page->keys);
  523. // check for free list corruption: is `next` at least in the same page?
  524. // TODO: check if `next` is `page->block_size` aligned?
  525. if (mi_unlikely(next!=NULL && !mi_is_in_same_page(block, next))) {
  526. _mi_error_message(EFAULT, "corrupted free list entry of size %zub at %p: value 0x%zx\n", mi_page_block_size(page), block, (uintptr_t)next);
  527. next = NULL;
  528. }
  529. return next;
  530. #else
  531. UNUSED(page);
  532. return mi_block_nextx(page,block,NULL);
  533. #endif
  534. }
  535. static inline void mi_block_set_next(const mi_page_t* page, mi_block_t* block, const mi_block_t* next) {
  536. #ifdef MI_ENCODE_FREELIST
  537. mi_block_set_nextx(page,block,next, page->keys);
  538. #else
  539. UNUSED(page);
  540. mi_block_set_nextx(page,block,next,NULL);
  541. #endif
  542. }
  543. // -------------------------------------------------------------------
  544. // Fast "random" shuffle
  545. // -------------------------------------------------------------------
  546. static inline uintptr_t _mi_random_shuffle(uintptr_t x) {
  547. if (x==0) { x = 17; } // ensure we don't get stuck in generating zeros
  548. #if (MI_INTPTR_SIZE==8)
  549. // by Sebastiano Vigna, see: <http://xoshiro.di.unimi.it/splitmix64.c>
  550. x ^= x >> 30;
  551. x *= 0xbf58476d1ce4e5b9UL;
  552. x ^= x >> 27;
  553. x *= 0x94d049bb133111ebUL;
  554. x ^= x >> 31;
  555. #elif (MI_INTPTR_SIZE==4)
  556. // by Chris Wellons, see: <https://nullprogram.com/blog/2018/07/31/>
  557. x ^= x >> 16;
  558. x *= 0x7feb352dUL;
  559. x ^= x >> 15;
  560. x *= 0x846ca68bUL;
  561. x ^= x >> 16;
  562. #endif
  563. return x;
  564. }
  565. // -------------------------------------------------------------------
  566. // Optimize numa node access for the common case (= one node)
  567. // -------------------------------------------------------------------
  568. int _mi_os_numa_node_get(mi_os_tld_t* tld);
  569. size_t _mi_os_numa_node_count_get(void);
  570. extern _Atomic(size_t) _mi_numa_node_count;
  571. static inline int _mi_os_numa_node(mi_os_tld_t* tld) {
  572. if (mi_likely(mi_atomic_load_relaxed(&_mi_numa_node_count) == 1)) return 0;
  573. else return _mi_os_numa_node_get(tld);
  574. }
  575. static inline size_t _mi_os_numa_node_count(void) {
  576. const size_t count = mi_atomic_load_relaxed(&_mi_numa_node_count);
  577. if (mi_likely(count>0)) return count;
  578. else return _mi_os_numa_node_count_get();
  579. }
  580. // -------------------------------------------------------------------
  581. // Getting the thread id should be performant as it is called in the
  582. // fast path of `_mi_free` and we specialize for various platforms.
  583. // -------------------------------------------------------------------
  584. #if defined(_WIN32)
  585. #define WIN32_LEAN_AND_MEAN
  586. #include <windows.h>
  587. static inline uintptr_t _mi_thread_id(void) mi_attr_noexcept {
  588. // Windows: works on Intel and ARM in both 32- and 64-bit
  589. return (uintptr_t)NtCurrentTeb();
  590. }
  591. #elif defined(__GNUC__) && \
  592. (defined(__x86_64__) || defined(__i386__) || defined(__arm__) || defined(__aarch64__))
  593. // TLS register on x86 is in the FS or GS register, see: https://akkadia.org/drepper/tls.pdf
  594. static inline void* mi_tls_slot(size_t slot) mi_attr_noexcept {
  595. void* res;
  596. const size_t ofs = (slot*sizeof(void*));
  597. #if defined(__i386__)
  598. __asm__("movl %%gs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // 32-bit always uses GS
  599. #elif defined(__APPLE__) && defined(__x86_64__)
  600. __asm__("movq %%gs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // x86_64 macOSX uses GS
  601. #elif defined(__x86_64__) && (MI_INTPTR_SIZE==4)
  602. __asm__("movl %%fs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // x32 ABI
  603. #elif defined(__x86_64__)
  604. __asm__("movq %%fs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // x86_64 Linux, BSD uses FS
  605. #elif defined(__arm__)
  606. void** tcb; UNUSED(ofs);
  607. __asm__ volatile ("mrc p15, 0, %0, c13, c0, 3\nbic %0, %0, #3" : "=r" (tcb));
  608. res = tcb[slot];
  609. #elif defined(__aarch64__)
  610. void** tcb; UNUSED(ofs);
  611. #if defined(__APPLE__) // M1, issue #343
  612. __asm__ volatile ("mrs %0, tpidrro_el0" : "=r" (tcb));
  613. tcb = (void**)((uintptr_t)tcb & ~0x07UL); // clear lower 3 bits
  614. #else
  615. __asm__ volatile ("mrs %0, tpidr_el0" : "=r" (tcb));
  616. #endif
  617. res = tcb[slot];
  618. #endif
  619. return res;
  620. }
  621. // setting is only used on macOSX for now
  622. static inline void mi_tls_slot_set(size_t slot, void* value) mi_attr_noexcept {
  623. const size_t ofs = (slot*sizeof(void*));
  624. #if defined(__i386__)
  625. __asm__("movl %1,%%gs:%0" : "=m" (*((void**)ofs)) : "rn" (value) : ); // 32-bit always uses GS
  626. #elif defined(__APPLE__) && defined(__x86_64__)
  627. __asm__("movq %1,%%gs:%0" : "=m" (*((void**)ofs)) : "rn" (value) : ); // x86_64 macOSX uses GS
  628. #elif defined(__x86_64__) && (MI_INTPTR_SIZE==4)
  629. __asm__("movl %1,%%fs:%1" : "=m" (*((void**)ofs)) : "rn" (value) : ); // x32 ABI
  630. #elif defined(__x86_64__)
  631. __asm__("movq %1,%%fs:%1" : "=m" (*((void**)ofs)) : "rn" (value) : ); // x86_64 Linux, BSD uses FS
  632. #elif defined(__arm__)
  633. void** tcb; UNUSED(ofs);
  634. __asm__ volatile ("mrc p15, 0, %0, c13, c0, 3\nbic %0, %0, #3" : "=r" (tcb));
  635. tcb[slot] = value;
  636. #elif defined(__aarch64__)
  637. void** tcb; UNUSED(ofs);
  638. #if defined(__APPLE__) // M1, issue #343
  639. __asm__ volatile ("mrs %0, tpidrro_el0" : "=r" (tcb));
  640. tcb = (void**)((uintptr_t)tcb & ~0x07UL); // clear lower 3 bits
  641. #else
  642. __asm__ volatile ("mrs %0, tpidr_el0" : "=r" (tcb));
  643. #endif
  644. tcb[slot] = value;
  645. #endif
  646. }
  647. static inline uintptr_t _mi_thread_id(void) mi_attr_noexcept {
  648. #if defined(__BIONIC__) && (defined(__arm__) || defined(__aarch64__))
  649. // on Android, slot 1 is the thread ID (pointer to pthread internal struct)
  650. return (uintptr_t)mi_tls_slot(1);
  651. #else
  652. // in all our other targets, slot 0 is the pointer to the thread control block
  653. return (uintptr_t)mi_tls_slot(0);
  654. #endif
  655. }
  656. #else
  657. // otherwise use standard C
  658. static inline uintptr_t _mi_thread_id(void) mi_attr_noexcept {
  659. return (uintptr_t)&_mi_heap_default;
  660. }
  661. #endif
  662. // -----------------------------------------------------------------------
  663. // Count bits: trailing or leading zeros (with MI_INTPTR_BITS on all zero)
  664. // -----------------------------------------------------------------------
  665. #if defined(__GNUC__)
  666. #include <limits.h> // LONG_MAX
  667. #define MI_HAVE_FAST_BITSCAN
  668. static inline size_t mi_clz(uintptr_t x) {
  669. if (x==0) return MI_INTPTR_BITS;
  670. #if (INTPTR_MAX == LONG_MAX)
  671. return __builtin_clzl(x);
  672. #else
  673. return __builtin_clzll(x);
  674. #endif
  675. }
  676. static inline size_t mi_ctz(uintptr_t x) {
  677. if (x==0) return MI_INTPTR_BITS;
  678. #if (INTPTR_MAX == LONG_MAX)
  679. return __builtin_ctzl(x);
  680. #else
  681. return __builtin_ctzll(x);
  682. #endif
  683. }
  684. #elif defined(_MSC_VER)
  685. #include <limits.h> // LONG_MAX
  686. #define MI_HAVE_FAST_BITSCAN
  687. static inline size_t mi_clz(uintptr_t x) {
  688. if (x==0) return MI_INTPTR_BITS;
  689. unsigned long idx;
  690. #if (INTPTR_MAX == LONG_MAX)
  691. _BitScanReverse(&idx, x);
  692. #else
  693. _BitScanReverse64(&idx, x);
  694. #endif
  695. return ((MI_INTPTR_BITS - 1) - idx);
  696. }
  697. static inline size_t mi_ctz(uintptr_t x) {
  698. if (x==0) return MI_INTPTR_BITS;
  699. unsigned long idx;
  700. #if (INTPTR_MAX == LONG_MAX)
  701. _BitScanForward(&idx, x);
  702. #else
  703. _BitScanForward64(&idx, x);
  704. #endif
  705. return idx;
  706. }
  707. #else
  708. static inline size_t mi_ctz32(uint32_t x) {
  709. // de Bruijn multiplication, see <http://supertech.csail.mit.edu/papers/debruijn.pdf>
  710. static const unsigned char debruijn[32] = {
  711. 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  712. 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  713. };
  714. if (x==0) return 32;
  715. return debruijn[((x & -(int32_t)x) * 0x077CB531UL) >> 27];
  716. }
  717. static inline size_t mi_clz32(uint32_t x) {
  718. // de Bruijn multiplication, see <http://supertech.csail.mit.edu/papers/debruijn.pdf>
  719. static const uint8_t debruijn[32] = {
  720. 31, 22, 30, 21, 18, 10, 29, 2, 20, 17, 15, 13, 9, 6, 28, 1,
  721. 23, 19, 11, 3, 16, 14, 7, 24, 12, 4, 8, 25, 5, 26, 27, 0
  722. };
  723. if (x==0) return 32;
  724. x |= x >> 1;
  725. x |= x >> 2;
  726. x |= x >> 4;
  727. x |= x >> 8;
  728. x |= x >> 16;
  729. return debruijn[(uint32_t)(x * 0x07C4ACDDUL) >> 27];
  730. }
  731. static inline size_t mi_clz(uintptr_t x) {
  732. if (x==0) return MI_INTPTR_BITS;
  733. #if (MI_INTPTR_BITS <= 32)
  734. return mi_clz32((uint32_t)x);
  735. #else
  736. size_t count = mi_clz32((uint32_t)(x >> 32));
  737. if (count < 32) return count;
  738. return (32 + mi_clz32((uint32_t)x));
  739. #endif
  740. }
  741. static inline size_t mi_ctz(uintptr_t x) {
  742. if (x==0) return MI_INTPTR_BITS;
  743. #if (MI_INTPTR_BITS <= 32)
  744. return mi_ctz32((uint32_t)x);
  745. #else
  746. size_t count = mi_ctz32((uint32_t)x);
  747. if (count < 32) return count;
  748. return (32 + mi_ctz32((uint32_t)(x>>32)));
  749. #endif
  750. }
  751. #endif
  752. // "bit scan reverse": Return index of the highest bit (or MI_INTPTR_BITS if `x` is zero)
  753. static inline size_t mi_bsr(uintptr_t x) {
  754. return (x==0 ? MI_INTPTR_BITS : MI_INTPTR_BITS - 1 - mi_clz(x));
  755. }
  756. // ---------------------------------------------------------------------------------
  757. // Provide our own `_mi_memcpy` for potential performance optimizations.
  758. //
  759. // For now, only on Windows with msvc/clang-cl we optimize to `rep movsb` if
  760. // we happen to run on x86/x64 cpu's that have "fast short rep movsb" (FSRM) support
  761. // (AMD Zen3+ (~2020) or Intel Ice Lake+ (~2017). See also issue #201 and pr #253.
  762. // ---------------------------------------------------------------------------------
  763. #if defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))
  764. #include <intrin.h>
  765. #include <string.h>
  766. extern bool _mi_cpu_has_fsrm;
  767. static inline void _mi_memcpy(void* dst, const void* src, size_t n) {
  768. if (_mi_cpu_has_fsrm) {
  769. __movsb((unsigned char*)dst, (const unsigned char*)src, n);
  770. }
  771. else {
  772. memcpy(dst, src, n); // todo: use noinline?
  773. }
  774. }
  775. #else
  776. #include <string.h>
  777. static inline void _mi_memcpy(void* dst, const void* src, size_t n) {
  778. memcpy(dst, src, n);
  779. }
  780. #endif
  781. // -------------------------------------------------------------------------------
  782. // The `_mi_memcpy_aligned` can be used if the pointers are machine-word aligned
  783. // This is used for example in `mi_realloc`.
  784. // -------------------------------------------------------------------------------
  785. #if (__GNUC__ >= 4) || defined(__clang__)
  786. // On GCC/CLang we provide a hint that the pointers are word aligned.
  787. #include <string.h>
  788. static inline void _mi_memcpy_aligned(void* dst, const void* src, size_t n) {
  789. mi_assert_internal(((uintptr_t)dst % MI_INTPTR_SIZE == 0) && ((uintptr_t)src % MI_INTPTR_SIZE == 0));
  790. void* adst = __builtin_assume_aligned(dst, MI_INTPTR_SIZE);
  791. const void* asrc = __builtin_assume_aligned(src, MI_INTPTR_SIZE);
  792. memcpy(adst, asrc, n);
  793. }
  794. #else
  795. // Default fallback on `_mi_memcpy`
  796. static inline void _mi_memcpy_aligned(void* dst, const void* src, size_t n) {
  797. mi_assert_internal(((uintptr_t)dst % MI_INTPTR_SIZE == 0) && ((uintptr_t)src % MI_INTPTR_SIZE == 0));
  798. _mi_memcpy(dst, src, n);
  799. }
  800. #endif
  801. #endif