Skip to content
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

future::Cache::get_or_(try_)insert_with() can lead UB as accepting init future that is not Send or 'static. #31

Closed
tatsuya6502 opened this issue Sep 2, 2021 · 1 comment
Assignees
Labels
bug Something isn't working
Milestone

Comments

@tatsuya6502
Copy link
Member

tatsuya6502 commented Sep 2, 2021

In Moka v0.5.0 and v0.5.1, the following code fragments for future::Cache will compile. However Moka should reject them as they can lead undefined behavior (UB) in safe Rust.

Example 1

use moka::future::Cache;
use std::rc::Rc;

#[tokio::main]
async fn main() {
    let cache: Cache<_, String> = Cache::new(100);

    // Rc is !Send.
    let data = Rc::new("zero".to_string());
    let data1 = Rc::clone(&data);

    cache
        .get_or_insert_with(0, async move {
            // A data race may occur. 
            // The async block can be executed by a different thread
            // but Rc's internal reference counters are not thread safe.
            data1.to_string()
        })
        .await;

    println!("{:?}", data);
}

Example 2

use moka::future::Cache;

#[tokio::main]
async fn main() {
    let cache: Cache<_, String> = Cache::new(100);

    let data = "zero".to_string();
    {
        // Not 'static.
        let data_ref = &data;

        cache
            .get_or_insert_with(0, async {
                // This may become a dangling pointer.
                // The async block can be executed by a different thread so
                // the captured reference `data_ref` may outlive its value.
                data_ref.to_string()
            })
            .await;
    }

    println!("{:?}", data);
}

So future::Cache's get_or_insert_with() and get_or_try_insert_with() need extra bounds Send and 'static on the init future.

@tatsuya6502 tatsuya6502 self-assigned this Sep 2, 2021
@tatsuya6502 tatsuya6502 added this to the v0.5.2 milestone Sep 2, 2021
@tatsuya6502 tatsuya6502 added the bug Something isn't working label Sep 2, 2021
@tatsuya6502
Copy link
Member Author

This has been addressed by #32.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant