rust icon indicating copy to clipboard operation
rust copied to clipboard

`unsafe_code` lint does not properly detect usages of `unsafe` functions when in an unsafe scope

Open asquared31415 opened this issue 3 years ago • 2 comments

This code:

fn uwu() {
    unsafe {
        #[forbid(unsafe_code)]
        let owo = (&1 as *const i32).read();
        dbg!(owo);
    }
}

Playground

Does not produce an error for using unsafe code in an expression that is annotated with a forbid(unsafe_code)

Instead, this happened: program compiled without any output

The same issue occurs in several similar scenarios, such as inside an unsafe fn (when unsafe_op_in_unsafe_fn is not enabled)

unsafe fn uwu() {
    #[forbid(unsafe_code)]
    {
        let owo = (&1 as *const i32).read();
        dbg!(owo);
    }
}

Meta

Reproduces on all of current stable, beta, and nightly: Stable 1.65.0 Beta 1.66.0-beta.2 Nightly 1.67.0 2022-11-26 80a96467ec5675e9f696

asquared31415 avatar Nov 27 '22 18:11 asquared31415

Adding some context -- it seems like the forbid(unsafe_code) lint only denies unsafe {} block usages, not unsafe operations. Therefore, when we're inside of a context with that implicitly allows unsafe operations, these operations are silently allowed..

Unclear if this is desired behavior, but certainly this isn't clear from the lint's name. It may be a breaking change to also lint against unsafe usages in this case, but we could definitely run crater to find out.

compiler-errors avatar Nov 27 '22 18:11 compiler-errors

Changing a lint is never considered a breaking change as dependencies are built with cap-lints. (And crater as well I think so cratering a lint doesn't make sense)

Noratrieb avatar Nov 27 '22 18:11 Noratrieb