### Install Core snmalloc Headers Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Installs the main snmalloc header files. ```cmake install(FILES src/snmalloc/snmalloc.h;src/snmalloc/snmalloc_core.h;src/snmalloc/snmalloc_front.h DESTINATION include/snmalloc) ``` -------------------------------- ### Fetch and Setup Fuzztest Source: https://github.com/microsoft/snmalloc/blob/main/fuzzing/CMakeLists.txt Declares and makes available the fuzztest library from its Git repository. Ensures fuzzing flags are set up. ```cmake include(FetchContent) FetchContent_Declare( fuzztest GIT_REPOSITORY https://github.com/google/fuzztest.git GIT_TAG 2024-10-28 ) FetchContent_MakeAvailable(fuzztest) enable_testing() fuzztest_setup_fuzzing_flags() ``` -------------------------------- ### Coverage Target Setup Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Configures the coverage target by finding LLVM tools (llvm-profdata, llvm-cov) and checking for test binaries. ```cmake # Coverage target. Generates a unified coverage.profdata + # coverage.json for all test binaries. if (SNMALLOC_COVERAGE AND SNMALLOC_BUILD_TESTING) find_program(LLVM_PROFDATA NAMES llvm-profdata-19 llvm-profdata-15 llvm-profdata) find_program(LLVM_COV NAMES llvm-cov-19 llvm-cov-15 llvm-cov) if (LLVM_PROFDATA STREQUAL "LLVM_PROFDATA-NOTFOUND" OR LLVM_COV STREQUAL "LLVM_COV-NOTFOUND") message(FATAL_ERROR "SNMALLOC_COVERAGE requires llvm-profdata and llvm-cov on PATH.") endif() get_property(_test_binaries GLOBAL PROPERTY SNMALLOC_TEST_BINARIES) if (NOT _test_binaries) message(FATAL_ERROR "SNMALLOC_TEST_BINARIES is empty; nothing to cover.") endif() # Build the -object argument list: first binary positional, rest with ``` -------------------------------- ### Install snmalloc Library and Configuration Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Installs the snmalloc library targets and configuration files. This includes the main library, export configuration, and header files. ```cmake install(TARGETS snmalloc EXPORT snmallocConfig) install(TARGETS EXPORT snmallocConfig DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/snmalloc) install(DIRECTORY src/snmalloc/aal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/backend DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/backend_helpers DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds_aal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds_core DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/global DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/mem DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/mitigations DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/override DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/pal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/stl DESTINATION include/snmalloc) install(FILES src/test/measuretime.h src/test/opt.h src/test/setup.h src/test/usage.h src/test/xoroshiro.h DESTINATION include/snmalloc/test ) install(FILES src/snmalloc/snmalloc.h;src/snmalloc/snmalloc_core.h;src/snmalloc/snmalloc_front.h DESTINATION include/snmalloc) install(EXPORT snmallocConfig FILE snmalloc-config.cmake NAMESPACE snmalloc:: DESTINATION "share/snmalloc" ) ``` -------------------------------- ### Install snmalloc Header Directories Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Installs various snmalloc header directories to the include path. ```cmake install(DIRECTORY src/snmalloc/aal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/backend DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/backend_helpers DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds_aal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/ds_core DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/global DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/mem DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/mitigations DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/override DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/pal DESTINATION include/snmalloc) install(DIRECTORY src/snmalloc/stl DESTINATION include/snmalloc) ``` -------------------------------- ### Install snmalloc Target Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Installs the snmalloc target and its associated configuration files. ```cmake install(TARGETS snmalloc EXPORT snmallocConfig) ``` ```cmake install(TARGETS EXPORT snmallocConfig DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/snmalloc) ``` -------------------------------- ### Install snmalloc Test Headers Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Installs header files for snmalloc testing utilities. ```cmake install(FILES src/test/measuretime.h src/test/opt.h src/test/setup.h src/test/usage.h src/test/xoroshiro.h DESTINATION include/snmalloc/test ) ``` -------------------------------- ### Coverage Target Setup Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Configures the coverage target by finding LLVM tools (llvm-profdata, llvm-cov) and checking if test binaries are available. It requires both tools to be present on the PATH. ```cmake if (SNMALLOC_COVERAGE AND SNMALLOC_BUILD_TESTING) find_program(LLVM_PROFDATA NAMES llvm-profdata-19 llvm-profdata-15 llvm-profdata) find_program(LLVM_COV NAMES llvm-cov-19 llvm-cov-15 llvm-cov) if (LLVM_PROFDATA STREQUAL "LLVM_PROFDATA-NOTFOUND" OR LLVM_COV STREQUAL "LLVM_COV-NOTFOUND") message(FATAL_ERROR "SNMALLOC_COVERAGE requires llvm-profdata and llvm-cov on PATH.") endif() get_property(_test_binaries GLOBAL PROPERTY SNMALLOC_TEST_BINARIES) if (NOT _test_binaries) message(FATAL_ERROR "SNMALLOC_TEST_BINARIES is empty; nothing to cover.") endif() # Build the -object argument list: first binary positional, rest with ``` -------------------------------- ### Platform-Specific Page Size Configuration Source: https://github.com/microsoft/snmalloc/blob/main/docs/PORTING.md Example of how to define `page_size` based on architecture using Aal. This is a compile-time constant. ```cpp static constexpr size_t page_size = Aal::aal_name == PowerPC ? 0x10000 : 0x1000; ``` -------------------------------- ### Install snmalloc Config CMake File Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Installs the snmalloc configuration CMake file for package management. ```cmake install(EXPORT snmallocConfig FILE snmalloc-config.cmake NAMESPACE snmalloc:: DESTINATION "share/snmalloc" ) ``` -------------------------------- ### NetBSD Specific Include and Link Directories Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Configures include and link directories for NetBSD systems, pointing to /usr/pkg/include and /usr/pkg/lib respectively, to accommodate package installations. ```cmake if (CMAKE_SYSTEM_NAME STREQUAL NetBSD) target_include_directories(snmalloc INTERFACE /usr/pkg/include) target_link_directories(snmalloc INTERFACE /usr/pkg/lib) endif() ``` -------------------------------- ### Configure Custom Meta-Data Provider Source: https://github.com/microsoft/snmalloc/blob/main/docs/release/0.7/README.md Example of configuring snmalloc to store a 64-bit counter for each allocation using `ArrayClientMetaDataProvider`. This configuration does not affect underlying alignment or pagemap size. ```cpp using Config = snmalloc::StandardConfigClientMeta< ArrayClientMetaDataProvider>>; ``` -------------------------------- ### Setting Target Include Directories Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Configures the include paths for the snmalloc target, specifying interface include directories for installation and build-time source directories. ```cmake target_include_directories(snmalloc INTERFACE $ $) ``` -------------------------------- ### Ingest Pointer from Client Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Use capptr_from_client() to annotate the raw pointer as AllocWild, then capptr_domesticate() to check for domestication. ```cpp p_wild = capptr_from_client(p_raw) p_tame = capptr_domesticate(state_ptr, p_wild) ``` -------------------------------- ### Free List Implementation Reference Source: https://github.com/microsoft/snmalloc/blob/main/docs/security/FreelistProtection.md This link points to the source code file in the snmalloc repository that contains the implementation of the free lists, including the protection mechanisms described. ```c++ https://github.com/microsoft/snmalloc/blob/main/src/snmalloc/mem/freelist.h ``` -------------------------------- ### Configure Allocation Sizes Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Set minimum allocation size and minimum allocation step size. Both should be powers of 2. ```cmake set(SNMALLOC_MIN_ALLOC_SIZE "" CACHE STRING "Minimum allocation bytes (power of 2)") set(SNMALLOC_MIN_ALLOC_STEP_SIZE "" CACHE STRING "Minimum allocation step (power of 2)") ``` -------------------------------- ### Build snmalloc on UNIX-like platforms with Ninja (RelWithDebInfo) Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Configure and build snmalloc with optimizations and debug information on UNIX-like systems using CMake with the Ninja generator. Requires CMake, Ninja, and Clang 6.0 or later. ```bash mkdir build cd build cmake -G Ninja .. -DCMAKE_BUILD_TYPE=RelWithDebInfo ninja ``` -------------------------------- ### Reveal Pointer to Client Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Use PAL::capptr_to_user_address_control() to convert AllocFull to Alloc, then capptr_reveal() to obtain the underlying T*. ```cpp PAL::capptr_to_user_address_control() capptr_chunk_is_alloc capptr_reveal() ``` -------------------------------- ### Get Slab Metadata - C++ Source: https://github.com/microsoft/snmalloc/blob/main/docs/security/VariableSizedChunks.md Retrieves the SlabMetadata for a given memory address using the chunk map. Assumes address is aligned to chunk boundaries. ```C++ SlabMetadata* get_slab_metadata(address_t addr) { return chunk_map[addr >> CHUNK_BITS].meta; } ``` -------------------------------- ### GWP-ASan Integration Configuration Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Configures integration with GWP-ASan (General Protection Fault Allocator - Address Sanitizer). It checks for required include and library paths and sets up compile definitions and link libraries accordingly. Fatal errors are reported if paths are not provided. ```cmake if (SNMALLOC_ENABLE_GWP_ASAN_INTEGRATION) if (NOT EXISTS ${SNMALLOC_GWP_ASAN_INCLUDE_PATH}) message(FATAL_ERROR "GwpAsan cannot be enabled without setting SNMALLOC_GWP_ASAN_INCLUDE_PATH") endif() if (NOT EXISTS ${SNMALLOC_GWP_ASAN_LIBRARY_PATH}) message(FATAL_ERROR "GwpAsan cannot be enabled without setting SNMALLOC_GWP_ASAN_LIBRARY_PATH") endif() message(STATUS "GwpAsan is enabled: ${SNMALLOC_GWP_ASAN_LIBRARY_PATH}/libclang_rt.gwp_asan-${CMAKE_SYSTEM_PROCESSOR}.a") target_include_directories(snmalloc INTERFACE ${SNMALLOC_GWP_ASAN_INCLUDE_PATH}) target_link_directories(snmalloc INTERFACE ${SNMALLOC_GWP_ASAN_LIBRARY_PATH}) target_compile_definitions(snmalloc INTERFACE -DSNMALLOC_ENABLE_GWP_ASAN_INTEGRATION) target_link_libraries(snmalloc INTERFACE clang_rt.gwp_asan-${CMAKE_SYSTEM_PROCESSOR}) endif() ``` -------------------------------- ### Register QEMU User Static Handler Source: https://github.com/microsoft/snmalloc/blob/main/ci/README.md Registers the QEMU user static handler for building multiarch Docker images on architectures other than the host. This is a prerequisite for multiarch builds. ```bash sudo docker run --rm --privileged multiarch/qemu-user-static:register --reset ``` -------------------------------- ### Build snmalloc on UNIX-like platforms with Ninja (Release) Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Configure and build a release version of snmalloc on UNIX-like systems using CMake with the Ninja generator. Requires CMake, Ninja, and Clang 6.0 or later. ```bash mkdir build cd build cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Release ninja ``` -------------------------------- ### Test Docker Image Locally Source: https://github.com/microsoft/snmalloc/blob/main/ci/README.md Runs a build and test cycle for the current code tree within a previously built Docker image. Mounts the current directory as read-only and specifies build configurations. ```bash docker run --rm -u $(id -u) -v ${PWD}:/opt:ro snmallocciteam/build_${IMG}:latest \ sh -c "cd /tmp; CC=clang-10 CXX=clang++-10 BUILD_TYPE=Debug SNMALLOC_SRC=/opt /opt/ci/scripts/build.sh && (cd build; ninja test)" ``` -------------------------------- ### Preload snmalloc with checks enabled Source: https://github.com/microsoft/snmalloc/blob/main/docs/security/README.md To test snmalloc's hardening features on Elf platforms (like Linux or BSD), build the library and then preload it when running your application. Ensure you replace `[snmalloc_build]` with the actual path to your build directory. ```bash LD_PRELOAD=[snmalloc_build]/libsnmalloc-checks.so ./my_app ``` -------------------------------- ### Provide Dummy CheckLinkerFlag Implementation Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Includes a fallback dummy implementation for CheckLinkerFlag if it's not available, to support older CMake versions. ```cmake include(CheckLinkerFlag OPTIONAL RESULT_VARIABLE CHECK_LINKER_FLAG) if (NOT CHECK_LINKER_FLAG) function(check_linker_flag) endfunction() endif () ``` -------------------------------- ### Enable Coverage Instrumentation Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Enable Clang source-based coverage mapping. Requires Clang or AppleClang compiler. ```cmake if (SNMALLOC_COVERAGE) if (NOT (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang")) message(FATAL_ERROR "SNMALLOC_COVERAGE requires Clang or AppleClang (got ${CMAKE_CXX_COMPILER_ID}). " "Point CMAKE_CXX_COMPILER at clang++ for the coverage build directory.") endif() add_compile_options(-fprofile-instr-generate -fcoverage-mapping) add_link_options(-fprofile-instr-generate -fcoverage-mapping) endif() ``` -------------------------------- ### Configure Page Size Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Set the page size in bytes for memory management. ```cmake set(SNMALLOC_PAGESIZE "" CACHE STRING "Page size in bytes") ``` -------------------------------- ### Optimized Division using Reciprocal Source: https://github.com/microsoft/snmalloc/blob/main/docs/security/GuardedMemcpy.md This demonstrates the mathematical transformation for fast division and modulus operations when the divisor is a constant, using multiplication and bit shifts. ```C++ (x * c) >> n ``` ```C++ x - (((x * c) >> n) * size) ``` -------------------------------- ### Windows Compatibility and VirtualAlloc2 Linking Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Configures Windows-specific settings, including a compatibility flag for Windows 8 and conditionally links against 'mincore' for VirtualAlloc2. ```cmake if (WIN32) set(WIN8COMPAT FALSE CACHE BOOL "Avoid Windows 10 APIs") target_compile_definitions(snmalloc INTERFACE $<$:WINVER=0x0603>) # VirtualAlloc2 is exposed by mincore.lib, not Kernel32.lib (as the # documentation says) target_link_libraries(snmalloc INTERFACE $<$>:mincore>) message(STATUS "snmalloc: Avoiding Windows 10 APIs is ${WIN8COMPAT}") endif() ``` -------------------------------- ### Build snmalloc on UNIX-like platforms with Ninja (Debug) Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Configure and build a debug version of snmalloc on UNIX-like systems using CMake with the Ninja generator. Requires CMake, Ninja, and Clang 6.0 or later. ```bash mkdir build cd build cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Debug ninja ``` -------------------------------- ### Configure Coverage Objects Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Sets up coverage objects for LLVM coverage tool, formatting them for use in shell commands. ```cmake # -object prefix per llvm-cov's CLI. CMake list joined with spaces so # the resulting string can be embedded in `sh -c "..."` commands. set(_cov_objects "") set(_first TRUE) foreach(_b ${_test_binaries}) if (_first) string(APPEND _cov_objects " $" ) set(_first FALSE) else() string(APPEND _cov_objects " -object $" ) endif() endforeach() ``` -------------------------------- ### Create Unverified Capability Pointer Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Wraps a void pointer as a capptr::AllocWild to mark it as unverified. ```cpp capptr_from_client ``` -------------------------------- ### Enable GwpAsan Integration Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Enable GwpAsan as a secondary allocator. Requires setting include and library paths. ```cmake option(SNMALLOC_ENABLE_GWP_ASAN_INTEGRATION "Enable GwpAsan as a secondary allocator" OFF) set(SNMALLOC_GWP_ASAN_INCLUDE_PATH "" CACHE PATH "GwpAsan header directory") set(SNMALLOC_GWP_ASAN_LIBRARY_PATH "" CACHE PATH "GwpAsan library directory") ``` -------------------------------- ### Build snmalloc on Windows with Visual Studio Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Use these CMake commands to configure and build snmalloc on Windows with Visual Studio 2022 for x64 architecture. Multiple build configurations (Debug, Release, RelWithDebInfo) are supported. ```bash mkdir build cd build cmake -G "Visual Studio 17 2022" -A x64 .. cmake --build . --config Debug cmake --build . --config Release cmake --build . --config RelWithDebInfo ``` -------------------------------- ### Build Test Libraries Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Iterates through 'fast' and 'check' flavours to build test libraries, setting SNMALLOC_CHECK_CLIENT definition for the 'check' flavour. ```cmake if (SNMALLOC_BUILD_TESTING) set(FLAVOURS fast;check) foreach(FLAVOUR ${FLAVOURS}) if (${FLAVOUR} STREQUAL "check") set(DEFINES SNMALLOC_CHECK_CLIENT) endif() if (${FLAVOUR} STREQUAL "fast") set(DEFINES " ") endif() build_test_library(${FLAVOUR} ${DEFINES}) make_tests(${FLAVOUR} ${DEFINES}) endforeach() endif() ``` -------------------------------- ### Building Minimal Shared Library Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Compiles a minimal shared library 'snmalloc-minimal' with exceptions disabled and potentially no standard C++ library. ```cmake compile(snmalloc-minimal SHARED ${MALLOC}) target_compile_options(snmalloc-minimal PRIVATE -fno-exceptions) if (SNMALLOC_LINKER_SUPPORT_NOSTDLIBXX AND NOT ${SNMALLOC_CLEANUP} STREQUAL CXX11_DESTRUCTORS) target_compile_options(snmalloc-minimal PRIVATE -fno-exceptions -nostdlib++) endif () ``` -------------------------------- ### Define Coverage Variables Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Sets up variables for coverage reporting, including profile directory, data files, and report paths. ```cmake set(_cov_profile_dir ${CMAKE_BINARY_DIR}/profiles) set(_cov_profdata ${CMAKE_BINARY_DIR}/coverage.profdata) set(_cov_json ${CMAKE_BINARY_DIR}/coverage.json) set(_cov_report ${CMAKE_BINARY_DIR}/coverage.report.txt) set(_cov_pairs_file ${CMAKE_BINARY_DIR}/coverage_tests.tsv) set(_cov_runner ${CMAKE_SOURCE_DIR}/cmake/run_coverage.cmake) ``` -------------------------------- ### Set Static Library Prefix Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Define a prefix for static library functions. Not supported on MSVC if empty. ```cmake set(SNMALLOC_STATIC_LIBRARY_PREFIX "sn_" CACHE STRING "Static library function prefix") ``` -------------------------------- ### In-Process Optimization (IPO) Support Check Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Checks if the compiler supports In-Process Optimization (IPO) when not building a header-only library and SNMALLOC_IPO is enabled. ```cmake if (NOT SNMALLOC_HEADER_ONLY_LIBRARY AND SNMALLOC_IPO) check_ipo_supported(RESULT HAS_IPO) if (HAS_IPO) set(SNMALLOC_COMPILER_SUPPORT_IPO TRUE) endif() endif() ``` -------------------------------- ### Static Library Build Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Compiles a static library target 'snmallocshim-static' with specified source files and sets a compile definition for the static library prefix. ```cmake if (SNMALLOC_STATIC_LIBRARY) compile(snmallocshim-static STATIC ${ALLOC}) target_compile_definitions(snmallocshim-static PRIVATE SNMALLOC_STATIC_LIBRARY_PREFIX=${SNMALLOC_STATIC_LIBRARY_PREFIX}) endif () ``` -------------------------------- ### Configure Coverage Test Pairs Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Builds '\t' pairs for the per-test cache loop used in coverage reporting. ```cmake # Build "\t" pairs for the per-test cache loop. set(_cov_test_pairs "") foreach(_b ${_test_binaries}) string(APPEND _cov_test_pairs "${_b}\t$\n" ) endforeach() ``` -------------------------------- ### Domesticate Capability Pointer Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Allows the backend to test if a capability pointer is sensible according to specific definitions. The input pointer must be Wild, and the output will be Tame but otherwise identical. ```cpp CapPtr capptr_domesticate(LocalState *, CapPtr ptr) ``` -------------------------------- ### New Override Library Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Compiles a static library target 'snmalloc-new-override' using the 'new.cc' source file. ```cmake compile(snmalloc-new-override STATIC ${NEW}) ``` -------------------------------- ### Sattolo's Algorithm for Cyclic Permutation Source: https://github.com/microsoft/snmalloc/blob/main/docs/security/Randomisation.md Implements Sattolo's algorithm using the 'inside-out' method to generate a cyclic permutation. This is used to build all possible free lists with equal probability. Ensure 'random(0, i-1)' provides a uniform distribution for theoretical guarantees, though performance approximations are used in practice. ```C++ object[0].next = &(object[0]); // 1 element cycle for (i = 1; i < n; i++) { auto j = random(0, i-1); // Pick element in cycle // Cyclic list insert of i after j object[i].next = object[j].next; object[j].next = &(object[i]); } auto end_index = random(0,n-1); // Select last element of cycle. auto start = object[end_index].next; // Find start object[end_index].next = nullptr; // Terminate list ``` -------------------------------- ### Partial PAL Implementations Source: https://github.com/microsoft/snmalloc/blob/main/docs/PORTING.md Pre-defined PAL implementations for POSIX-like systems. ```APIDOC ### PALPOSIX Defines a PAL for a POSIX platform using no non-standard features. ### PALBSD Defines a PAL for the common set of BSD extensions to POSIX. ### PALBSD_Aligned Extends `PALBSD` to provide support for aligned allocation from `mmap`, as supported by NetBSD and FreeBSD. Each of these template classes takes the PAL that inherits from it as a template parameter. ``` -------------------------------- ### Enable snmalloc statistics tracking Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Add this CMake feature flag to your command line to enable the tracking of allocation statistics within snmalloc. ```bash -DUSE_SNMALLOC_STATS=ON ``` -------------------------------- ### Linking Backtrace Library for Debug/CI Builds Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Links the 'backtrace' library for debug and CI builds to enable stack trace functionality. ```cmake # In debug and CI builds, link the backtrace library so that we can get stack ``` -------------------------------- ### Configure CMake for snmalloc vcpkg Tests Source: https://github.com/microsoft/snmalloc/blob/main/test/vcpkg-consumer/CMakeLists.txt Sets the minimum CMake version, project name, and enables verbose build output. This configuration is essential for building and testing snmalloc with vcpkg. ```cmake cmake_minimum_required(VERSION 3.16) project(snmalloc-vcpkg-test CXX) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_VERBOSE_MAKEFILE ON) enable_testing() find_package(snmalloc CONFIG REQUIRED) add_executable(test-header-only test_header_only.cpp) target_link_libraries(test-header-only PRIVATE snmalloc::snmalloc) add_test(NAME header-only COMMAND test-header-only) if(TARGET snmalloc::snmallocshim-static) add_executable(test-static-shim test_static_shim.cpp) target_link_libraries(test-static-shim PRIVATE snmalloc::snmallocshim-static) add_test(NAME static-shim COMMAND test-static-shim) endif() ``` -------------------------------- ### Minimal Shared Library with Nostdlib++ (Non-Windows) Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Configures the minimal shared library to use '-fno-exceptions -nostdlib++' when SNMALLOC_LINKER_SUPPORT_NOSTDLIBXX is enabled and not using C++11 destructors. ```cmake if (SNMALLOC_LINKER_SUPPORT_NOSTDLIBXX AND NOT ${SNMALLOC_CLEANUP} STREQUAL CXX11_DESTRUCTORS) target_compile_options(snmalloc-minimal PRIVATE -fno-exceptions -nostdlib++) endif () ``` -------------------------------- ### Preload snmalloc shared library on ELF platforms Source: https://github.com/microsoft/snmalloc/blob/main/docs/BUILDING.md Use LD_PRELOAD to dynamically link the snmalloc shared library (`libsnmallocshim.so`) in place of the system allocator for a specific command. This is applicable on ELF-based systems. ```bash LD_PRELOAD=/usr/local/lib/libsnmallocshim.so ninja ``` -------------------------------- ### Configure Pointer Authentication (PAC) Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Enables Pointer Authentication (PAC) if the option is set and the compiler/target support it. Includes a check for necessary headers and intrinsics. ```cmake option(SNMALLOC_ENABLE_PAC "Use Pointer Authentication (PAC) for freelist forward-edge protection \n Switch to defaul if target does not support it." OFF) if(SNMALLOC_ENABLE_PAC) check_cxx_compiler_flag( "-Werror -fptrauth-intrinsics" SNMALLOC_COMPILER_SUPPORT_FPTRAUTH_INTRINSICS) if(SNMALLOC_COMPILER_SUPPORT_FPTRAUTH_INTRINSICS) set(SNMALLOC_SAVED_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fptrauth-intrinsics") check_cxx_source_compiles( "#if !defined(__aarch64__) && !defined(_M_ARM64) && !defined(_M_ARM64EC) # error PAC instructions require AArch64 #endif #if !__has_include() # error Missing ptrauth.h #endif #include #ifndef __ARM_FEATURE_PAUTH # error Compiler target does not expose pointer authentication #endif static inline void* sign_and_auth(void* ptr, void* storage) { auto discriminator = ptrauth_blend_discriminator(storage, 0x5678U); auto signed_ptr = ptrauth_sign_unauthenticated( ptr, ptrauth_key_process_dependent_data, discriminator); return ptrauth_auth_data( signed_ptr, ptrauth_key_process_dependent_data, discriminator); } int main() { return sign_and_auth(nullptr, reinterpret_cast(0x1234UL)) != nullptr; } " SNMALLOC_COMPILER_SUPPORT_PACA_PACG) set(CMAKE_REQUIRED_FLAGS "${SNMALLOC_SAVED_REQUIRED_FLAGS}") unset(SNMALLOC_SAVED_REQUIRED_FLAGS) endif() if(NOT SNMALLOC_COMPILER_SUPPORT_PACA_PACG) message(FATAL_ERROR "SNMALLOC_ENABLE_PAC=ON but the target does not support.") endif() target_compile_options(snmalloc INTERFACE $<$:-fptrauth-intrinsics>) endif() ``` -------------------------------- ### Build Docker Image Source: https://github.com/microsoft/snmalloc/blob/main/ci/README.md Rebuilds a Docker image for the snmalloc project. Replace `$IMG` with the target image name (e.g., `linux_x64`). ```bash docker build -t snmallocciteam/build_${IMG}:latest -f ci/${IMG} . ``` -------------------------------- ### Convert ChunkUser to Alloc Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Converts a capptr::ChunkUser to a capptr::Alloc without computational effect, intended for auditing. ```cpp capptr_chunk_is_alloc ``` -------------------------------- ### Push Docker Image to Docker Hub Source: https://github.com/microsoft/snmalloc/blob/main/ci/README.md Pushes the updated Docker image to the snmallocciteam repository on Docker Hub. Requires appropriate permissions. ```bash docker push snmallocciteam/$IMG:latest ``` -------------------------------- ### Check for MSVC Static Library Prefix Compatibility Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Ensures that an empty static library prefix is not used with MSVC, which is not supported. ```cmake if(MSVC AND SNMALLOC_STATIC_LIBRARY AND (SNMALLOC_STATIC_LIBRARY_PREFIX STREQUAL "")) message(FATAL_ERROR "Empty static library prefix not supported on MSVC") endif() ``` -------------------------------- ### Shared Library Build (Non-Windows) Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Compiles a shared library target 'snmallocshim' with specified source files for non-Windows platforms. ```cmake if(NOT WIN32) compile(snmallocshim SHARED ${ALLOC}) ``` -------------------------------- ### Set Minimum Allocation Step Size Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Configures the minimum allocation step size in bytes, which must be a power of 2. ```cmake set(SNMALLOC_MIN_ALLOC_STEP_SIZE "" CACHE STRING "Minimum allocation step (power of 2)") ``` -------------------------------- ### Rust Support Libraries Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Compiles static library targets 'snmallocshim-rust' and 'snmallocshim-checks-rust' using the Rust override source file when SNMALLOC_RUST_SUPPORT is enabled. ```cmake if(SNMALLOC_RUST_SUPPORT) compile(snmallocshim-rust STATIC ${RUST}) compile(snmallocshim-checks-rust STATIC ${RUST}) target_compile_definitions(snmallocshim-checks-rust PRIVATE SNMALLOC_CHECK_CLIENT) endif() ``` -------------------------------- ### Benchmarking Individual Mitigations Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Builds shared libraries for benchmarking individual snmalloc mitigations, each with a unique compile definition. ```cmake if (SNMALLOC_BENCHMARK_INDIVIDUAL_MITIGATIONS) set (MITIGATIONS metadata_protection; pal_enforce_access; random_pagemap; sanity_checks; freelist_forward_edge; freelist_backward_edge; freelist_teardown_validate; reuse_LIFO; random_larger_thresholds; random_initial; random_preserve; random_extra_slab) foreach (MITIGATION ${MITIGATIONS}) set(DEFINES "SNMALLOC_CHECK_CLIENT_MITIGATIONS=${MITIGATION}") compile(snmallocshim-${MITIGATION} SHARED ${ALLOC}) target_compile_definitions(snmallocshim-${MITIGATION} PRIVATE ${DEFINES}) if (SNMALLOC_BUILD_TESTING) make_tests(${MITIGATION} ${DEFINES}) endif() endforeach() set(MITIGATIONSET "no_checks") set(COUNT 0) foreach (MITIGATION ${MITIGATIONS}) MATH(EXPR COUNT "${COUNT} + 1") set(MITIGATIONNAME "mitigations-${COUNT}") set(MITIGATIONSET "${MITIGATIONSET}+${MITIGATION}") message(STATUS "MITIGATIONSET: ${COUNT} -> ${MITIGATIONSET}") set(DEFINES "-DSNMALLOC_CHECK_CLIENT_MITIGATIONS=${MITIGATIONSET}") compile(snmallocshim-${MITIGATIONNAME} SHARED ${ALLOC}) target_compile_definitions(snmallocshim-${MITIGATIONNAME} PRIVATE ${DEFINES}) if (SNMALLOC_BUILD_TESTING) make_tests(${MITIGATIONNAME} ${DEFINES}) endif() endforeach() endif() ``` -------------------------------- ### Define Header Only Library Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Define SNMALLOC_HEADER_ONLY_LIBRARY to build with just the header library target. ```cmake # To build with just the header library target define SNMALLOC_HEADER_ONLY_LIBRARY ``` -------------------------------- ### Build snmalloc Test Library Source: https://github.com/microsoft/snmalloc/blob/main/snmalloc-rs/snmalloc-sys/upstream/CMakeLists.txt Defines a function to build a static test library for snmalloc, linking it against the main snmalloc library and applying specific compile definitions and options. ```cmake function(build_test_library TAG DEFINES) set(LIBNAME snmalloc-testlib-${TAG}) add_library(${LIBNAME} STATIC src/test/snmalloc_testlib.cc) target_link_libraries(${LIBNAME} PRIVATE snmalloc) set_target_properties(${LIBNAME} PROPERTIES INTERFACE_LINK_LIBRARIES "") target_compile_definitions(${LIBNAME} PRIVATE "SNMALLOC_USE_${TEST_CLEANUP}") if (NOT DEFINES STREQUAL " ") target_compile_definitions(${LIBNAME} PRIVATE ${DEFINES}) endif() if(SNMALLOC_SANITIZER) target_compile_options(${LIBNAME} PRIVATE -g -fsanitize=${SNMALLOC_SANITIZER} -fno-omit-frame-pointer) if (${SNMALLOC_SANITIZER} MATCHES "thread") target_compile_definitions(${LIBNAME} PRIVATE SNMALLOC_THREAD_SANITIZER_ENABLED) endif() endif() add_warning_flags(${LIBNAME}) endfunction() ``` -------------------------------- ### Minimal Shared Library (Non-Windows) Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Compiles a minimal shared library target 'snmalloc-minimal' using only the malloc source file and disabling exceptions. ```cmake compile(snmalloc-minimal SHARED ${MALLOC}) target_compile_options(snmalloc-minimal PRIVATE -fno-exceptions) ``` -------------------------------- ### Link Options for MSVC Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Configures static linking for the C++ standard library on MSVC to manage dependencies, especially when exceptions are used. ```cmake if(MSVC) else() # We can't do --nostdlib++ as we are using exceptions, but we # can make it a static dependency, which we aren't really using # as the interesting stuff for exceptions is in libgcc_s target_link_options(${name} PRIVATE -static-libstdc++) endif() ``` -------------------------------- ### Check for linux/futex.h Header Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Checks if the 'linux/futex.h' header file is available. Futex (Fast Userspace Mutex) related functions are often defined in this header on Linux systems. ```cmake CHECK_INCLUDE_FILE_CXX(linux/futex.h SNMALLOC_HAS_LINUX_FUTEX_H) ``` -------------------------------- ### Check Memcpy Override Capability Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Verifies if memcpy can be overridden, which is necessary for SNMALLOC_CHECK_LOADS. Warns if override fails, potentially due to _FORTIFY_SOURCE. ```cmake CHECK_CXX_SOURCE_COMPILES("\n#include \nextern \"C\" void* memcpy(void *, const void*, size_t) {} int main() { return 0; }" SNMALLOC_MEMCPY_OVERRIDE) if (NOT SNMALLOC_MEMCPY_OVERRIDE) message(WARNING "Unable to override memcpy (possbily due to _FORTIFY_SOURCE).") if (SNMALLOC_CHECK_LOADS) message(FATAL_ERROR "SNMALLOC_CHECK_LOADS is incompatible as memcpy could not be overridden. (possbily due to _FORTIFY_SOURCE)") endif() endif() ``` -------------------------------- ### Configure Static TLS Model Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Sets the SNMALLOC_STATIC_MODE_TLS variable based on the system name and dynamic loading configuration. Static TLS is generally used unless on Haiku or dynamic loading is enabled. ```cmake if ((NOT CMAKE_SYSTEM_NAME STREQUAL "Haiku") AND (NOT SNMALLOC_ENABLE_DYNAMIC_LOADING)) message(STATUS "snmalloc: Using static TLS model") set (SNMALLOC_STATIC_MODE_TLS TRUE) endif() ``` -------------------------------- ### Configure Sanitizer Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Set the sanitizer type to use for the build. A message will indicate the chosen sanitizer. ```cmake set(SNMALLOC_SANITIZER "" CACHE STRING "Use sanitizer type (undefined|thread|...)") if (SNMALLOC_SANITIZER) message(STATUS "Using sanitizer=${SNMALLOC_SANITIZER}") endif() ``` -------------------------------- ### Build Test Library Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Defines a CMake function to build a static test library. It links against the main snmalloc library and applies specific compile definitions and options. ```cmake function(build_test_library TAG DEFINES) set(LIBNAME snmalloc-testlib-${TAG}) add_library(${LIBNAME} STATIC src/test/snmalloc_testlib.cc) target_link_libraries(${LIBNAME} PRIVATE snmalloc) set_target_properties(${LIBNAME} PROPERTIES INTERFACE_LINK_LIBRARIES "") target_compile_definitions(${LIBNAME} PRIVATE "SNMALLOC_USE_${TEST_CLEANUP}") if (NOT DEFINES STREQUAL " ") target_compile_definitions(${LIBNAME} PRIVATE ${DEFINES}) endif() if(SNMALLOC_SANITIZER) target_compile_options(${LIBNAME} PRIVATE -g -fsanitize=${SNMALLOC_SANITIZER} -fno-omit-frame-pointer) if (${SNMALLOC_SANITIZER} MATCHES "thread") target_compile_definitions(${LIBNAME} PRIVATE SNMALLOC_THREAD_SANITIZER_ENABLED) endif() endif() add_warning_flags(${LIBNAME}) endfunction() ``` -------------------------------- ### Reveal Wild Pointer Source: https://github.com/microsoft/snmalloc/blob/main/docs/StrictProvenance.md Converts a capptr::AllocWild to a void*, annotating where a wild pointer is intended. ```cpp capptr_reveal_wild ``` -------------------------------- ### Set Test Processors on Windows Source: https://github.com/microsoft/snmalloc/blob/main/CMakeLists.txt Adjusts the number of processors for specific tests on Windows due to high memory usage. This helps manage resource consumption. ```cmake if(WIN32) # On Windows these tests use a lot of memory as it doesn't support # lazy commit. if (${TEST} MATCHES "two_alloc_types") message(VERBOSE "Single threaded test: ${TESTNAME}") set_tests_properties(${TESTNAME} PROPERTIES PROCESSORS 4) endif() if (${TEST} MATCHES "fixed_region") message(VERBOSE "Single threaded test: ${TESTNAME}") set_tests_properties(${TESTNAME} PROPERTIES PROCESSORS 4) endif() if (${TEST} MATCHES "memory") message(VERBOSE "Single threaded test: ${TESTNAME}") set_tests_properties(${TESTNAME} PROPERTIES PROCESSORS 4) endif() endif() ```