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

Add lint for u8 as *mut cast #42915

Open
mattico opened this issue Jun 26, 2017 · 3 comments
Open

Add lint for u8 as *mut cast #42915

mattico opened this issue Jun 26, 2017 · 3 comments
Labels
A-lint Area: Lints (warnings about flaws in source code) such as unused_mut. C-feature-request Category: A feature request, i.e: not implemented / a PR.

Comments

@mattico
Copy link
Contributor

mattico commented Jun 26, 2017

This is an easy error to make: #42901 #42827

A cast from u8 to a pointer is probably always an error. In the rare case that you're creating a pointer into the first 256 bytes of address space, u8 as usize as *mut is more clear, or you can be troubled to #[allow(u8_to_ptr)].

@Mark-Simulacrum Mark-Simulacrum added the A-lint Area: Lints (warnings about flaws in source code) such as unused_mut. label Jun 26, 2017
@retep998
Copy link
Member

This lint should apply to any cast from an integer type that is not usize/isize to a raw pointer, especially because Rust has awful footgun behavior for such casts.

-1i8 as isize gives 0xFFFFFFFFFFFFFFFF
-1i8 as usize gives 0xFFFFFFFFFFFFFFFF
-1i8 as *const () as usize rather surprisingly gives 0xFF

If we compare this to C++ for example:

(intptr_t)int8_t{-1} gives 0xFFFFFFFFFFFFFFFF
(uintptr_t)int8_t{-1} gives 0xFFFFFFFFFFFFFFFF
(uintptr_t)(void*)int8_t{-1} gives the naturally expected 0xFFFFFFFFFFFFFFFF

So basically Rust has a giant footgun in that casting from non pointer sized integers to pointers differs from C/C++ and casts from non pointer sized integers to pointer sized integers. This lint is essential to catch this footgun and warn people about this hazard!

@retep998
Copy link
Member

Related footgun: #43291

@Enselic
Copy link
Member

Enselic commented Sep 14, 2023

Triage: Lint remains unimplemented. Seems useful to have and easy to implement. Maybe first in clippy? Not sure. Playground:

fn main() {
    let _ = 42u8 as *mut u8;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: Lints (warnings about flaws in source code) such as unused_mut. C-feature-request Category: A feature request, i.e: not implemented / a PR.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants