Skip to content

Latest commit

 

History

History
69 lines (52 loc) · 3.04 KB

README.md

File metadata and controls

69 lines (52 loc) · 3.04 KB

mimalloc for Swift

Swift package for mimalloc, built from the sources in this repository. Requires Swift 6.2 or later, on Linux or macOS.

Usage

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.

Traits

  • Override (default): replace malloc process-wide.
  • Secure, SecureChecked, SecureBasic: MI_SECURE 4, 2 and 1.
  • Debug: assertions (MI_DEBUG=2); DebugInDebug only in debug builds.
  • LocalDynamicTLS: for mimalloc inside a dlopened 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.

Windows

The package does not support Windows (as a static library cannot override malloc there within Swift). Instead, use the dynamic override with mimalloc.dll:

  1. Build the DLL from the root of this repository: cmake -B out and cmake --build out --config Release (see also CMake with Visual Studio). This puts mimalloc.dll, its import library mimalloc.dll.lib, and mimalloc-redirect.dll (mimalloc-redirect-arm64.dll on arm64) in out/Release.

  2. Link the executable with mimalloc.dll.lib, and include mi_version so 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])),
        ]
    ),
  3. Copy mimalloc.dll and the redirect DLL next to MyServer.exe. Run with MIMALLOC_VERBOSE=1 to 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.