Swift package for mimalloc, built from the sources in this repository. Requires Swift 6.2 or later, on Linux or macOS.
Add the product to an executable target:
dependencies: [
.package(url: "https://github.com/microsoft/mimalloc", from: "3.7.2"),
],
targets: [
.executableTarget(
name: "MyServer",
dependencies: [.product(name: "mimalloc", package: "mimalloc")]
),
]The default Override trait replaces malloc, free and C++ new and delete for the whole process, so the Swift runtime, Foundation and C libraries all allocate from mimalloc. Depend on the product only from the executable: a dynamic library that depends on it links a second copy.
The C API is available with import Cmimalloc; see the API documentation.
Override(default): replacemallocprocess-wide.Secure,SecureChecked,SecureBasic:MI_SECURE4, 2 and 1.Debug: assertions (MI_DEBUG=2);DebugInDebugonly in debug builds.LocalDynamicTLS: for mimalloc inside adlopened library.NoTHP: no transparent huge pages by default on Linux.OptArch: architecture specific optimizations, as-DMI_OPT_ARCH=ON. On Linux these follow the build machine's architecture, so do not use it when cross-compiling.MTE,PAC: memory tagging and pointer authentication, required at runtime (aarch64 Linux and macOS).
.package(url: "https://github.com/microsoft/mimalloc", from: "3.7.2", traits: ["Override", "SecureBasic"]),Other defines go through MIMALLOC_DEFINES, e.g. MIMALLOC_DEFINES="MI_GUARDED=1" swift build.
The package does not support Windows (as a static library cannot override malloc there within Swift).
Instead, use the dynamic override with mimalloc.dll:
-
Build the DLL from the root of this repository:
cmake -B outandcmake --build out --config Release(see also CMake with Visual Studio). This putsmimalloc.dll, its import librarymimalloc.dll.lib, andmimalloc-redirect.dll(mimalloc-redirect-arm64.dllon arm64) inout/Release. -
Link the executable with
mimalloc.dll.lib, and includemi_versionso the linker keeps the import:.executableTarget( name: "MyServer", linkerSettings: [ .linkedLibrary("mimalloc.dll", .when(platforms: [.windows])), .unsafeFlags(["-LC:/path/to/mimalloc/out/Release", "-Xlinker", "/include:mi_version"], .when(platforms: [.windows])), ] ),
-
Copy
mimalloc.dlland the redirect DLL next toMyServer.exe. Run withMIMALLOC_VERBOSE=1to check that mimalloc is redirected.
Optionally, use minject --inplace MyServer.exe (in bin) to move mimalloc.dll to the front of the
import table so it also intercepts allocations made while other DLLs load; minject can also inject mimalloc.dll
into an executable that is not linked with it.