Skip to content

Is bool FFI-safe? #95184

Open
Open
@mcy

Description

@mcy

The following seem inconsistent:

An object with the boolean type has a size and alignment
of 1 each. The value false has the bit pattern 0x00 and the value true has the bit pattern 0x01. It is
undefined behavior for an object with the boolean type
to have any other bit pattern.

-- https://doc.rust-lang.org/reference/types/boolean.html#boolean-type

warning: `extern` fn uses type `Improper`, which is not FFI-safe
 --> <source>:2:35
  |
2 | pub extern "C" fn bad(_: bool, _: Improper) {}
  |                                   ^^^^^^^^ not FFI-safe
  |
  = note: `#[warn(improper_ctypes_definitions)]` on by default
  = help: consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct
  = note: this struct has unspecified layout
note: the type is defined here
 --> <source>:1:1
  |
1 | pub struct Improper;
  | ^^^^^^^^^^^^^^^^^^^^

warning: 1 warning emitted

The reference states that bool has the same layout as u8 and can only take on the "usual" bitpatterns. OTOH, The improper ctypes lints seem to believe that bool is FFI-safe, by omission, which is further underscored in the UGC draft: https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#bool, which ties it to _Bool; C makes ~no guarantees about the layout of this type, although papers have been published in the past to try to nail down a bit representation. (Personally, such a proposal seems as unlikely as nullptr being guaranteed to be all-zeroes, so I wouldn't count on it.)

Discussion on a somewhat old issue seems to indicate we are not sure how we feel about this, so I'd lean towards weakening the reference's assertion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ABIArea: Concerning the application binary interface (ABI)A-FFIArea: Foreign function interface (FFI)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions