Skip to content

Commit f4d69aa

Browse files
committed
Merge branch 'dev3' into dev3-hbatch
2 parents 06ba367 + ed10d4d commit f4d69aa

19 files changed

Lines changed: 300 additions & 148 deletions

File tree

‎.github/workflows/test.yaml‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,47 @@ jobs:
508508
- name: Single threaded
509509
run: sh .github/ci/cmake-test.sh single-wasm Release
510510

511+
# WASI: build with wasi-sdk (with CMake and directly from `src/static.c`) and run with wasmtime
512+
wasi:
513+
name: wasi
514+
runs-on: ubuntu-latest
515+
env:
516+
WASI_SDK_URL: https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-34/wasi-sdk-34.0-x86_64-linux.tar.gz
517+
WASI_SDK_SHA256: b761e3a0721dbae9c09a0059e5fdb2bf917d1b4a8a7b430fb3b5aafb0984b2c4
518+
WASMTIME_URL: https://github.com/bytecodealliance/wasmtime/releases/download/v51.0.0/wasmtime-v51.0.0-x86_64-linux.tar.xz
519+
WASMTIME_SHA256: a18020674fac4107f329bc9ed720ea9c88e4b30a61e8a527787bcce051123d32
520+
steps:
521+
- name: Checkout repository
522+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
523+
with:
524+
persist-credentials: false
525+
526+
- name: Setup
527+
run: |
528+
curl -sSfL -o wasi-sdk.tar.gz "$WASI_SDK_URL"
529+
echo "$WASI_SDK_SHA256 wasi-sdk.tar.gz" | sha256sum -c
530+
mkdir -p "$RUNNER_TEMP/wasi-sdk" && tar xzf wasi-sdk.tar.gz -C "$RUNNER_TEMP/wasi-sdk" --strip-components=1
531+
curl -sSfL -o wasmtime.tar.xz "$WASMTIME_URL"
532+
echo "$WASMTIME_SHA256 wasmtime.tar.xz" | sha256sum -c
533+
mkdir -p "$RUNNER_TEMP/wasmtime" && tar xJf wasmtime.tar.xz -C "$RUNNER_TEMP/wasmtime" --strip-components=1
534+
echo "CI_CMAKE_ARGS=-DCMAKE_TOOLCHAIN_FILE=$RUNNER_TEMP/wasi-sdk/share/cmake/wasi-sdk-p1.cmake -DWASI_SDK_PREFIX=$RUNNER_TEMP/wasi-sdk -DCMAKE_CROSSCOMPILING_EMULATOR=$RUNNER_TEMP/wasmtime/wasmtime;-S;inherit-env=y -DMI_BUILD_SHARED=OFF" >> "$GITHUB_ENV"
535+
536+
- name: Release
537+
run: sh .github/ci/cmake-test.sh release-wasi Release
538+
539+
- name: Debug
540+
run: sh .github/ci/cmake-test.sh debug-wasi Debug -DMI_DEBUG=FULL
541+
542+
- name: Release, Static
543+
run: |
544+
"$RUNNER_TEMP/wasi-sdk/bin/clang" --sysroot="$RUNNER_TEMP/wasi-sdk/share/wasi-sysroot" -O2 -Iinclude src/static.c test/main.c -o main.wasm
545+
"$RUNNER_TEMP/wasmtime/wasmtime" main.wasm
546+
547+
- name: Debug, Static
548+
run: |
549+
"$RUNNER_TEMP/wasi-sdk/bin/clang" --sysroot="$RUNNER_TEMP/wasi-sdk/share/wasi-sysroot" -O0 -g -DMI_DEBUG=3 -Iinclude src/static.c test/main.c -o main-debug.wasm
550+
"$RUNNER_TEMP/wasmtime/wasmtime" main-debug.wasm
551+
511552
# MSYS2
512553
mingw:
513554
name: mingw-${{ matrix.target }}

‎CMakeLists.txt‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -944,7 +944,11 @@ else()
944944
if(MI_LIB_RT)
945945
list(APPEND mi_libraries "${MI_LIB_RT}")
946946
endif()
947-
find_link_library("atomic" MI_LIB_ATOMIC)
947+
if(MI_USE_LIBATOMIC)
948+
find_link_library("atomic" MI_LIB_ATOMIC)
949+
else()
950+
find_libatomic_if_needed("${MI_OPT_ARCH_FLAGS}" MI_LIB_ATOMIC)
951+
endif()
948952
if(MI_LIB_ATOMIC)
949953
list(APPEND mi_libraries "${MI_LIB_ATOMIC}")
950954
endif()
@@ -1316,6 +1320,9 @@ if (MI_BUILD_TESTS)
13161320
if((TEST_NAME STREQUAL "arena" OR TEST_NAME STREQUAL "bitmap" OR TEST_NAME STREQUAL "secure") AND (NOT MI_BUILD_STATIC OR MI_DEBUG_TSAN))
13171321
continue()
13181322
endif()
1323+
if(CMAKE_SYSTEM_NAME STREQUAL "WASI" AND TEST_NAME MATCHES "^stress")
1324+
continue() # multi-threaded tests are not supported on WASI
1325+
endif()
13191326
add_executable(mimalloc-test-${TEST_NAME} test/test-${TEST_NAME}.c)
13201327
mi_test_sign(mimalloc-test-${TEST_NAME})
13211328
target_compile_definitions(mimalloc-test-${TEST_NAME} PRIVATE ${mi_defines})
@@ -1352,7 +1359,7 @@ if (MI_BUILD_TESTS)
13521359
endforeach()
13531360

