Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/mimalloc/prim/unix/prim.c
Line
Count
Source
1
/* ----------------------------------------------------------------------------
2
Copyright (c) 2018-2025, 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
8
// This file is included in `src/prim/prim.c`
9
10
#ifndef _DEFAULT_SOURCE
11
#define _DEFAULT_SOURCE   // ensure mmap flags and syscall are defined
12
#endif
13
14
#if defined(__sun)
15
// illumos provides new mman.h api when any of these are defined
16
// otherwise the old api based on caddr_t which predates the void pointers one.
17
// stock solaris provides only the former, chose to atomically to discard those
18
// flags only here rather than project wide tough.
19
#undef _XOPEN_SOURCE
20
#undef _POSIX_C_SOURCE
21
#endif
22
23
#include "mimalloc.h"
24
#include "mimalloc/internal.h"
25
#include "mimalloc/prim.h"
26
27
#include <sys/mman.h>  // mmap
28
#include <unistd.h>    // sysconf
29
#include <fcntl.h>     // open, close, read, access
30
#include <stdlib.h>    // getenv, arc4random_buf
31
32
#if defined(__linux__)
33
  #include <features.h>
34
  #include <sys/prctl.h>    // THP disable, PR_SET_VMA
35
  #include <sys/sysinfo.h>  // sysinfo
36
  #if defined(__GLIBC__) && !defined(PR_SET_VMA)
37
  #include <linux/prctl.h>
38
  #endif
39
  #if defined(__GLIBC__)
40
  #include <linux/mman.h>   // linux mmap flags
41
  #else
42
  #include <sys/mman.h>
43
  #endif
44
#elif defined(__APPLE__)
45
  #include <AvailabilityMacros.h>
46
  #include <TargetConditionals.h>
47
  #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX   // see issue #879, used to be (!TARGET_IOS_IPHONE && !TARGET_IOS_SIMULATOR)
48
  #include <mach/vm_statistics.h>    // VM_MAKE_TAG, VM_FLAGS_SUPERPAGE_SIZE_2MB, etc.
49
  #endif
50
  #if !defined(MAC_OS_X_VERSION_10_7)
51
  #define MAC_OS_X_VERSION_10_7   1070
52
  #endif
53
  #include <sys/sysctl.h>
54
#elif defined(__FreeBSD__) || defined(__DragonFly__)
55
  #include <sys/param.h>
56
  #if __FreeBSD_version >= 1200000
57
  #include <sys/cpuset.h>
58
  #include <sys/domainset.h>
59
  #endif
60
  #include <sys/sysctl.h>
61
#endif
62
63
#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__)
64
  #define MI_HAS_SYSCALL_H
65
  #include <sys/syscall.h>
66
#endif
67
68
#if !defined(MADV_DONTNEED) && defined(POSIX_MADV_DONTNEED)  // QNX
69
#define MADV_DONTNEED  POSIX_MADV_DONTNEED
70
#endif
71
#if !defined(MADV_FREE) && defined(POSIX_MADV_FREE)  // QNX
72
#define MADV_FREE  POSIX_MADV_FREE
73
#endif
74
75
37
#define MI_UNIX_LARGE_PAGE_SIZE (2*MI_MiB) // TODO: can we query the OS for this?
76
77
//------------------------------------------------------------------------------------
78
// Use syscalls for some primitives to allow for libraries that override open/read/close etc.
79
// and do allocation themselves; using syscalls prevents recursion when mimalloc is
80
// still initializing (issue #713)
81
// Declare inline to avoid unused function warnings.
82
//------------------------------------------------------------------------------------
83
84
#if defined(MI_HAS_SYSCALL_H) && defined(SYS_open) && defined(SYS_close) && defined(SYS_read) && defined(SYS_access)
85
86
37
static inline int mi_prim_open(const char* fpath, int open_flags) {
87
37
  return syscall(SYS_open,fpath,open_flags,0);
88
37
}
89
37
static inline ssize_t mi_prim_read(int fd, void* buf, size_t bufsize) {
90
37
  return syscall(SYS_read,fd,buf,bufsize);
91
37
}
92
37
static inline int mi_prim_close(int fd) {
93
37
  return syscall(SYS_close,fd);
94
37
}
95
0
static inline int mi_prim_access(const char *fpath, int mode) {
96
0
  return syscall(SYS_access,fpath,mode);
97
0
}
98
99
#else
100
101
static inline int mi_prim_open(const char* fpath, int open_flags) {
102
  return open(fpath,open_flags);
103
}
104
static inline ssize_t mi_prim_read(int fd, void* buf, size_t bufsize) {
105
  return read(fd,buf,bufsize);
106
}
107
static inline int mi_prim_close(int fd) {
108
  return close(fd);
109
}
110
static inline int mi_prim_access(const char *fpath, int mode) {
111
  return access(fpath,mode);
112
}
113
114
#endif
115
116
117
118
//---------------------------------------------
119
// init
120
//---------------------------------------------
121
122
37
static bool unix_detect_overcommit(void) {
123
37
  bool os_overcommit = true;
124
37
  #if defined(__linux__)
125
37
    int fd = mi_prim_open("/proc/sys/vm/overcommit_memory", O_RDONLY);
126
37
    if (fd >= 0) {
127
37
      char buf[32] = {0};  // CPython: zero-initialize to avoid an MSAN report
128
37
      ssize_t nread = mi_prim_read(fd, &buf, sizeof(buf));
129
37
      mi_prim_close(fd);
130
      // <https://www.kernel.org/doc/Documentation/vm/overcommit-accounting>
131
      // 0: heuristic overcommit, 1: always overcommit, 2: never overcommit (ignore NORESERVE)
132
37
      if (nread >= 1) {
133
37
        os_overcommit = (buf[0] == '0' || buf[0] == '1');
134
37
      }
135
37
    }
136
  #elif defined(__FreeBSD__)
137
    int val = 0;
138
    size_t olen = sizeof(val);
139
    if (sysctlbyname("vm.overcommit", &val, &olen, NULL, 0) == 0) {
140
      os_overcommit = (val != 0);
141
    }
142
  #else
143
    // default: overcommit is true
144
  #endif
145
37
  return os_overcommit;
146
37
}
147
148
// try to detect the physical memory dynamically (if possible)
149
37
static void unix_detect_physical_memory( size_t page_size, size_t* physical_memory_in_kib ) {
150
  #if defined(CTL_HW) && (defined(HW_PHYSMEM64) || defined(HW_MEMSIZE))  // freeBSD, macOS
151
    MI_UNUSED(page_size);
152
    int64_t physical_memory = 0;
153
    size_t length = sizeof(int64_t);
154
    #if defined(HW_PHYSMEM64)
155
    int mib[2] = { CTL_HW, HW_PHYSMEM64 };
156
    #else
157
    int mib[2] = { CTL_HW, HW_MEMSIZE };
158
    #endif
159
    const int err = sysctl(mib, 2, &physical_memory, &length, NULL, 0);
160
    if (err==0 && physical_memory > 0) {
161
      const int64_t phys_in_kib = physical_memory / MI_KiB;
162
      if (phys_in_kib > 0 && (uint64_t)phys_in_kib <= SIZE_MAX) {
163
        *physical_memory_in_kib = (size_t)phys_in_kib;
164
      }
165
    }
166
  #elif defined(__linux__)
167
37
    MI_UNUSED(page_size);
168
37
    struct sysinfo info; _mi_memzero_var(info);
169
37
    const int err = sysinfo(&info);
170
37
    if (err==0 && info.mem_unit > 0 && info.totalram <= SIZE_MAX) {
171
37
      if (info.mem_unit==MI_KiB) {
172
0
        *physical_memory_in_kib = (size_t)info.totalram;
173
0
      }
174
37
      else {
175
37
        size_t total = 0;
176
37
        if (!mi_mul_overflow((size_t)info.totalram, (size_t)info.mem_unit, &total)) {
177
37
          *physical_memory_in_kib = (total / MI_KiB);
178
37
        }
179
37
      }
180
37
    }
181
  #elif defined(_SC_PHYS_PAGES)  // do not use by default as it might cause allocation (by using `fopen` to parse /proc/meminfo) (issue #1100)
182
    const long pphys = sysconf(_SC_PHYS_PAGES);
183
    const size_t psize_in_kib = page_size / MI_KiB;
184
    if (psize_in_kib > 0 && pphys > 0 && (unsigned long)pphys <= SIZE_MAX && (size_t)pphys <= (SIZE_MAX/psize_in_kib)) {
185
      *physical_memory_in_kib = (size_t)pphys * psize_in_kib;
186
    }
187
  #endif
188
37
}
189
190
void _mi_prim_mem_init( mi_os_mem_config_t* config )
191
37
{
192
37
  long psize = sysconf(_SC_PAGESIZE);
193
37
  if (psize > 0 && (unsigned long)psize < SIZE_MAX) {
194
37
    config->page_size = (size_t)psize;
195
37
    config->alloc_granularity = (size_t)psize;
196
37
    unix_detect_physical_memory(config->page_size, &config->physical_memory_in_kib);
197
37
  }
198
37
  config->large_page_size = MI_UNIX_LARGE_PAGE_SIZE;
199
37
  config->has_overcommit = unix_detect_overcommit();
200
37
  config->has_partial_free = true;    // mmap can free in parts
201
37
  config->has_virtual_reserve = true; // todo: check if this true for NetBSD?  (for anonymous mmap with PROT_NONE)
202
203
  // disable transparent huge pages for this process?
204
37
  #if (defined(__linux__) || defined(__ANDROID__)) && defined(PR_GET_THP_DISABLE)
205
37
  if (!mi_option_is_enabled(mi_option_allow_thp)) // disable THP if requested through an option
206
0
  {
207
0
    if (prctl(PR_GET_THP_DISABLE, 0, 0, 0, 0) == 0) {   // -1 on error, 1 if already disabled
208
      // Most likely since distros often come with always/madvise settings.
209
      // Disabling only for mimalloc process rather than touching system wide settings
210
0
      (void)prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);
211
0
    }
212
0
  }
213
37
  #endif
214
37
}
215
216
217
//---------------------------------------------
218
// free
219
//---------------------------------------------
220
221
0
int _mi_prim_free(void* addr, size_t size ) {
222
0
  if (size==0) return 0;
223
0
  bool err = (munmap(addr, size) == -1);
224
0
  return (err ? errno : 0);
225
0
}
226
227
228
//---------------------------------------------
229
// mmap
230
//---------------------------------------------
231
232
// return errno on failure
233
0
static int unix_madvise(void* addr, size_t size, int advice) {
234
  #if defined(__sun) || defined(_AIX)
235
  const int res = madvise((caddr_t)addr, size, advice);  // Solaris needs cast (issue #520)
236
  return (res==0 ? 0 : errno);
237
  #elif defined(__QNX__)
238
  return posix_madvise(addr, size, advice);              // posix returns errno
239
  #else
240
0
  const int res = madvise(addr, size, advice);           // linux returns -1 on failure and sets errno
241
0
  return (res==0 ? 0 : errno);
242
0
  #endif
243
0
}
244
245
0
static void* unix_mmap_prim(void* addr, size_t size, int protect_flags, int flags, int fd) {
246
0
  void* p = mmap(addr, size, protect_flags, flags, fd, 0 /* offset */);
247
  #if defined(__linux__) && defined(PR_SET_VMA)
248
  if (p!=MAP_FAILED && p!=NULL) {
249
    prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, p, size, "mimalloc");
250
  }
251
  #endif
252
0
  return p;
253
0
}
254
255
0
static void* unix_mmap_prim_aligned(void* addr, size_t size, size_t try_alignment, int protect_flags, int flags, int fd) {
256
0
  MI_UNUSED(try_alignment);
257
0
  void* p = NULL;
258
  #if defined(MAP_ALIGNED)  // BSD
259
  if (addr == NULL && try_alignment > 1 && (try_alignment % _mi_os_page_size()) == 0) {
260
    size_t n = mi_bsr(try_alignment);
261
    if (((size_t)1 << n) == try_alignment && n >= 12 && n <= 30) {  // alignment is a power of 2 and 4096 <= alignment <= 1GiB
262
      p = unix_mmap_prim(addr, size, protect_flags, flags | MAP_ALIGNED(n), fd);
263
      if (p==MAP_FAILED || !_mi_is_aligned(p,try_alignment)) {
264
        int err = errno;
265
        _mi_trace_message("unable to directly request aligned OS memory (error: %d (0x%x), size: 0x%zx bytes, alignment: 0x%zx, hint address: %p)\n", err, err, size, try_alignment, addr);
266
      }
267
      if (p!=MAP_FAILED) return p;
268
      // fall back to regular mmap
269
    }
270
  }
271
  #elif defined(MAP_ALIGN)  // Solaris
272
  if (addr == NULL && try_alignment > 1 && (try_alignment % _mi_os_page_size()) == 0) {
273
    p = unix_mmap_prim((void*)try_alignment, size, protect_flags, flags | MAP_ALIGN, fd);  // addr parameter is the required alignment
274
    if (p!=MAP_FAILED) return p;
275
    // fall back to regular mmap
276
  }
277
  #endif
278
0
  #if (MI_INTPTR_SIZE >= 8) && !defined(MAP_ALIGNED)
279
  // on 64-bit systems, use the virtual address area after 2TiB for 4MiB aligned allocations
280
0
  if (addr == NULL) {
281
0
    void* hint = _mi_os_get_aligned_hint(try_alignment, size);
282
0
    if (hint != NULL) {
283
0
      p = unix_mmap_prim(hint, size, protect_flags, flags, fd);
284
0
      if (p==MAP_FAILED || !_mi_is_aligned(p,try_alignment)) {
285
        #if MI_TRACK_ENABLED  // asan sometimes does not instrument errno correctly?
286
        int err = 0;
287
        #else
288
0
        int err = errno;
289
0
        #endif
290
0
        _mi_trace_message("unable to directly request hinted aligned OS memory (error: %d (0x%x), size: 0x%zx bytes, alignment: 0x%zx, hint address: %p)\n", err, err, size, try_alignment, hint);
291
0
      }
292
0
      if (p!=MAP_FAILED) return p;
293
      // fall back to regular mmap
294
0
    }
295
0
  }
296
0
  #endif
297
  // regular mmap
298
0
  p = unix_mmap_prim(addr, size, protect_flags, flags, fd);
299
0
  if (p!=MAP_FAILED) return p;
300
  // failed to allocate
301
0
  return NULL;
302
0
}
303
304
0
static int unix_mmap_fd(void) {
305
  #if defined(VM_MAKE_TAG)
306
  // macOS: tracking anonymous page with a specific ID. (All up to 98 are taken officially but LLVM sanitizers had taken 99)
307
  int os_tag = (int)mi_option_get(mi_option_os_tag);
308
  if (os_tag < 100 || os_tag > 255) { os_tag = 254; }
309
  return VM_MAKE_TAG(os_tag);
310
  #else
311
0
  return -1;
312
0
  #endif
313
0
}
314
315
#if defined(MAP_ALIGNED_SUPER) || defined(MAP_HUGETLB) || defined(MAP_HUGE_1GB) || defined(MAP_HUGE_2MB) || defined(VM_FLAGS_SUPERPAGE_SIZE_2MB)
316
#define MI_OS_HAS_HUGE_PAGES  1
317
#endif
318
319
0
static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protect_flags, bool large_only, bool allow_large, bool* is_large) {
320
  #if !defined(MAP_ANONYMOUS)
321
  #define MAP_ANONYMOUS  MAP_ANON
322
  #endif
323
  #if !defined(MAP_NORESERVE)
324
  #define MAP_NORESERVE  0
325
  #endif
326
0
  void* p = NULL;
327
0
  const int fd = unix_mmap_fd();
328
0
  int flags = MAP_PRIVATE | MAP_ANONYMOUS;
329
0
  if (_mi_os_has_overcommit()) {
330
0
    flags |= MAP_NORESERVE;
331
0
  }
332
  #if defined(PROT_MAX)
333
  protect_flags |= PROT_MAX(PROT_READ | PROT_WRITE); // BSD
334
  #endif
335
  // huge page allocation
336
0
  #if MI_OS_HAS_HUGE_PAGES
337
0
  if (allow_large && (large_only || (_mi_os_canuse_large_page(size, try_alignment) && mi_option_is_enabled(mi_option_allow_large_os_pages)))) {
338
0
    static _Atomic(size_t) large_page_try_ok; // = 0;
339
0
    size_t try_ok = mi_atomic_load_acquire(&large_page_try_ok);
340
0
    if (!large_only && try_ok > 0) {
341
      // If the OS is not configured for large OS pages, or the user does not have
342
      // enough permission, the `mmap` will always fail (but it might also fail for other reasons).
343
      // Therefore, once a large page allocation failed, we don't try again for `large_page_try_ok` times
344
      // to avoid too many failing calls to mmap.
345
0
      mi_atomic_cas_strong_acq_rel(&large_page_try_ok, &try_ok, try_ok - 1);
346
0
    }
347
0
    else {
348
0
      int lflags = flags & ~MAP_NORESERVE;  // using NORESERVE on huge pages seems to fail on Linux
349
0
      int lfd = fd;
350
      #ifdef MAP_ALIGNED_SUPER
351
      lflags |= MAP_ALIGNED_SUPER;
352
      #endif
353
0
      #ifdef MAP_HUGETLB
354
0
      lflags |= MAP_HUGETLB;
355
0
      #endif
356
0
      #ifdef MAP_HUGE_1GB
357
0
      static _Atomic(size_t) mi_huge_1gib_pages_unavailable;
358
0
      if (large_only && (size % MI_GiB) == 0 && (mi_atomic_load_relaxed(&mi_huge_1gib_pages_unavailable)==0)) {
359
0
        lflags |= MAP_HUGE_1GB;
360
0
      }
361
0
      else
362
0
      #endif
363
0
      {
364
0
        #ifdef MAP_HUGE_2MB
365
0
        lflags |= MAP_HUGE_2MB;
366
0
        #endif
367
0
      }
368
      #ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB
369
      lfd |= VM_FLAGS_SUPERPAGE_SIZE_2MB;
370
      #endif
371
0
      if (large_only || lflags != flags) {
372
        // try large OS page allocation
373
0
        *is_large = true;
374
0
        p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, lflags, lfd);
375
0
        #ifdef MAP_HUGE_1GB
376
0
        if (p == NULL && (lflags & MAP_HUGE_1GB) == MAP_HUGE_1GB) {
377
0
          mi_atomic_store_relaxed(&mi_huge_1gib_pages_unavailable,1); // don't try huge 1GiB pages again
378
0
          if (large_only) {
379
0
            _mi_warning_message("unable to allocate huge (1GiB) page, trying large (2MiB) pages instead (errno: %i)\n", errno);
380
0
          }
381
0
          lflags = ((lflags & ~MAP_HUGE_1GB) | MAP_HUGE_2MB);
382
0
          p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, lflags, lfd);
383
0
        }
384
0
        #endif
385
0
        if (large_only) return p;
386
0
        if (p == NULL) {
387
0
          mi_atomic_store_release(&large_page_try_ok, (size_t)8);  // on error, don't try again for the next N allocations
388
0
        }
389
0
      }
390
0
    }
391
0
  } // huge pages
392
0
  #endif
393
  // regular allocation
394
0
  if (p == NULL) {
395
0
    *is_large = false;
396
0
    p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, flags, fd);
397
    #if !defined(MI_NO_THP)
398
    if (p != NULL && mi_option_is_enabled(mi_option_allow_thp) && _mi_os_canuse_large_page(size, try_alignment)) {
399
      #if defined(MADV_HUGEPAGE)
400
      // Many Linux systems don't allow MAP_HUGETLB but they support instead
401
      // transparent huge pages (THP). Generally, it is not required to call `madvise` with MADV_HUGE
402
      // though since properly aligned allocations will already use large pages if available
403
      // in that case -- in particular for our large regions (in `memory.c`).
404
      // However, some systems only allow THP if called with explicit `madvise`, so
405
      // when large OS pages are enabled for mimalloc, we call `madvise` anyways.
406
      if (unix_madvise(p, size, MADV_HUGEPAGE) == 0) {
407
        // *is_large = true; // possibly
408
      };
409
      #elif defined(__sun)
410
      struct memcntl_mha cmd = {0};
411
      cmd.mha_pagesize = _mi_os_large_page_size();
412
      cmd.mha_cmd = MHA_MAPSIZE_VA;
413
      if (memcntl((caddr_t)p, size, MC_HAT_ADVISE, (caddr_t)&cmd, 0, 0) == 0) {
414
        // *is_large = true; // possibly
415
      }
416
      #endif
417
    }
418
    #endif
419
0
  }
420
0
  return p;
421
0
}
422
423
// Note: the `try_alignment` is just a hint and the returned pointer is not guaranteed to be aligned.
424
0
int _mi_prim_alloc(void* hint_addr, size_t size, size_t try_alignment, bool commit, bool allow_large, bool* is_large, bool* is_zero, void** addr) {
425
0
  mi_assert_internal(size > 0 && (size % _mi_os_page_size()) == 0);
426
0
  mi_assert_internal(commit || !allow_large);
427
0
  mi_assert_internal(try_alignment > 0);
428
0
  *is_zero = true;
429
0
  int protect_flags = (commit ? (PROT_WRITE | PROT_READ) : PROT_NONE);
430
0
  *addr = unix_mmap(hint_addr, size, try_alignment, protect_flags, false, allow_large, is_large);
431
0
  return (*addr != NULL ? 0 : errno);
432
0
}
433
434
435
//---------------------------------------------
436
// Commit/Reset
437
//---------------------------------------------
438
439
0
static void unix_mprotect_hint(int err) {
440
  #if defined(__linux__) && (MI_SECURE>=5) // guard page around every mimalloc page
441
  if (err == ENOMEM) {
442
    _mi_warning_message("The next warning may be caused by a low memory map limit.\n"
443
                        "  On Linux this is controlled by the vm.max_map_count -- maybe increase it?\n"
444
                        "  For example: sudo sysctl -w vm.max_map_count=262144\n");
445
  }
446
  #else
447
0
  MI_UNUSED(err);
448
0
  #endif
449
0
}
450
451
0
int _mi_prim_commit(void* start, size_t size, bool* is_zero) {
452
  // commit: ensure we can access the area
453
  // note: we may think that *is_zero can be true since the memory
454
  // was either from mmap PROT_NONE, or from decommit MADV_DONTNEED, but
455
  // we sometimes call commit on a range with still partially committed
456
  // memory and `mprotect` does not zero the range.
457
0
  *is_zero = false;
458
0
  int err = mprotect(start, size, (PROT_READ | PROT_WRITE));
459
0
  if (err != 0) {
460
0
    err = errno;
461
0
    unix_mprotect_hint(err);
462
0
  }
463
0
  return err;
464
0
}
465
466
0
int _mi_prim_reuse(void* start, size_t size) {
467
0
  MI_UNUSED(start); MI_UNUSED(size);
468
  #if defined(__APPLE__) && defined(MADV_FREE_REUSE)
469
  return unix_madvise(start, size, MADV_FREE_REUSE);
470
  #endif
471
0
  return 0;
472
0
}
473
474
0
int _mi_prim_decommit(void* start, size_t size, bool* needs_recommit) {
475
0
  int err = 0;
476
  #if defined(__APPLE__) && defined(MADV_FREE_REUSABLE)
477
    // decommit on macOS: use MADV_FREE_REUSABLE as it does immediate rss accounting (issue #1097)
478
    err = unix_madvise(start, size, MADV_FREE_REUSABLE);
479
    if (err) { err = unix_madvise(start, size, MADV_DONTNEED); }
480
  #else
481
    // decommit: use MADV_DONTNEED as it decreases rss immediately (unlike MADV_FREE)
482
0
    err = unix_madvise(start, size, MADV_DONTNEED);
483
0
  #endif
484
0
  #if !MI_DEBUG && MI_SECURE<=2
485
0
    *needs_recommit = false;
486
  #else
487
    *needs_recommit = true;
488
    mprotect(start, size, PROT_NONE);
489
  #endif
490
  /*
491
  // decommit: use mmap with MAP_FIXED and PROT_NONE to discard the existing memory (and reduce rss)
492
  *needs_recommit = true;
493
  const int fd = unix_mmap_fd();
494
  void* p = mmap(start, size, PROT_NONE, (MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE), fd, 0);
495
  if (p != start) { err = errno; }
496
  */
497
0
  return err;
498
0
}
499
500
0
int _mi_prim_reset(void* start, size_t size) {
501
0
  int err = 0;
502
503
  // on macOS can use MADV_FREE_REUSABLE (but we disable this for now as it seems slower)
504
  #if 0 && defined(__APPLE__) && defined(MADV_FREE_REUSABLE)
505
  err = unix_madvise(start, size, MADV_FREE_REUSABLE);
506
  if (err==0) return 0;
507
  // fall through
508
  #endif
509
510
0
  #if defined(MADV_FREE)
511
  // Otherwise, we try to use `MADV_FREE` as that is the fastest. A drawback though is that it
512
  // will not reduce the `rss` stats in tools like `top` even though the memory is available
513
  // to other processes. With the default `MIMALLOC_PURGE_DECOMMITS=1` we ensure that by
514
  // default `MADV_DONTNEED` is used though.
515
0
  static _Atomic(size_t) advice = MI_ATOMIC_VAR_INIT(MADV_FREE);
516
0
  int oadvice = (int)mi_atomic_load_relaxed(&advice);
517
0
  while ((err = unix_madvise(start, size, oadvice)) != 0 && err == EAGAIN) { /* try again */ };
518
0
  if (err == EINVAL && oadvice == MADV_FREE) {
519
    // if MADV_FREE is not supported, fall back to MADV_DONTNEED from now on
520
0
    mi_atomic_store_release(&advice, (size_t)MADV_DONTNEED);
521
0
    err = unix_madvise(start, size, MADV_DONTNEED);
522
0
  }
523
  #else
524
  err = unix_madvise(start, size, MADV_DONTNEED);
525
  #endif
526
0
  return err;
527
0
}
528
529
0
int _mi_prim_protect(void* start, size_t size, bool protect) {
530
0
  int err = mprotect(start, size, protect ? PROT_NONE : (PROT_READ | PROT_WRITE));
531
0
  if (err != 0) { err = errno; }
532
0
  unix_mprotect_hint(err);
533
0
  return err;
534
0
}
535
536
537
538
//---------------------------------------------
539
// Huge page allocation
540
//---------------------------------------------
541
542
#if (MI_INTPTR_SIZE >= 8) && !defined(__HAIKU__) && !defined(__CYGWIN__)
543
544
#ifndef MPOL_PREFERRED
545
0
#define MPOL_PREFERRED 1
546
#endif
547
548
#if defined(MI_HAS_SYSCALL_H) && defined(SYS_mbind)
549
0
static long mi_prim_mbind(void* start, unsigned long len, unsigned long mode, const unsigned long* nmask, unsigned long maxnode, unsigned flags) {
550
0
  return syscall(SYS_mbind, start, len, mode, nmask, maxnode, flags);
551
0
}
552
#else
553
static long mi_prim_mbind(void* start, unsigned long len, unsigned long mode, const unsigned long* nmask, unsigned long maxnode, unsigned flags) {
554
  MI_UNUSED(start); MI_UNUSED(len); MI_UNUSED(mode); MI_UNUSED(nmask); MI_UNUSED(maxnode); MI_UNUSED(flags);
555
  return 0;
556
}
557
#endif
558
559
0
int _mi_prim_alloc_huge_os_pages(void* hint_addr, size_t size, int numa_node, bool* is_zero, void** addr) {
560
0
  bool is_large = true;
561
0
  *is_zero = true;
562
0
  *addr = unix_mmap(hint_addr, size, MI_SEGMENT_SIZE, PROT_READ | PROT_WRITE, true, true, &is_large);
563
0
  if (*addr != NULL && numa_node >= 0 && numa_node < (8*MI_INTPTR_SIZE - 1)) { // at most 63 nodes
564
0
    unsigned long numa_mask = (1UL << numa_node);
565
    // TODO: does `mbind` work correctly for huge OS pages? should we
566
    // use `set_mempolicy` before calling mmap instead?
567
    // see: <https://lkml.org/lkml/2017/2/9/875>
568
0
    long err = mi_prim_mbind(*addr, size, MPOL_PREFERRED, &numa_mask, 8*MI_INTPTR_SIZE, 0);
569
0
    if (err != 0) {
570
0
      err = errno;
571
0
      _mi_warning_message("failed to bind huge (1GiB) pages to numa node %d (error: %ld (0x%lx))\n", numa_node, err, err);
572
0
    }
573
0
  }
574
0
  return (*addr != NULL ? 0 : errno);
575
0
}
576
577
#else
578
579
int _mi_prim_alloc_huge_os_pages(void* hint_addr, size_t size, int numa_node, bool* is_zero, void** addr) {
580
  MI_UNUSED(hint_addr); MI_UNUSED(size); MI_UNUSED(numa_node);
581
  *is_zero = false;
582
  *addr = NULL;
583
  return ENOMEM;
584
}
585
586
#endif
587
588
//---------------------------------------------
589
// NUMA nodes
590
//---------------------------------------------
591
592
#if defined(__linux__)
593
594
0
size_t _mi_prim_numa_node(void) {
595
0
  #if defined(MI_HAS_SYSCALL_H) && defined(SYS_getcpu)
596
0
    unsigned int node = 0;
597
0
    unsigned int ncpu = 0;
598
0
    int err = syscall(SYS_getcpu, &ncpu, &node, NULL);
599
0
    if (err != 0) return 0;
600
0
    return node;
601
  #else
602
    return 0;
603
  #endif
604
0
}
605
606
0
size_t _mi_prim_numa_node_count(void) {
607
0
  char buf[128];
608
0
  unsigned last_found = 0;
609
0
  for(unsigned node = 1; node < 256; node++) {
610
    // enumerate node entries -- todo: it there a more efficient way to do this? (but ensure there is no allocation)
611
0
    _mi_snprintf(buf, 127, "/sys/devices/system/node/node%u", node);
612
0
    if (mi_prim_access(buf,R_OK) != 0) {
613
0
      if (node - last_found > 4) break; // allow some sparseness of nodes but not more than 4
614
0
    }
615
0
    else { last_found = node; }         // highest found node
616
0
  }
617
0
  return last_found + 1;
618
0
}
619
620
#elif defined(__FreeBSD__) && __FreeBSD_version >= 1200000
621
622
size_t _mi_prim_numa_node(void) {
623
  domainset_t dom;
624
  size_t node;
625
  int policy;
626
  if (cpuset_getdomain(CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1, sizeof(dom), &dom, &policy) == -1) return 0ul;
627
  for (node = 0; node < MAXMEMDOM; node++) {
628
    if (DOMAINSET_ISSET(node, &dom)) return node;
629
  }
630
  return 0ul;
631
}
632
633
size_t _mi_prim_numa_node_count(void) {
634
  size_t ndomains = 0;
635
  size_t len = sizeof(ndomains);
636
  if (sysctlbyname("vm.ndomains", &ndomains, &len, NULL, 0) == -1) return 0ul;
637
  return ndomains;
638
}
639
640
#elif defined(__DragonFly__)
641
642
size_t _mi_prim_numa_node(void) {
643
  // TODO: DragonFly does not seem to provide any userland means to get this information.
644
  return 0ul;
645
}
646
647
size_t _mi_prim_numa_node_count(void) {
648
  size_t ncpus = 0, nvirtcoresperphys = 0;
649
  size_t len = sizeof(size_t);
650
  if (sysctlbyname("hw.ncpu", &ncpus, &len, NULL, 0) == -1) return 0ul;
651
  if (sysctlbyname("hw.cpu_topology_ht_ids", &nvirtcoresperphys, &len, NULL, 0) == -1) return 0ul;
652
  return nvirtcoresperphys * ncpus;
653
}
654
655
#else
656
657
size_t _mi_prim_numa_node(void) {
658
  return 0;
659
}
660
661
size_t _mi_prim_numa_node_count(void) {
662
  return 1;
663
}
664
665
#endif
666
667
// ----------------------------------------------------------------
668
// Clock
669
// ----------------------------------------------------------------
670
671
#include <time.h>
672
673
// low resolution timer
674
static mi_msecs_t mi_prim_clock_now_lowres(void) {
675
  const int64_t ticks = (int64_t)clock();
676
  #if !defined(CLOCKS_PER_SEC)
677
    return ticks;
678
  #else
679
    if (CLOCKS_PER_SEC <= 0 || CLOCKS_PER_SEC == 1000) {
680
      return ticks;
681
    }
682
    else if (CLOCKS_PER_SEC > 0 && CLOCKS_PER_SEC < 1000) {
683
      return ticks * (1000 / (mi_msecs_t)CLOCKS_PER_SEC);
684
    }
685
    else {
686
      return ticks / ((mi_msecs_t)CLOCKS_PER_SEC / 1000);
687
    }
688
  #endif
689
}
690
691
111
mi_msecs_t _mi_prim_clock_now(void) {
692
111
  #if defined(CLOCK_REALTIME) || defined(CLOCK_MONOTONIC)
693
111
    #ifdef CLOCK_MONOTONIC
694
111
    const clockid_t clockid = CLOCK_MONOTONIC;
695
    #else
696
    const clockid_t clockid = CLOCK_REALTIME;
697
    #endif
698
111
    struct timespec t;
699
111
    if (clock_gettime(clockid,&t) == 0) {
700
111
      return ((mi_msecs_t)t.tv_sec * 1000) + ((mi_msecs_t)t.tv_nsec / 1000000L);
701
111
    }
702
0
  #endif
703
0
  return mi_prim_clock_now_lowres();
704
111
}
705
706
707
//----------------------------------------------------------------
708
// Process info
709
//----------------------------------------------------------------
710
711
#if defined(__unix__) || defined(__unix) || defined(unix) || defined(__APPLE__) || defined(__HAIKU__)
712
#include <stdio.h>
713
#include <unistd.h>
714
#include <sys/resource.h>
715
716
#if defined(__APPLE__)
717
#include <mach/mach.h>
718
#endif
719
720
#if defined(__HAIKU__)
721
#include <kernel/OS.h>
722
#endif
723
724
0
static mi_msecs_t timeval_secs(const struct timeval* tv) {
725
0
  return ((mi_msecs_t)tv->tv_sec * 1000L) + ((mi_msecs_t)tv->tv_usec / 1000L);
726
0
}
727
728
void _mi_prim_process_info(mi_process_info_t* pinfo)
729
0
{
730
0
  struct rusage rusage;
731
0
  if (getrusage(RUSAGE_SELF, &rusage) == 0) {
732
0
    pinfo->utime = timeval_secs(&rusage.ru_utime);
733
0
    pinfo->stime = timeval_secs(&rusage.ru_stime);
734
0
    #if !defined(__HAIKU__)
735
0
      pinfo->page_faults = rusage.ru_majflt;
736
0
    #endif
737
    #if defined(__APPLE__)
738
      pinfo->peak_rss = rusage.ru_maxrss;         // macos reports in bytes
739
    #else
740
0
      pinfo->peak_rss = rusage.ru_maxrss * 1024;  // Linux/BSD report in KiB
741
0
    #endif
742
0
  }
743
744
  #if defined(__HAIKU__)
745
    // Haiku does not have (yet?) a way to
746
    // get these stats per process
747
    thread_info tid;
748
    if (get_thread_info(find_thread(0), &tid) == B_OK) {
749
      area_info mem;
750
      ssize_t c;
751
      while (get_next_area_info(tid.team, &c, &mem) == B_OK) {
752
        pinfo->peak_rss += mem.ram_size;
753
      }
754
    }
755
    pinfo->page_faults = 0;
756
  #elif defined(__APPLE__)
757
    #ifdef MACH_TASK_BASIC_INFO
758
    struct mach_task_basic_info info;
759
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
760
    if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) == KERN_SUCCESS) {
761
      pinfo->current_rss = (size_t)info.resident_size;
762
    }
763
    #else
764
    struct task_basic_info info;
765
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
766
    if (task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &infoCount) == KERN_SUCCESS) {
767
      pinfo->current_rss = (size_t)info.resident_size;
768
    }
769
    #endif
770
  #endif
771
  // use defaults for commit
772
0
}
773
774
#else
775
776
#ifndef __wasi__
777
// WebAssembly instances are not processes
778
#pragma message("define a way to get process info")
779
#endif
780
781
void _mi_prim_process_info(mi_process_info_t* pinfo)
782
{
783
  // use defaults
784
  MI_UNUSED(pinfo);
785
}
786
787
#endif
788
789
790
//----------------------------------------------------------------
791
// Output
792
//----------------------------------------------------------------
793
794
0
void _mi_prim_out_stderr( const char* msg ) {
795
0
  fputs(msg,stderr);
796
0
}
797
798
799
//----------------------------------------------------------------
800
// Environment
801
//----------------------------------------------------------------
802
803
#if !defined(MI_USE_ENVIRON) || (MI_USE_ENVIRON!=0)
804
// On Posix systemsr use `environ` to access environment variables
805
// even before the C runtime is initialized.
806
#if defined(__APPLE__) && defined(__has_include) && __has_include(<crt_externs.h>)
807
#include <crt_externs.h>
808
static char** mi_get_environ(void) {
809
  return (*_NSGetEnviron());
810
}
811
#else
812
extern char** environ;
813
1.66k
static char** mi_get_environ(void) {
814
1.66k
  return environ;
815
1.66k
}
816
#endif
817
1.66k
int _mi_prim_getenv(const char* name, char* result, size_t result_size) {
818
1.66k
  if (name==NULL) return -1;
819
1.66k
  const size_t len = _mi_strlen(name);
820
1.66k
  if (len == 0) return -1;
821
1.66k
  char** env = mi_get_environ();
822
1.66k
  if (env == NULL) return -1;
823
  // compare up to 10000 entries
824
56.5k
  for (int i = 0; i < 10000 && env[i] != NULL; i++) {
825
54.9k
    const char* s = env[i];
826
54.9k
    if (_mi_strnicmp(name, s, len) == 0 && s[len] == '=') { // case insensitive
827
      // found it
828
0
      if (!_mi_strlcpy(result, s + len + 1, result_size)) return -1;
829
0
      return 1;   // success
830
0
    }
831
54.9k
  }
832
1.66k
  return 0; // not found
833
1.66k
}
834
#else
835
// fallback: use standard C `getenv` but this cannot be used while initializing the C runtime
836
int _mi_prim_getenv(const char* name, char* result, size_t result_size) {
837
  // cannot call getenv() when still initializing the C runtime.
838
  if (_mi_preloading()) return -1;  // error, try again later
839
  const char* s = getenv(name);
840
  if (s == NULL) {
841
    // we check the upper case name too.
842
    char buf[64+1];
843
    size_t len = _mi_strnlen(name,sizeof(buf)-1);
844
    for (size_t i = 0; i < len; i++) {
845
      buf[i] = _mi_toupper(name[i]);
846
    }
847
    buf[len] = 0;
848
    s = getenv(buf);
849
  }
850
  if (s == NULL || _mi_strnlen(s,result_size) >= result_size) return 0; // not found
851
  if (!_mi_strlcpy(result, s, result_size)) return -1;
852
  return 1;  // success
853
}
854
#endif  // !MI_USE_ENVIRON
855
856
857
//----------------------------------------------------------------
858
// Random
859
//----------------------------------------------------------------
860
861
#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_15) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_15)
862
#include <CommonCrypto/CommonCryptoError.h>
863
#include <CommonCrypto/CommonRandom.h>
864
865
bool _mi_prim_random_buf(void* buf, size_t buf_len) {
866
  // We prefer CCRandomGenerateBytes as it returns an error code while arc4random_buf
867
  // may fail silently on macOS. See PR #390, and <https://opensource.apple.com/source/Libc/Libc-1439.40.11/gen/FreeBSD/arc4random.c.auto.html>
868
  return (CCRandomGenerateBytes(buf, buf_len) == kCCSuccess);
869
}
870
871
#elif defined(__ANDROID__) || defined(__DragonFly__) || \
872
      defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
873
      defined(__sun) || \
874
      defined(__CYGWIN__) /* CPython: gh-148461 */ || \
875
      (defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7))
876
877
bool _mi_prim_random_buf(void* buf, size_t buf_len) {
878
  arc4random_buf(buf, buf_len);
879
  return true;
880
}
881
882
#elif defined(__APPLE__) || defined(__linux__) || defined(__HAIKU__)   // also for old apple versions < 10.7 (issue #829)
883
884
#include <sys/types.h>
885
#include <sys/stat.h>
886
#include <errno.h>
887
888
37
bool _mi_prim_random_buf(void* buf, size_t buf_len) {
889
  // Modern Linux provides `getrandom` but different distributions either use `sys/random.h` or `linux/random.h`
890
  // and for the latter the actual `getrandom` call is not always defined.
891
  // (see <https://stackoverflow.com/questions/45237324/why-doesnt-getrandom-compile>)
892
  // We therefore use a syscall directly and fall back dynamically to /dev/urandom when needed.
893
37
  #if defined(MI_HAS_SYSCALL_H) && defined(SYS_getrandom)
894
37
    #ifndef GRND_NONBLOCK
895
37
    #define GRND_NONBLOCK (1)
896
37
    #endif
897
37
    static _Atomic(uintptr_t) no_getrandom; // = 0
898
37
    if (mi_atomic_load_acquire(&no_getrandom)==0) {
899
37
      ssize_t ret = syscall(SYS_getrandom, buf, buf_len, GRND_NONBLOCK);
900
37
      if (ret >= 0) return (buf_len == (size_t)ret);
901
0
      if (errno != ENOSYS) return false;
902
0
      mi_atomic_store_release(&no_getrandom, (uintptr_t)1); // don't call again, and fall back to /dev/urandom
903
0
    }
904
0
  #endif
905
0
  int flags = O_RDONLY;
906
0
  #if defined(O_CLOEXEC)
907
0
  flags |= O_CLOEXEC;
908
0
  #endif
909
0
  int fd = mi_prim_open("/dev/urandom", flags);
910
0
  if (fd < 0) return false;
911
0
  size_t count = 0;
912
0
  while(count < buf_len) {
913
0
    ssize_t ret = mi_prim_read(fd, (char*)buf + count, buf_len - count);
914
0
    if (ret==0) {
915
0
      break;
916
0
    }
917
0
    else if (ret<0) {
918
0
      if (errno!=EAGAIN && errno!=EINTR) break;
919
0
    }
920
0
    else {
921
0
      count += ret;
922
0
    }
923
0
  }
924
0
  mi_prim_close(fd);
925
0
  return (count==buf_len);
926
0
}
927
928
#else
929
930
bool _mi_prim_random_buf(void* buf, size_t buf_len) {
931
  return false;
932
}
933
934
#endif
935
936
937
//----------------------------------------------------------------
938
// Thread init/done
939
//----------------------------------------------------------------
940
941
#if defined(MI_USE_PTHREADS)
942
943
// use pthread local storage keys to detect thread ending
944
// (and used with MI_TLS_PTHREADS for the default heap)
945
pthread_key_t _mi_heap_default_key = (pthread_key_t)(-1);
946
947
0
static void mi_pthread_done(void* value) {
948
0
  if (value!=NULL) {
949
0
    _mi_thread_done((mi_heap_t*)value);
950
0
  }
951
0
}
952
953
37
void _mi_prim_thread_init_auto_done(void) {
954
37
  mi_assert_internal(_mi_heap_default_key == (pthread_key_t)(-1));
955
37
  const int err = pthread_key_create(&_mi_heap_default_key, &mi_pthread_done);
956
37
  if (err!=0) {
957
0
    _mi_error_message(err,"unable to create a pthread thread local key (error %d (0x%x))", err, err);
958
0
    _mi_heap_default_key = (pthread_key_t)(-1);
959
0
  };
960
37
}
961
962
0
void _mi_prim_thread_done_auto_done(void) {
963
0
  if (_mi_heap_default_key != (pthread_key_t)(-1)) {  // do not leak the key, see issue #809
964
0
    pthread_key_delete(_mi_heap_default_key);
965
0
  }
966
0
}
967
968
37
void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {
969
37
  if (_mi_heap_default_key != (pthread_key_t)(-1)) {  // can happen during recursive invocation on freeBSD
970
37
    pthread_setspecific(_mi_heap_default_key, heap);
971
37
  }
972
37
}
973
974
#else
975
976
void _mi_prim_thread_init_auto_done(void) {
977
  // nothing
978
}
979
980
void _mi_prim_thread_done_auto_done(void) {
981
  // nothing
982
}
983
984
void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {
985
  MI_UNUSED(heap);
986
}
987
988
#endif