Coverage Report

Created: 2026-12-01 06:09

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