13541361
# static override test
1355-
if(MI_BUILD_OBJECT AND MI_OVERRIDE AND NOT (MI_CYGWIN OR (MI_TRACK STREQUAL "ASAN") OR MI_DEBUG_TSAN OR MI_DEBUG_UBSAN))
1362+
if(MI_BUILD_OBJECT AND MI_OVERRIDE AND NOT (MI_CYGWIN OR CMAKE_SYSTEM_NAME STREQUAL "WASI" OR (MI_TRACK STREQUAL "ASAN") OR MI_DEBUG_TSAN OR MI_DEBUG_UBSAN))
13561363
add_executable(mimalloc-test-stress-static test/test-stress.c)
13571364
mi_test_sign(mimalloc-test-stress-static)
13581365
target_compile_definitions(mimalloc-test-stress-static PRIVATE ${mi_defines} "USE_STD_MALLOC=1")

‎cmake/util.cmake‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,45 @@ function(check_big_endian outvar)
6262
check_c_source_runs("int main(void) { const unsigned int n = 1; return *(const unsigned char*)&n; }" ${outvar})
6363
endfunction()
6464

65+
# determine if `libatomic` is needed for 64-bit and pointer-sized atomics (on some 32-bit platforms);
66+
# sets `outvar` to the library to link with (or empty if not needed or not found) (issue #634)
67+
function(find_libatomic_if_needed cflags outvar)
68+
set(${outvar} "" PARENT_SCOPE)
69+
set(src "
70+
#include <stdatomic.h>
71+
#include <stdint.h>
72+
static _Atomic(int64_t) x64;
73+
static _Atomic(uintptr_t) xp;
74+
int main(void) {
75+
volatile int64_t v64 = 1; volatile uintptr_t vp = 1;
76+
int64_t e64 = atomic_load_explicit(&x64, memory_order_acquire);
77+
uintptr_t ep = atomic_load_explicit(&xp, memory_order_acquire);
78+
atomic_store_explicit(&x64, v64, memory_order_release);
79+
atomic_fetch_add_explicit(&x64, v64, memory_order_relaxed);
80+
atomic_compare_exchange_strong(&x64, &e64, v64);
81+
atomic_exchange(&xp, vp);
82+
atomic_compare_exchange_weak(&xp, &ep, vp);
83+
return (int)atomic_fetch_add_explicit(&xp, vp, memory_order_acq_rel);
84+
}")
85+
cmake_push_check_state(RESET)
86+
string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${cflags}")
87+
check_c_source_compiles("${src}" mi_has_builtin_atomics)
88+
if(NOT mi_has_builtin_atomics)
89+
find_link_library("atomic" libatomic)
90+
if(libatomic)
91+
set(CMAKE_REQUIRED_LIBRARIES ${libatomic})
92+
check_c_source_compiles("${src}" mi_has_libatomic_atomics)
93+
if(mi_has_libatomic_atomics)
94+
set(${outvar} ${libatomic} PARENT_SCOPE)
95+
endif()
96+
endif()
97+
if(NOT mi_has_libatomic_atomics)
98+
message(WARNING "Unable to link 64-bit atomic operations (with or without libatomic)")
99+
endif()
100+
endif()
101+
cmake_pop_check_state()
102+
endfunction()
103+
65104
# we prefer -l<lib> test over `find_library` as sometimes core libraries
66105
# like `libatomic` are not on the system path (see issue #898)
67106
function(find_link_library libname outlibname)

‎contrib/rust/src/allocator.rs‎

Lines changed: 41 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ terms of the MIT license. A copy of the license can be found in the file
55
"LICENSE" at the root of this distribution.
66
-----------------------------------------------------------------------------*/
77
use crate::heap::realloc_in;
8-
use crate::{free_sized, realloc_aligned, sys, Heap, MiMalloc, MAX_ALIGN_SIZE};
8+
use crate::{free_sized, malloc_aligned_size, realloc_aligned, sys, Heap, MiMalloc};
99
use core::alloc::{AllocError, Allocator, GlobalAlloc, Layout};
10-
use core::mem::size_of;
11-
use core::ptr::NonNull;
10+
use core::ptr::{self, NonNull};
1211

1312
#[inline(always)]
1413
fn block(ptr: *mut u8, size: usize) -> Result<NonNull<[u8]>, AllocError> {
@@ -135,70 +134,56 @@ unsafe impl Allocator for &Heap {
135134
}
136135
}
137136

138-
/// As [`MiMalloc`] but `allocate` returns the full usable size by requesting `good_size` bytes.
137+
/// As [`MiMalloc`] but returns the full usable size of the allocated block (using the `mi_u*` functions).
139138
/// This can be useful for vector or buffer allocations to maximise the usable memory and reduce reallocations.
140139
#[derive(Clone, Copy, Debug, Default)]
141140
pub struct MiMallocExcess;
142141

143-
// As `mi_good_size` for sizes up to `MI_SMALL_SIZE_MAX` (in words, see `mi_bin`); a mismatch only wastes space as we allocate the returned size.
144-
// (If the size classes ever change, we catch this in the tests where we verify `small_good_wsize` against `mi_good_size`.)
145142
#[inline(always)]
146-
pub(crate) const fn small_good_wsize(size: usize) -> usize {
147-
const ALIGN_WSIZE: usize = MAX_ALIGN_SIZE / size_of::<usize>();
148-
let wsize = crate::wsize_from_size(size);
149-
if wsize <= 1 {
150-
1
151-
} else if size <= 16 {
152-
(wsize + 1) & !1
153-
} else if size <= 64 {
154-
(wsize + ALIGN_WSIZE - 1) & !(ALIGN_WSIZE - 1)
155-
} else {
156-
// 4 size classes per power of two
157-
let w = wsize - 1;
158-
let shift = (usize::BITS - 1 - w.leading_zeros()) - 2;
159-
((w >> shift) + 1) << shift
160-
}
161-
}
162-
163-
#[inline(always)]
164-
fn small_alloc(layout: Layout, zero: bool) -> Option<Result<NonNull<[u8]>, AllocError>> {
165-
if layout.align() > MAX_ALIGN_SIZE || layout.size() > sys::MI_SMALL_SIZE_MAX {
166-
return None;
167-
}
168-
let wsize = small_good_wsize(layout.size());
143+
unsafe fn urealloc(ptr: *mut u8, new: Layout) -> (*mut u8, usize) {
144+
let mut usable = 0;
169145
let p = unsafe {
170-
if zero {
171-
sys::mi_wzalloc_small(wsize)
172-
} else {
173-
sys::mi_wmalloc_small(wsize)
146+
match malloc_aligned_size(new.size(), new.align()) {
147+
Some(size) => sys::mi_urealloc(ptr.cast(), size, ptr::null_mut(), &mut usable),
148+
None => sys::mi_urealloc_aligned(
149+
ptr.cast(),
150+
new.size(),
151+
new.align(),
152+
ptr::null_mut(),
153+
&mut usable,
154+
),
174155
}
175156
};
176-
Some(block(p.cast(), wsize * size_of::<usize>()))
177-
}
178-
179-
#[inline(always)]
180-
fn good_layout(layout: Layout) -> Layout {
181-
let size = crate::good_size(layout.size());
182-
unsafe { Layout::from_size_align_unchecked(size, layout.align()) }
157+
(p.cast(), usable)
183158
}
184159

185160
unsafe impl Allocator for MiMallocExcess {
186161
#[inline]
187162
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
188-
if let Some(r) = small_alloc(layout, false) {
189-
return r;
190-
}
191-
let layout = good_layout(layout);
192-
block(unsafe { MiMalloc.alloc(layout) }, layout.size())
163+
let (size, align) = (layout.size(), layout.align());
164+
let mut usable = 0;
165+
let p = unsafe {
166+
if let Some(size) = malloc_aligned_size(size, align) {
167+
sys::mi_umalloc(size, &mut usable)
168+
} else {
169+
sys::mi_umalloc_aligned(size, align, &mut usable)
170+
}
171+
};
172+
block(p.cast(), usable)
193173
}
194174

195175
#[inline]
196176
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
197-
if let Some(r) = small_alloc(layout, true) {
198-
return r;
199-
}
200-
let layout = good_layout(layout);
201-
block(unsafe { MiMalloc.alloc_zeroed(layout) }, layout.size())
177+
let (size, align) = (layout.size(), layout.align());
178+
let mut usable = 0;
179+
let p = unsafe {
180+
if let Some(size) = malloc_aligned_size(size, align) {
181+
sys::mi_uzalloc(size, &mut usable)
182+
} else {
183+
sys::mi_uzalloc_aligned(size, align, &mut usable)
184+
}
185+
};
186+
block(p.cast(), usable)
202187
}
203188

204189
#[inline]
@@ -213,11 +198,8 @@ unsafe impl Allocator for MiMallocExcess {
213198
_old: Layout,
214199
new: Layout,
215200
) -> Result<NonNull<[u8]>, AllocError> {
216-
let size = crate::good_size(new.size());
217-
block(
218-
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
219-
size,
220-
)
201+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
202+
block(p, usable)
221203
}
222204

223205
#[inline]
@@ -227,9 +209,8 @@ unsafe impl Allocator for MiMallocExcess {
227209
old: Layout,
228210
new: Layout,
229211
) -> Result<NonNull<[u8]>, AllocError> {
230-
let size = crate::good_size(new.size());
231-
let p = unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) };
232-
block(unsafe { zero_tail(p, old.size(), size) }, size)
212+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
213+
block(unsafe { zero_tail(p, old.size(), usable) }, usable)
233214
}
234215

235216
#[inline]
@@ -239,10 +220,7 @@ unsafe impl Allocator for MiMallocExcess {
239220
_old: Layout,
240221
new: Layout,
241222
) -> Result<NonNull<[u8]>, AllocError> {
242-
let size = crate::good_size(new.size());
243-
block(
244-
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
245-
size,
246-
)
223+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
224+
block(p, usable)
247225
}
248226
}

‎contrib/rust/src/heap.rs‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ This is free software; you can redistribute it and/or modify it under the
44
terms of the MIT license. A copy of the license can be found in the file
55
"LICENSE" at the root of this distribution.
66
-----------------------------------------------------------------------------*/
7-
use crate::{free_sized, is_malloc_aligned, sys, Arena, MiString};
7+
use crate::{free_sized, malloc_aligned_size, sys, Arena, MiString};
88
use core::alloc::Layout;
99
use core::ptr::{self, NonNull};
1010

@@ -50,14 +50,14 @@ impl Heap {
5050
/// Allocate a block for `layout`; returns null when out of memory.
5151
#[inline]
5252
pub fn alloc(&self, layout: Layout) -> *mut u8 {
53-
let (heap, size) = (self.as_ptr(), layout.size());
53+
let heap = self.as_ptr();
5454
unsafe {
55-
if !is_malloc_aligned(size, layout.align()) {
56-
sys::mi_heap_malloc_aligned(heap, size, layout.align())
57-
} else if size <= sys::MI_SMALL_SIZE_MAX {
58-
sys::mi_heap_malloc_small(heap, size)
59-
} else {
60-
sys::mi_heap_malloc(heap, size)
55+
match malloc_aligned_size(layout.size(), layout.align()) {
56+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
57+
sys::mi_heap_malloc_small(heap, size)
58+
}
59+
Some(size) => sys::mi_heap_malloc(heap, size),
60+
None => sys::mi_heap_malloc_aligned(heap, layout.size(), layout.align()),
6161
}
6262
}
6363
.cast()
@@ -66,14 +66,14 @@ impl Heap {
6666
/// Allocate a zero-initialized block for `layout`; returns null when out of memory.
6767
#[inline]
6868
pub fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
69-
let (heap, size) = (self.as_ptr(), layout.size());
69+
let heap = self.as_ptr();
7070
unsafe {
71-
if !is_malloc_aligned(size, layout.align()) {
72-
sys::mi_heap_zalloc_aligned(heap, size, layout.align())
73-
} else if size <= sys::MI_SMALL_SIZE_MAX {
74-
sys::mi_heap_zalloc_small(heap, size)
75-
} else {
76-
sys::mi_heap_zalloc(heap, size)
71+
match malloc_aligned_size(layout.size(), layout.align()) {
72+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
73+
sys::mi_heap_zalloc_small(heap, size)
74+
}
75+
Some(size) => sys::mi_heap_zalloc(heap, size),
76+
None => sys::mi_heap_zalloc_aligned(heap, layout.size(), layout.align()),
7777
}
7878
}
7979
.cast()
@@ -137,10 +137,9 @@ pub(crate) unsafe fn realloc_in(
137137
new_size: usize,
138138
) -> *mut u8 {
139139
unsafe {
140-
if is_malloc_aligned(new_size, align) {
141-
sys::mi_heap_realloc(heap, ptr.cast(), new_size)
142-
} else {
143-
sys::mi_heap_realloc_aligned(heap, ptr.cast(), new_size, align)
140+
match malloc_aligned_size(new_size, align) {
141+
Some(size) => sys::mi_heap_realloc(heap, ptr.cast(), size),
142+
None => sys::mi_heap_realloc_aligned(heap, ptr.cast(), new_size, align),
144143
}
145144
}
146145
.cast()

0 commit comments

Comments
 (0)