Skip to content

SIGSEGV / Use After Free in sync::Cache with small weighted capacity #53

@zhu-he

Description

@zhu-he

Description:

I encountered a crash (SIGSEGV) when using mini_moka::sync::Cache with a small capacity and a custom weigher. Running the reproduction case with Miri confirms it is a Use After Free (UAF) issue occurring during eviction in handle_upsert.

Reproduction:

Create a test file issue.rs with the following content:

use mini_moka::sync::CacheBuilder;

#[test]
fn issue() {
    let cache = CacheBuilder::new(3)
        .weigher(|key: &u32, _: &()| key % 2 + 1)
        .build();

    cache.insert(4, ());
    cache.insert(7, ());
    cache.get(&3);
    cache.insert(3, ());
    cache.insert(4, ());
    cache.get(&6);
    cache.get(&6);
    cache.insert(6, ());
    cache.get(&1);
    cache.insert(4, ());
    cache.insert(6, ());
    cache.insert(1, ());
    cache.get(&9);
}

Backtrace (cargo test):

Running cargo test --test issue results in a segmentation fault:

running 1 test
error: test failed, to rerun pass `--test issue`

Caused by:
  process didn't exit successfully: ... (signal: 11, SIGSEGV: invalid memory reference)

Miri Output:

Running cargo +nightly miri test --test issue detects Undefined Behavior (pointer not dereferenceable):

error: Undefined Behavior: pointer not dereferenceable: alloc94094 has been freed, so this pointer is dangling
   --> .../rust/library/core/src/ptr/non_null.rs:445:18
    |
445 |         unsafe { &*self.as_ptr().cast_const() }
    |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    ...
    = note: inside `std::ptr::NonNull::<mini_moka::common::deque::DeqNode<...>>::as_ref::<'_>` 
note: inside `mini_moka::sync::base_cache::Inner::<...>::handle_upsert`
   --> src/sync/base_cache.rs:865:52
    |
865 |                         self.cache.remove(unsafe { victim.as_ref().element.key() })
    |                                                    ^^^^^^^^^^^^^^^

Environment:

  • OS: Linux (x86_64)
  • Rust version: rustc 1.91.1 (ed61e7d7e 2025-11-07)
  • Miri version: miri 0.1.0 (25d319a0f6 2025-11-11) (running with rustc 1.93.0-nightly)

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No fields configured for Bug.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions