Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
1 change: 1 addition & 0 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
54 changes: 54 additions & 0 deletions misc/bazel/jemalloc/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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",
Comment thread
redsun82 marked this conversation as resolved.
Resolved
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"],
)
217 changes: 217 additions & 0 deletions misc/bazel/jemalloc/lib.rs
Original file line number Diff line number Diff line change
@@ -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 {
Comment thread
redsun82 marked this conversation as resolved.
Resolved
#[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::<u8>();
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}"
);
}
}
}
7 changes: 7 additions & 0 deletions misc/bazel/jemalloc/shim.rs
Original file line number Diff line number Diff line change
@@ -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() {}
2 changes: 2 additions & 0 deletions misc/bazel/jemalloc/xcrun_nm.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
exec /usr/bin/xcrun nm "$@"
9 changes: 9 additions & 0 deletions misc/bazel/rust.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,23 @@ 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,
dep = ":" + rust_label_name,
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
Expand Down
1 change: 1 addition & 0 deletions ruby/extractor/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
Expand Down
20 changes: 20 additions & 0 deletions ruby/extractor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);
}
}
Comment thread
redsun82 marked this conversation as resolved.
Resolved

#[derive(Parser)]
#[command(author, version, about)]
enum Cli {
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions rust/extractor/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
Expand Down
Loading
Loading