Skip to content

C2Rust emits size_t for __builtin_object_size cast to unsigned long, causing Rust type mismatch #1707

@chisa22

Description

@chisa22

C2Rust incorrectly translates a cast from __builtin_object_size(..., 1) to unsigned long.
Reproducer

int main(void) {
    int x = 0;
    unsigned long n = (unsigned long)__builtin_object_size(&x, 1);
    return 0;
}

Generated Rust

#![allow(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    non_upper_case_globals,
    unused_assignments,
    unused_mut
)]
unsafe fn main_0() -> ::core::ffi::c_int {
    let mut x: ::core::ffi::c_int = 0 as ::core::ffi::c_int;
    &mut x as *mut ::core::ffi::c_int;
    let mut n: ::core::ffi::c_ulong = (if 1 as ::core::ffi::c_int & 2 == 0 {
        -1isize
    } else {
        0isize
    }) as ::libc::size_t;
    return 0 as ::core::ffi::c_int;
}
pub fn main() {
    unsafe { ::std::process::exit(main_0() as i32) }
}

Rust Compilation Error:

error[E0308]: mismatched types
  --> src/main.rs:12:39
   |
12 |       let mut n: ::core::ffi::c_ulong = (if 1 as ::core::ffi::c_int & 2 == 0 {
   |  ________________--------------------___^
   | |                |
   | |                expected due to this
13 | |         -1isize
14 | |     } else {
15 | |         0isize
16 | |     }) as ::libc::size_t;
   | |________________________^ expected `u64`, found `usize`

The C source explicitly casts the result of __builtin_object_size(&x, 1) to unsigned long:

(unsigned long)__builtin_object_size(&x, 1)

However, the generated Rust leaves the expression as ::libc::size_t and assigns it directly to ::core::ffi::c_ulong, which causes a type mismatch in Rust.
Environment

  • c2rust version: v0.21.0
  • platform: Ubuntu 24.04
  • Rust: nightly-2022-08-08
  • Clang version: 17.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions