diff --git a/.bazelrc b/.bazelrc index af13e1838e49..9b0520f667e7 100644 --- a/.bazelrc +++ b/.bazelrc @@ -41,6 +41,9 @@ common --@rules_dotnet//dotnet/settings:strict_deps=false # we only configure a nightly toolchain common --@rules_rust//rust/toolchain/channel=nightly +# the macOS C++ toolchain declares no `nm`, needed by jemalloc +common:macos --@jemalloc//settings/flags:nm=//misc/bazel/jemalloc:xcrun_nm + # Reduce this eventually to empty, once we've fixed all our usages of java, and https://github.com/bazel-contrib/rules_go/issues/4193 is fixed common --incompatible_autoload_externally="+@rules_cc,+@rules_java,+@rules_shell" diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89d4d91f561c..e784d1063fac 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -63,6 +63,14 @@ jobs: - name: Compilation shell: bash run: cargo check + jemalloc: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v5 + - name: Test + shell: bash + run: bazel test //misc/bazel/jemalloc:jemalloc_test rust-codegen: runs-on: ubuntu-latest steps: diff --git a/Cargo.toml b/Cargo.toml index 3b91087a7764..4c8f9798afc5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,8 @@ edition = "2024" [workspace.lints.rust] redundant_imports = "warn" +# set by Bazel builds only, see `codeql_rust_binary` +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(codeql_jemalloc)"] } [workspace.lints.clippy] all = { level = "warn", priority = -1 } diff --git a/MODULE.bazel b/MODULE.bazel index c1c940ee744f..33691157a3f0 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -29,6 +29,7 @@ bazel_dep(name = "rules_kotlin", version = "2.4.21-codeql.1") bazel_dep(name = "gazelle", version = "0.54.0") bazel_dep(name = "rules_dotnet", version = "0.23.0-codeql.1") bazel_dep(name = "googletest", version = "1.18.0.bcr.1") +bazel_dep(name = "jemalloc", version = "5.3.1") bazel_dep(name = "rules_rust", version = "0.75.0") bazel_dep(name = "rules_swift", version = "4.3.0-codeql.1") bazel_dep(name = "swift-syntax", version = "604.0.0") diff --git a/misc/bazel/jemalloc/BUILD.bazel b/misc/bazel/jemalloc/BUILD.bazel new file mode 100644 index 000000000000..9361fbdd13f8 --- /dev/null +++ b/misc/bazel/jemalloc/BUILD.bazel @@ -0,0 +1,54 @@ +load("@jemalloc//settings:config.bzl", "jemalloc") +load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") + +# buildifier: disable=bzl-visibility +load("@rules_rust//rust/private:rust_allocator_libraries.bzl", "rust_allocator_libraries") +load("@rules_shell//shell:sh_binary.bzl", "sh_binary") + +# jemalloc as Rust `#[global_allocator]`, see `codeql_rust_binary`. +rust_library( + name = "jemalloc", + srcs = ["lib.rs"], + crate_name = "codeql_jemalloc", + edition = "2024", + visibility = ["//visibility:public"], + deps = [":jemalloc_c"], +) + +rust_test( + name = "jemalloc_test", + crate = ":jemalloc", +) + +# Prefixed, and not registered as the macOS default malloc zone, so it never replaces the process-wide `malloc`. +jemalloc( + name = "jemalloc_c", + cxx = "False", + jemalloc_prefix = "_rjem_", + stats = "False", + zone_allocator = "no", +) + +# Allocator shim for binaries defining a `#[global_allocator]`. It is only used when linking with `cc_common` and +# mangled allocator symbols, where the default shim would clash with the `__rust_alloc*` symbols emitted for the +# global allocator. The upstream `experimental_use_global_allocator` setting cannot be used instead, as it is +# toolchain-wide and its shim lags behind current nightly rustc. +rust_allocator_libraries( + name = "allocator_libraries", + allocator_library = ":shim", + visibility = ["//visibility:public"], +) + +rust_library( + name = "shim", + srcs = ["shim.rs"], + allocator_libraries = "@rules_rust//ffi/rs:empty_allocator_libraries", + edition = "2024", +) + +# The macOS C++ toolchain declares no `nm`, which jemalloc needs to generate its private namespace header. +# Selected in `.bazelrc` via `@jemalloc//settings/flags:nm`. +sh_binary( + name = "xcrun_nm", + srcs = ["xcrun_nm.sh"], +) diff --git a/misc/bazel/jemalloc/lib.rs b/misc/bazel/jemalloc/lib.rs new file mode 100644 index 000000000000..61212350e009 --- /dev/null +++ b/misc/bazel/jemalloc/lib.rs @@ -0,0 +1,217 @@ +//! `GlobalAlloc` over the `_rjem_`-prefixed jemalloc, as in `tikv-jemallocator`. + +use std::alloc::{GlobalAlloc, Layout}; +use std::ffi::{c_int, c_void}; + +unsafe extern "C" { + #[link_name = "_rjem_malloc"] + fn je_malloc(size: usize) -> *mut c_void; + #[link_name = "_rjem_calloc"] + fn je_calloc(count: usize, size: usize) -> *mut c_void; + #[link_name = "_rjem_realloc"] + fn je_realloc(ptr: *mut c_void, size: usize) -> *mut c_void; + #[link_name = "_rjem_free"] + pub fn free(ptr: *mut c_void); + #[link_name = "_rjem_mallocx"] + fn mallocx(size: usize, flags: c_int) -> *mut c_void; + #[link_name = "_rjem_rallocx"] + fn rallocx(ptr: *mut c_void, size: usize, flags: c_int) -> *mut c_void; + #[link_name = "_rjem_sdallocx"] + fn sdallocx(ptr: *mut c_void, size: usize, flags: c_int); +} + +// Alignment guaranteed by plain `malloc` on the supported 64-bit targets. +const MIN_ALIGN: usize = 16; +const MALLOCX_ZERO: c_int = 0x40; + +/// `MALLOCX_LG_ALIGN` flags, or 0 if plain `malloc` already satisfies the alignment. +#[inline] +fn flags(align: usize, size: usize) -> c_int { + if align <= MIN_ALIGN && align <= size { + 0 + } else { + align.trailing_zeros() as c_int + } +} + +// C allocation functions for C libraries (`tree_sitter::set_allocator`). Like tree-sitter's defaults, they abort +// rather than return null when out of memory. + +fn check(ptr: *mut c_void, count: usize) -> *mut c_void { + if ptr.is_null() && count > 0 { + eprintln!("jemalloc failed to allocate"); + std::process::abort(); + } + ptr +} + +/// # Safety +/// As C `malloc`. +pub unsafe extern "C" fn malloc(size: usize) -> *mut c_void { + check(unsafe { je_malloc(size) }, size) +} + +/// # Safety +/// As C `calloc`. +pub unsafe extern "C" fn calloc(count: usize, size: usize) -> *mut c_void { + check(unsafe { je_calloc(count, size) }, count) +} + +/// # Safety +/// As C `realloc`. +pub unsafe extern "C" fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void { + check(unsafe { je_realloc(ptr, size) }, size) +} + +pub struct Jemalloc; + +// `#[inline]` also places the `_rjem_*` references in the binary's own objects, which rules_rust links ahead of the +// jemalloc archive. + +// SAFETY: jemalloc honours the requested size and alignment, and `dealloc`/`realloc` get the original layout. +unsafe impl GlobalAlloc for Jemalloc { + #[inline] + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + match flags(layout.align(), layout.size()) { + 0 => unsafe { je_malloc(layout.size()) }.cast(), + f => unsafe { mallocx(layout.size(), f) }.cast(), + } + } + + #[inline] + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + match flags(layout.align(), layout.size()) { + 0 => unsafe { je_calloc(1, layout.size()) }.cast(), + f => unsafe { mallocx(layout.size(), f | MALLOCX_ZERO) }.cast(), + } + } + + #[inline] + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { + sdallocx( + ptr.cast(), + layout.size(), + flags(layout.align(), layout.size()), + ) + } + } + + #[inline] + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + match flags(layout.align(), new_size) { + 0 => unsafe { je_realloc(ptr.cast(), new_size) }.cast(), + f => unsafe { rallocx(ptr.cast(), new_size, f) }.cast(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Allocates many live blocks of `layout`, checking alignment, zeroing and contents through a realloc to `new_size`. + fn roundtrip(layout: Layout, new_size: usize) { + let new_layout = Layout::from_size_align(new_size, layout.align()).unwrap(); + let kept = layout.size().min(new_size); + let ptrs: Vec<_> = (0..1000) + .map(|i| unsafe { + let p = if i % 2 == 0 { + Jemalloc.alloc(layout) + } else { + let p = Jemalloc.alloc_zeroed(layout); + assert!( + std::slice::from_raw_parts(p, layout.size()) + .iter() + .all(|&b| b == 0) + ); + p + }; + assert_eq!(p as usize % layout.align(), 0, "misaligned {layout:?}"); + p.write_bytes(i as u8, layout.size()); + let p = Jemalloc.realloc(p, layout, new_size); + assert_eq!( + p as usize % layout.align(), + 0, + "misaligned {layout:?} -> {new_size}" + ); + assert!( + std::slice::from_raw_parts(p, kept) + .iter() + .all(|&b| b == i as u8) + ); + p + }) + .collect(); + for p in ptrs { + unsafe { Jemalloc.dealloc(p, new_layout) }; + } + } + + #[test] + fn ordinary_layouts() { + roundtrip(Layout::from_size_align(24, 8).unwrap(), 100); + roundtrip(Layout::from_size_align(100, 8).unwrap(), 24); + } + + #[test] + fn realloc_keeps_alignment_when_shrinking() { + roundtrip(Layout::from_size_align(32, 16).unwrap(), 8); + } + + #[test] + fn over_aligned_layouts() { + roundtrip(Layout::from_size_align(8, 64).unwrap(), 200); + roundtrip(Layout::from_size_align(5000, 4096).unwrap(), 16); + } + + #[test] + fn c_functions() { + unsafe { + let p = calloc(10, 10).cast::(); + assert!(std::slice::from_raw_parts(p, 100).iter().all(|&b| b == 0)); + let p = realloc(p.cast(), 1000); + free(p); + free(malloc(10)); + } + } + + // Run by `c_functions_abort_on_oom` in a child process. + #[test] + fn oom_child() { + let Ok(f) = std::env::var("CODEQL_JEMALLOC_OOM") else { + return; + }; + let p = unsafe { + match f.as_str() { + "malloc" => malloc(usize::MAX), + "calloc" => calloc(usize::MAX, 2), + "realloc" => realloc(malloc(8), usize::MAX), + _ => unreachable!(), + } + }; + println!("returned {p:?}"); + } + + #[test] + fn c_functions_abort_on_oom() { + for f in ["malloc", "calloc", "realloc"] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tests::oom_child", + "--nocapture", + "--test-threads=1", + ]) + .env("CODEQL_JEMALLOC_OOM", f) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{f} returned instead of aborting"); + assert!( + stderr.contains("jemalloc failed to allocate"), + "{f}: {stderr}" + ); + } + } +} diff --git a/misc/bazel/jemalloc/shim.rs b/misc/bazel/jemalloc/shim.rs new file mode 100644 index 000000000000..3dcadc699565 --- /dev/null +++ b/misc/bazel/jemalloc/shim.rs @@ -0,0 +1,7 @@ +// The only allocator shim symbol not provided by `std` or by `#[global_allocator]` itself. +#![no_std] +#![allow(internal_features)] +#![feature(rustc_attrs)] + +#[rustc_std_internal_symbol] +fn __rust_no_alloc_shim_is_unstable_v2() {} diff --git a/misc/bazel/jemalloc/xcrun_nm.sh b/misc/bazel/jemalloc/xcrun_nm.sh new file mode 100755 index 000000000000..481d037f11f3 --- /dev/null +++ b/misc/bazel/jemalloc/xcrun_nm.sh @@ -0,0 +1,2 @@ +#!/bin/sh +exec /usr/bin/xcrun nm "$@" diff --git a/misc/bazel/rust.bzl b/misc/bazel/rust.bzl index 97afee4ba1c1..6396a109d6f7 100644 --- a/misc/bazel/rust.bzl +++ b/misc/bazel/rust.bzl @@ -7,7 +7,12 @@ def codeql_rust_binary( target_compatible_with = None, visibility = None, symbols_test = True, + jemalloc = False, **kwargs): + """ + `jemalloc` adds a `codeql_jemalloc` dependency and sets `--cfg=codeql_jemalloc`, under which the crate must use + `codeql_jemalloc::Jemalloc` as `#[global_allocator]`. Cargo builds keep the system allocator. + """ rust_label_name = "single_arch/" + name universal_binary( name = name, @@ -15,6 +20,10 @@ def codeql_rust_binary( target_compatible_with = target_compatible_with, visibility = visibility, ) + if jemalloc: + kwargs["rustc_flags"] = kwargs.get("rustc_flags", []) + ["--cfg=codeql_jemalloc"] + kwargs["deps"] = kwargs.get("deps", []) + [Label("//misc/bazel/jemalloc")] + kwargs["allocator_libraries"] = Label("//misc/bazel/jemalloc:allocator_libraries") rust_binary( name = rust_label_name, **kwargs diff --git a/ruby/extractor/BUILD.bazel b/ruby/extractor/BUILD.bazel index 8c93cec30785..40186b78a20e 100644 --- a/ruby/extractor/BUILD.bazel +++ b/ruby/extractor/BUILD.bazel @@ -7,6 +7,7 @@ codeql_rust_binary( name = "extractor", srcs = glob(["src/*.rs"]), aliases = aliases(), + jemalloc = True, proc_macro_deps = all_crate_deps( proc_macro = True, ), diff --git a/ruby/extractor/src/main.rs b/ruby/extractor/src/main.rs index 7768a535bc30..02069bfaad78 100644 --- a/ruby/extractor/src/main.rs +++ b/ruby/extractor/src/main.rs @@ -4,6 +4,24 @@ mod autobuilder; mod extractor; mod generator; +#[cfg(codeql_jemalloc)] +#[global_allocator] +static GLOBAL: codeql_jemalloc::Jemalloc = codeql_jemalloc::Jemalloc; + +/// Routes tree-sitter's C allocations to the same (prefixed) jemalloc as Rust allocations. +#[cfg(codeql_jemalloc)] +fn use_jemalloc_for_tree_sitter() { + // SAFETY: called first thing in `main`, before tree-sitter allocates anything. + unsafe { + tree_sitter::set_allocator( + Some(codeql_jemalloc::malloc), + Some(codeql_jemalloc::calloc), + Some(codeql_jemalloc::realloc), + Some(codeql_jemalloc::free), + ); + } +} + #[derive(Parser)] #[command(author, version, about)] enum Cli { @@ -13,6 +31,8 @@ enum Cli { } fn main() -> std::io::Result<()> { + #[cfg(codeql_jemalloc)] + use_jemalloc_for_tree_sitter(); let cli = Cli::parse(); match cli { diff --git a/rust/extractor/BUILD.bazel b/rust/extractor/BUILD.bazel index 0ed545a7f37e..2de7e3687270 100644 --- a/rust/extractor/BUILD.bazel +++ b/rust/extractor/BUILD.bazel @@ -11,6 +11,7 @@ codeql_rust_binary( "src/qltest_cargo.mustache", "src/nightly-toolchain/rust-toolchain.toml", ], + jemalloc = True, proc_macro_deps = all_crate_deps( proc_macro = True, ), diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 92f119b68777..19b49702469c 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -37,6 +37,10 @@ mod translate; pub mod trap; mod util; +#[cfg(codeql_jemalloc)] +#[global_allocator] +static GLOBAL: codeql_jemalloc::Jemalloc = codeql_jemalloc::Jemalloc; + struct Extractor<'a> { archiver: &'a Archiver, traps: &'a trap::TrapFileProvider, diff --git a/unified/extractor/BUILD.bazel b/unified/extractor/BUILD.bazel index 73ce3ca0e810..006d334d77c8 100644 --- a/unified/extractor/BUILD.bazel +++ b/unified/extractor/BUILD.bazel @@ -15,6 +15,7 @@ codeql_rust_binary( "swift_node_types.yml", ], data = ["//unified/swift-syntax-rs:swift_runtime"], + jemalloc = True, proc_macro_deps = all_crate_deps( proc_macro = True, ), diff --git a/unified/extractor/src/main.rs b/unified/extractor/src/main.rs index 5a3407c37a29..02b0ce33fd26 100644 --- a/unified/extractor/src/main.rs +++ b/unified/extractor/src/main.rs @@ -5,6 +5,16 @@ mod extractor; mod generator; mod languages; +#[cfg(codeql_jemalloc)] +#[global_allocator] +static GLOBAL: codeql_jemalloc::Jemalloc = codeql_jemalloc::Jemalloc; + +// With jemalloc's default per-thread arenas, peak RSS was ~60% above the system allocator here; +// a single arena brings it below that at no measured CPU cost. +#[cfg(codeql_jemalloc)] +#[unsafe(export_name = "_rjem_malloc_conf")] +static MALLOC_CONF: &[u8; 10] = b"narenas:1\0"; + #[derive(Parser)] #[command(author, version, about)] enum Cli {