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

c2rust Incorrectly Translates const Variable as Mutable static mut #1184

Open
Yeaseen opened this issue Dec 5, 2024 · 2 comments
Open

c2rust Incorrectly Translates const Variable as Mutable static mut #1184

Yeaseen opened this issue Dec 5, 2024 · 2 comments

Comments

@Yeaseen
Copy link
Contributor

Yeaseen commented Dec 5, 2024

Description

When translating C code with a const variable, c2rust incorrectly generates a mutable static mut variable in Rust. This behavior is inconsistent with the immutability semantics of const in C.

Source C code

#include <stdio.h>
const int x = 1;
int main() {
    printf("Value of x: %d\n", x);
    
    // x=5; // this is compile error in C
    return 0;
}

Translated Rust Code

#[no_mangle]
pub static mut x: libc::c_int = 1 as libc::c_int;
unsafe fn main_0() -> libc::c_int {
    printf(b"Value of x: %d\n\0" as *const u8 as *const libc::c_char, x);
   
   // x=5; // this line is okay here as x is declared as mutable
    return 0 as libc::c_int;
}

In the original C code, x is declared as const, meaning it is immutable. However, c2rust generates static mut x, which makes x mutable in Rust. This is incorrect and violates the immutability semantics of the original C code.

Expected Declaration

#[no_mangle]
pub static x: libc::c_int = 1 as libc::c_int;
@Yeaseen
Copy link
Contributor Author

Yeaseen commented Dec 5, 2024

I think this line creates the problem as it forcefully makes all static contexts mutable!

                // Force mutability due to the potential for raw pointers occurring in the type
                // and because we may be assigning to these variables in the external initializer
                let mut static_def = static_def.span(span).mutbl();

Before this, the mutbl for static context ctf.static_ is ignored here

@kkysen
Copy link
Contributor

kkysen commented Dec 6, 2024

The reason for this is a bit complex. consts in C that contain pointers have to be translated as static muts because internal raw pointers are not allowed in consts in Rust. So we'd have to detect which cases can be const and which ones have to be static muts, which isn't trivial (though we should do it). What's allowed in consts and static muts has been changing and under discussion recently, so we also want to keep that in mind as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants