c2rust icon indicating copy to clipboard operation
c2rust copied to clipboard

Missing unsafe for extern "C" blocks/update to syn 2.0

Open Lysarina opened this issue 8 months ago • 1 comments

Hi, I am trying to translate a whole C project to Rust using C2Rust. I am using the 2024 edition, which requires using the unsafe keyword for extern blocks. However, the code C2Rust emits does not put unsafe before an extern "C" block, leading to the code not compiling.

error: extern blocks must be unsafe
   --> src/xcm.rs:11:1
    |
11  | / extern "C" {
12  | |     pub type xcm_attr_map;
13  | |     pub type ctl;
14  | |     pub type xpoll;
...   |
132 | |     fn poll(__fds: *mut pollfd, __nfds: nfds_t, __timeout: libc::c_int) -> libc::c_int;
133 | | }
    | |_^

I've spent some time digging around and trying to insert unsafe into different places, and my guess is that the error lies in c2rust-ast-builder/src/builder.rs:

    pub fn foreign_items(self, items: Vec<ForeignItem>) -> Box<Item> {
        let abi = self.get_abi();

        Box::new(Item::ForeignMod(ItemForeignMod {
            attrs: self.attrs,
            brace_token: token::Brace(self.span),
            items,
            abi,
        }))
    }

For syn 2.0, ItemForeignMod has an unsafety field which I think would solve this issue, but with syn 1.0, I cannot find a way of making extern blocks unsafe.

I saw that there was a previous issue about syn 2.0 and how it brought a lot of changes, but if this could be fixed somehow (in one way or another), it would be great!

Lysarina avatar Apr 04 '25 14:04 Lysarina

I think c2rust-transpile need to upgrade to syn 2.0 for better feature, but upgrading will increasing rustc version which still need "nightly-2022-08-08" for c2rust-analyze. upgrading from sync 1.0 -> 2.0 is time consuming but doable. last year I upgrading my fork to sync 2.0

https://github.com/bungcip/rustification/commit/df0cdaf421f2d1f9e5bd0ff9c275fb2a9aeef425

bungcip avatar Apr 23 '25 13:04 bungcip