Repository navigation
Shared: Use jemalloc as global allocator in Rust-coded extractors #23334
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
redsun82
wants to merge
12
commits into
main
Choose a base branch
from
redsun82-congenial-guacamole
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+340
−0
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ebd4041
Shared: Use jemalloc as global allocator in Rust extractors
226b91c
Bazel: Don't register jemalloc as default malloc zone on macOS
4288be5
Shared: Restrict jemalloc to the Rust extractor
4000b93
Rust: Fix jemalloc Bazel build with cc_common linking and on macOS
4429ba9
Shared: Use jemalloc in the Ruby, QL and unified extractors
625a554
Unified: Use a single jemalloc arena in the extractor
e0166d5
Ruby, QL: Route tree-sitter allocations to jemalloc
1493072
Rust, Ruby, unified: Use jemalloc in Bazel builds only, on all platforms
62f3db2
Shared: Use the new size for jemalloc realloc flags
96302b5
Shared: Abort on OOM in jemalloc's C functions, test more layouts
a1e584e
Shared: Test jemalloc's C functions abort on OOM
710a3da
Rust: Run the jemalloc allocator test in CI
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| 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"], | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
|
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}" | ||
| ); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| #!/bin/sh | ||
| exec /usr/bin/xcrun nm "$@" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.