Skip to content

regparm(2) functions on i386 are emitted as ordinary extern C #3417

Description

@lwz23

Input C/C++ header

int regparm2_third(int a, int b, int c) __attribute__((regparm(2)));

Bindgen invocation

$ bindgen input.h \
    --rust-target 1.75 \
    -- -target i686-unknown-linux-gnu -std=gnu11

Actual output

extern "C" {
    pub fn regparm2_third(
        a: ::std::os::raw::c_int,
        b: ::std::os::raw::c_int,
        c: ::std::os::raw::c_int,
    ) -> ::std::os::raw::c_int;
}

I defined the function to return its third argument and called it with
(11, 22, 33). The observed results were:

C caller:          return=33, callee saw c=33
Generated binding: return=11, callee saw c=11

This reproduces at both -O0 and -O2.

Clang lowers the optimized C definition as:

define dso_local i32 @regparm2_third(
    i32 inreg noundef %0,
    i32 inreg noundef %1,
    i32 noundef returned %2)

The Rust caller instead declares it as:

declare dso_local noundef i32 @regparm2_third(
    i32 noundef,
    i32 noundef,
    i32 noundef)

What is wrong

On 32-bit x86, regparm(2) passes the first two integer arguments in EAX and
EDX, with the third argument on the stack. The generated ordinary C declaration
passes all three arguments on the stack. The Rust caller and C callee therefore
use different locations for the same arguments, without any diagnostic.

Expected output

Rust does not provide a matching regparm ABI. Bindgen should diagnose this
declaration as unsupported and avoid emitting a misleading ordinary C binding,
or generate a C wrapper that preserves the source ABI.

Impact

Calls through the generated declaration read the wrong argument values. In
this reproducer, the third parameter is 11 instead of 33 and the function
returns the wrong value.

Environment

bindgen: 0.72.0, current main 25b23474496e78f6a1fbf1c02cb66f11e4d176d0
bindgen release: 0.72.1
clang/libclang: 15.0.7
rustc: 1.75.0
target: i686-unknown-linux-gnu
OS: Ubuntu 22.04.5 LTS, x86_64 host

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