Skip to content

Commit aad36fb

Browse files
authored
Unrolled build for #144066
Rollup merge of #144066 - RalfJung:extern-c-variadics, r=workingjubilee stabilize c-style varargs for sysv64, win64, efiapi, aapcs This has been split up so the PR now only contains the extended_varargs_abi_support stabilization; "system" has been moved to #145954. **Previous (combined) PR description:** This stabilizes extern block declarations of variadic functions with the system, sysv64, win64, efiapi, aapcs ABIs. This corresponds to the extended_varargs_abi_support and extern_system_varargs feature gates. The feature gates were split up since it seemed like there might be further discussion needed for what exactly "system" ABI variadic functions should do, but a [consensus](#136946 (comment)) has meanwhile been reached: they shall behave like "C" functions. IOW, the ABI of a "system" function is (bold part is new in this PR): - "stdcall" for win32 targets **for non-variadic functions** - "C" for everything else This had been previously stabilized *without FCP* in #116161, which got reverted in #136897. There was also a "fun" race condition involved with the system ABI being [added](#119587) to the list of variadic-supporting ABIs between the creation and merge of #116161. There was a question raised [here](#116161 (comment)) whether t-lang even needs to be involved for a change like this. Not sure if that has meanwhile been clarified? The behavior of the "system" ABI (a Rust-specific ABI) definitely feels like t-lang territory to me. Fixes #100189 Cc `@rust-lang/lang` # Stabilization report > ## General design > ### What is the RFC for this feature and what changes have occurred to the user-facing design since the RFC was finalized? AFAIK there is no RFC. The tracking issues are - #100189 - #136946 > ### What behavior are we committing to that has been controversial? Summarize the major arguments pro/con. The only controversial point is whether "system" ABI functions should support variadics. - Pro: This allows crates like windows-rs to consistently use "system", see e.g. microsoft/windows-rs#3626. - Cons: `@workingjubilee` had some implementation concerns, but I think those have been [resolved](#136946 (comment)). EDIT: turns out Jubilee still has concerns (she mentioned that in a DM); I'll let her express those. Note that "system" is already a magic ABI we introduced to "do the right thing". This just makes it do the right thing in more cases. In particular, it means that on Windows one can almost always just do ```rust extern "system" { // put all the things here } ``` and it'll do the right thing, rather than having to split imports into non-varargs and varargs, with the varargs in a separate `extern "C"` block (and risking accidentally putting a non-vararg there). (I am saying "almost" always because some Windows API functions actually use cdecl, not stdcall, on x86. Those of course need to go in `extern "C"` blocks.) > ### Are there extensions to this feature that remain unstable? How do we know that we are not accidentally committing to those? Actually defining variadic functions in Rust remains unstable, under the [c_variadic feature gate](#44930). > ## Has a Call for Testing period been conducted? If so, what feedback was received? > > Does any OSS nightly users use this feature? For instance, a useful indication might be "search <grep.app> for `#![feature(FEATURE_NAME)]` and had `N` results". There was no call for testing. A search brings up https://github.com/rust-osdev/uefi-rs/blob/main/uefi-raw/src/table/boot.rs using this for "efiapi". This doesn't seem widely used, but it is an "obvious" gap in our support for c-variadics. > ## Implementation quality All rustc does here is forward the ABI to LLVM so there's lot a lot to say here... > ### Summarize the major parts of the implementation and provide links into the code (or to PRs) > > An example for async closures: <https://rustc-dev-guide.rust-lang.org/coroutine-closures.html>. The check for allowed variadic ABIs is [here](https://github.com/rust-lang/rust/blob/9c870d30e2d6434c9e9a004b450c5ccffdf3d844/compiler/rustc_hir_analysis/src/lib.rs#L109-L126). The special handling of "system" is [here](https://github.com/rust-lang/rust/blob/c24914ec8329b22ec7bcaa6ab534a784b2bd8ab9/compiler/rustc_target/src/spec/abi_map.rs#L82-L85). > ### Summarize existing test coverage of this feature > > Consider what the "edges" of this feature are. We're particularly interested in seeing tests that assure us about exactly what nearby things we're not stabilizing. > > Within each test, include a comment at the top describing the purpose of the test and what set of invariants it intends to demonstrate. This is a great help to those reviewing the tests at stabilization time. > > - What does the test coverage landscape for this feature look like? > - Tests for compiler errors when you use the feature wrongly or make mistakes? > - Tests for the feature itself: > - Limits of the feature (so failing compilation) > - Exercises of edge cases of the feature > - Tests that checks the feature works as expected (where applicable, `//@ run-pass`). > - Are there any intentional gaps in test coverage? > > Link to test folders or individual tests (ui/codegen/assembly/run-make tests, etc.). Prior PRs add a codegen test for all ABIs and tests actually calling extern variadic functions for sysv64 and win64: - #144359 - #144379 We don't have a way of executing uefi target code in the test suite, so it's unclear how to fully test efiapi. aapcs could probably be done? (But note that we have hardly an such actually-calling-functions tests for ABI things, we almost entirely rely on codegen tests.) The test ensuring that we do *not* stabilize *defining* c-variadic functions is `tests/ui/feature-gates/feature-gate-c_variadic.rs`. > ### What outstanding bugs in the issue tracker involve this feature? Are they stabilization-blocking? None that I am aware of. > ### What FIXMEs are still in the code for that feature and why is it ok to leave them there? None that I am aware of. > ### Summarize contributors to the feature by name for recognition and assuredness that people involved in the feature agree with stabilization `@Soveu` added sysv64, win64, efiapi, aapcs to the list of ABIs that allow variadics, `@beepster4096` added system. `@workingjubilee` recently refactored the ABI handling in the compiler, also affecting this feature. > ### Which tools need to be adjusted to support this feature. Has this work been done? > > Consider rustdoc, clippy, rust-analyzer, rustfmt, rustup, docs.rs. Maybe RA needs to be taught about the new allowed ABIs? No idea how precisely they mirror what exactly rustc accepts and rejects here. > ## Type system and execution rules > ### What compilation-time checks are done that are needed to prevent undefined behavior? > > (Be sure to link to tests demonstrating that these tests are being done.) Nothing new here, this just expands the existing support for calling variadic functions to more ABIs. > ### Does the feature's implementation need checks to prevent UB or is it sound by default and needs opt in in places to perform the dangerous/unsafe operations? If it is not sound by default, what is the rationale? Nothing new here, this just expands the existing support for calling variadic functions to more ABIs. > ### Can users use this feature to introduce undefined behavior, or use this feature to break the abstraction of Rust and expose the underlying assembly-level implementation? (Describe.) Nothing new here, this just expands the existing support for calling variadic functions to more ABIs. > ### What updates are needed to the reference/specification? (link to PRs when they exist) - rust-lang/reference#1936 > ## Common interactions > ### Does this feature introduce new expressions and can they produce temporaries? What are the lifetimes of those temporaries? No. > ### What other unstable features may be exposed by this feature? None.
2 parents a2c8b0b + f6d55ae commit aad36fb

28 files changed

+128
-162
lines changed

compiler/rustc_abi/src/extern_abi.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ use std::hash::{Hash, Hasher};
66
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd};
77
#[cfg(feature = "nightly")]
88
use rustc_macros::{Decodable, Encodable};
9+
#[cfg(feature = "nightly")]
10+
use rustc_span::Symbol;
911

1012
use crate::AbiFromStrErr;
1113

@@ -226,6 +228,13 @@ impl StableOrd for ExternAbi {
226228
#[cfg(feature = "nightly")]
227229
rustc_error_messages::into_diag_arg_using_display!(ExternAbi);
228230

231+
#[cfg(feature = "nightly")]
232+
pub enum CVariadicStatus {
233+
NotSupported,
234+
Stable,
235+
Unstable { feature: Symbol },
236+
}
237+
229238
impl ExternAbi {
230239
/// An ABI "like Rust"
231240
///
@@ -238,23 +247,33 @@ impl ExternAbi {
238247
matches!(self, Rust | RustCall | RustCold)
239248
}
240249

241-
pub fn supports_varargs(self) -> bool {
250+
/// Returns whether the ABI supports C variadics. This only controls whether we allow *imports*
251+
/// of such functions via `extern` blocks; there's a separate check during AST construction
252+
/// guarding *definitions* of variadic functions.
253+
#[cfg(feature = "nightly")]
254+
pub fn supports_c_variadic(self) -> CVariadicStatus {
242255
// * C and Cdecl obviously support varargs.
243256
// * C can be based on Aapcs, SysV64 or Win64, so they must support varargs.
244257
// * EfiApi is based on Win64 or C, so it also supports it.
258+
// * System automatically falls back to C when used with variadics, therefore supports it.
245259
//
246260
// * Stdcall does not, because it would be impossible for the callee to clean
247261
// up the arguments. (callee doesn't know how many arguments are there)
248262
// * Same for Fastcall, Vectorcall and Thiscall.
249263
// * Other calling conventions are related to hardware or the compiler itself.
264+
//
265+
// All of the supported ones must have a test in `tests/codegen/cffi/c-variadic-ffi.rs`.
250266
match self {
251267
Self::C { .. }
252268
| Self::Cdecl { .. }
253269
| Self::Aapcs { .. }
254270
| Self::Win64 { .. }
255271
| Self::SysV64 { .. }
256-
| Self::EfiApi => true,
257-
_ => false,
272+
| Self::EfiApi => CVariadicStatus::Stable,
273+
Self::System { .. } => {
274+
CVariadicStatus::Unstable { feature: rustc_span::sym::extern_system_varargs }
275+
}
276+
_ => CVariadicStatus::NotSupported,
258277
}
259278
}
260279
}

compiler/rustc_abi/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ mod tests;
6363

6464
pub use callconv::{Heterogeneous, HomogeneousAggregate, Reg, RegKind};
6565
pub use canon_abi::{ArmCall, CanonAbi, InterruptKind, X86Call};
66+
#[cfg(feature = "nightly")]
67+
pub use extern_abi::CVariadicStatus;
6668
pub use extern_abi::{ExternAbi, all_names};
6769
#[cfg(feature = "nightly")]
6870
pub use layout::{FIRST_VARIANT, FieldIdx, Layout, TyAbiInterface, TyAndLayout, VariantIdx};

compiler/rustc_ast_passes/messages.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ ast_passes_auto_super_lifetime = auto traits cannot have super traits or lifetim
5757
.label = {ast_passes_auto_super_lifetime}
5858
.suggestion = remove the super traits or lifetime bounds
5959
60-
ast_passes_bad_c_variadic = only foreign, `unsafe extern "C"`, or `unsafe extern "C-unwind"` functions may have a C-variadic arg
60+
ast_passes_bad_c_variadic = defining functions with C-variadic arguments is only allowed for free functions with the "C" or "C-unwind" calling convention
6161
6262
ast_passes_body_in_extern = incorrect `{$kind}` inside `extern` block
6363
.cannot_have = cannot have a body

compiler/rustc_feature/src/accepted.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,9 @@ declare_features! (
203203
(accepted, expr_fragment_specifier_2024, "1.83.0", Some(123742)),
204204
/// Allows arbitrary expressions in key-value attributes at parse time.
205205
(accepted, extended_key_value_attributes, "1.54.0", Some(78835)),
206+
/// Allows using `aapcs`, `efiapi`, `sysv64` and `win64` as calling conventions
207+
/// for functions with varargs.
208+
(accepted, extended_varargs_abi_support, "CURRENT_RUSTC_VERSION", Some(100189)),
206209
/// Allows resolving absolute paths as paths from other crates.
207210
(accepted, extern_absolute_paths, "1.30.0", Some(44660)),
208211
/// Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.

compiler/rustc_feature/src/unstable.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -492,9 +492,6 @@ declare_features! (
492492
(incomplete, explicit_tail_calls, "1.72.0", Some(112788)),
493493
/// Allows using `#[export_stable]` which indicates that an item is exportable.
494494
(incomplete, export_stable, "1.88.0", Some(139939)),
495-
/// Allows using `aapcs`, `efiapi`, `sysv64` and `win64` as calling conventions
496-
/// for functions with varargs.
497-
(unstable, extended_varargs_abi_support, "1.65.0", Some(100189)),
498495
/// Allows using `system` as a calling convention with varargs.
499496
(unstable, extern_system_varargs, "1.86.0", Some(136946)),
500497
/// Allows defining `extern type`s.

compiler/rustc_hir_analysis/src/check/check.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(),
978978
tcx.ensure_ok().fn_sig(def_id);
979979
let item = tcx.hir_foreign_item(item);
980980
let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() };
981-
require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
981+
check_c_variadic_abi(tcx, sig.decl, abi, item.span);
982982
}
983983
DefKind::Static { .. } => {
984984
tcx.ensure_ok().codegen_fn_attrs(def_id);

compiler/rustc_hir_analysis/src/check/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ use tracing::debug;
9898

9999
use self::compare_impl_item::collect_return_position_impl_trait_in_trait_tys;
100100
use self::region::region_scope_tree;
101-
use crate::{errors, require_c_abi_if_c_variadic};
101+
use crate::{check_c_variadic_abi, errors};
102102

103103
/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]
104104
pub(super) fn provide(providers: &mut Providers) {

compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,11 @@ use rustc_trait_selection::traits::{self, FulfillmentError};
5252
use tracing::{debug, instrument};
5353

5454
use crate::check::check_abi;
55+
use crate::check_c_variadic_abi;
5556
use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation};
5657
use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
5758
use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
5859
use crate::middle::resolve_bound_vars as rbv;
59-
use crate::require_c_abi_if_c_variadic;
6060

6161
/// A path segment that is semantically allowed to have generic arguments.
6262
#[derive(Debug)]
@@ -2412,7 +2412,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
24122412
Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
24132413
}
24142414
hir::TyKind::FnPtr(bf) => {
2415-
require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, hir_ty.span);
2415+
check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
24162416

24172417
Ty::new_fn_ptr(
24182418
tcx,

compiler/rustc_hir_analysis/src/lib.rs

Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ mod outlives;
9090
mod variance;
9191

9292
pub use errors::NoVariantNamed;
93-
use rustc_abi::ExternAbi;
93+
use rustc_abi::{CVariadicStatus, ExternAbi};
9494
use rustc_hir::def::DefKind;
9595
use rustc_hir::lints::DelayedLint;
9696
use rustc_hir::{self as hir};
@@ -99,7 +99,6 @@ use rustc_middle::mir::interpret::GlobalId;
9999
use rustc_middle::query::Providers;
100100
use rustc_middle::ty::{self, Const, Ty, TyCtxt};
101101
use rustc_session::parse::feature_err;
102-
use rustc_span::symbol::sym;
103102
use rustc_span::{ErrorGuaranteed, Span};
104103
use rustc_trait_selection::traits;
105104

@@ -108,46 +107,34 @@ use crate::hir_ty_lowering::{FeedConstTy, HirTyLowerer};
108107

109108
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
110109

111-
fn require_c_abi_if_c_variadic(
112-
tcx: TyCtxt<'_>,
113-
decl: &hir::FnDecl<'_>,
114-
abi: ExternAbi,
115-
span: Span,
116-
) {
117-
// ABIs which can stably use varargs
118-
if !decl.c_variadic || matches!(abi, ExternAbi::C { .. } | ExternAbi::Cdecl { .. }) {
110+
fn check_c_variadic_abi(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: ExternAbi, span: Span) {
111+
if !decl.c_variadic {
112+
// Not even a variadic function.
119113
return;
120114
}
121115

122-
// ABIs with feature-gated stability
123-
let extended_abi_support = tcx.features().extended_varargs_abi_support();
124-
let extern_system_varargs = tcx.features().extern_system_varargs();
125-
126-
// If the feature gate has been enabled, we can stop here
127-
if extern_system_varargs && let ExternAbi::System { .. } = abi {
128-
return;
129-
};
130-
if extended_abi_support && abi.supports_varargs() {
131-
return;
132-
};
133-
134-
// Looks like we need to pick an error to emit.
135-
// Is there any feature which we could have enabled to make this work?
136-
let unstable_explain =
137-
format!("C-variadic functions with the {abi} calling convention are unstable");
138-
match abi {
139-
ExternAbi::System { .. } => {
140-
feature_err(&tcx.sess, sym::extern_system_varargs, span, unstable_explain)
116+
match abi.supports_c_variadic() {
117+
CVariadicStatus::Stable => {}
118+
CVariadicStatus::NotSupported => {
119+
tcx.dcx()
120+
.create_err(errors::VariadicFunctionCompatibleConvention {
121+
span,
122+
convention: &format!("{abi}"),
123+
})
124+
.emit();
141125
}
142-
abi if abi.supports_varargs() => {
143-
feature_err(&tcx.sess, sym::extended_varargs_abi_support, span, unstable_explain)
126+
CVariadicStatus::Unstable { feature } => {
127+
if !tcx.features().enabled(feature) {
128+
feature_err(
129+
&tcx.sess,
130+
feature,
131+
span,
132+
format!("C-variadic functions with the {abi} calling convention are unstable"),
133+
)
134+
.emit();
135+
}
144136
}
145-
_ => tcx.dcx().create_err(errors::VariadicFunctionCompatibleConvention {
146-
span,
147-
convention: &format!("{abi}"),
148-
}),
149137
}
150-
.emit();
151138
}
152139

153140
/// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`]

library/std/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,6 @@
290290
#![feature(doc_masked)]
291291
#![feature(doc_notable_trait)]
292292
#![feature(dropck_eyepatch)]
293-
#![feature(extended_varargs_abi_support)]
294293
#![feature(f16)]
295294
#![feature(f128)]
296295
#![feature(ffi_const)]

0 commit comments

Comments
 (0)