Skip to content

Commit 8df5004

Browse files
committed
Add -Zfunction-return={keep,thunk-extern} option
This is intended to be used for Linux kernel RETHUNK builds. With this commit (optionally backported to Rust 1.73.0), plus a patched Linux kernel to pass the flag, I get a RETHUNK build with Rust enabled that is `objtool`-warning-free and is able to boot in QEMU and load a sample Rust kernel module. Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 7ed02b7 commit 8df5004

File tree

17 files changed

+207
-5
lines changed

17 files changed

+207
-5
lines changed

compiler/rustc_codegen_llvm/src/attributes.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_codegen_ssa::traits::*;
44
use rustc_hir::def_id::DefId;
55
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
66
use rustc_middle::ty::{self, TyCtxt};
7-
use rustc_session::config::OptLevel;
7+
use rustc_session::config::{FunctionReturn, OptLevel};
88
use rustc_span::symbol::sym;
99
use rustc_target::spec::abi::Abi;
1010
use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtector};
@@ -118,6 +118,15 @@ pub fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attr
118118
Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
119119
}
120120

121+
fn function_return_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
122+
let function_return_attr = match cx.sess().opts.unstable_opts.function_return {
123+
FunctionReturn::Keep => return None,
124+
FunctionReturn::ThunkExtern => AttributeKind::FnRetThunkExtern,
125+
};
126+
127+
Some(function_return_attr.create_attr(cx.llcx))
128+
}
129+
121130
/// Tell LLVM what instrument function to insert.
122131
#[inline]
123132
fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 4]> {
@@ -333,6 +342,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
333342

334343
// FIXME: none of these functions interact with source level attributes.
335344
to_add.extend(frame_pointer_type_attr(cx));
345+
to_add.extend(function_return_attr(cx));
336346
to_add.extend(instrument_function_attr(cx));
337347
to_add.extend(nojumptables_attr(cx));
338348
to_add.extend(probestack_attr(cx));

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

+1
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ pub enum AttributeKind {
200200
AllocatedPointer = 38,
201201
AllocAlign = 39,
202202
SanitizeSafeStack = 40,
203+
FnRetThunkExtern = 41,
203204
}
204205

205206
/// LLVMIntPredicate

compiler/rustc_interface/src/tests.rs

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_data_structures::profiling::TimePassesFormat;
66
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
77
use rustc_session::config::rustc_optgroups;
88
use rustc_session::config::DebugInfo;
9+
use rustc_session::config::FunctionReturn;
910
use rustc_session::config::Input;
1011
use rustc_session::config::InstrumentXRay;
1112
use rustc_session::config::LinkSelfContained;
@@ -782,6 +783,7 @@ fn test_unstable_options_tracking_hash() {
782783
tracked!(flatten_format_args, false);
783784
tracked!(force_unstable_if_unmarked, true);
784785
tracked!(fuel, Some(("abc".to_string(), 99)));
786+
tracked!(function_return, FunctionReturn::ThunkExtern);
785787
tracked!(function_sections, Some(false));
786788
tracked!(human_readable_cgu_names, true);
787789
tracked!(incremental_ignore_spans, true);

compiler/rustc_llvm/llvm-wrapper/LLVMWrapper.h

+1
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ enum LLVMRustAttribute {
9494
AllocatedPointer = 38,
9595
AllocAlign = 39,
9696
SanitizeSafeStack = 40,
97+
FnRetThunkExtern = 41,
9798
};
9899

99100
typedef struct OpaqueRustString *RustStringRef;

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,8 @@ static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
283283
return Attribute::AllocAlign;
284284
case SanitizeSafeStack:
285285
return Attribute::SafeStack;
286+
case FnRetThunkExtern:
287+
return Attribute::FnRetThunkExtern;
286288
}
287289
report_fatal_error("bad AttributeKind");
288290
}

compiler/rustc_session/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ session_file_is_not_writeable = output file {$file} is not writeable -- check it
2626
2727
session_file_write_fail = failed to write `{$path}` due to error `{$err}`
2828
29+
session_function_return_requires_x86_or_x86_64 = `-Zfunction-return` (except `keep`) is only supported on x86 and x86_64
30+
31+
session_function_return_thunk_extern_requires_non_large_code_model = `-Zfunction-return=thunk-extern` is only supported on non-large code models
32+
2933
session_hexadecimal_float_literal_not_supported = hexadecimal float literal is not supported
3034
3135
session_incompatible_linker_flavor = linker flavor `{$flavor}` is incompatible with the current target

compiler/rustc_session/src/config.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -3171,9 +3171,9 @@ impl PpMode {
31713171
pub(crate) mod dep_tracking {
31723172
use super::{
31733173
BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, DebugInfoCompression,
3174-
ErrorOutputType, InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail,
3175-
LtoCli, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes, Polonius,
3176-
ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath,
3174+
ErrorOutputType, FunctionReturn, InstrumentCoverage, InstrumentXRay, LinkerPluginLto,
3175+
LocationDetail, LtoCli, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes,
3176+
Polonius, ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath,
31773177
SymbolManglingVersion, TraitSolver, TrimmedDefPaths,
31783178
};
31793179
use crate::lint;
@@ -3279,6 +3279,7 @@ pub(crate) mod dep_tracking {
32793279
LanguageIdentifier,
32803280
TraitSolver,
32813281
Polonius,
3282+
FunctionReturn,
32823283
);
32833284

32843285
impl<T1, T2> DepTrackingHash for (T1, T2)
@@ -3449,3 +3450,14 @@ impl Polonius {
34493450
matches!(self, Polonius::Next)
34503451
}
34513452
}
3453+
3454+
/// The different settings that the `-Zfunction-return` flag can have.
3455+
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]
3456+
pub enum FunctionReturn {
3457+
/// Keep the function return unmodified.
3458+
#[default]
3459+
Keep,
3460+
3461+
/// Replace returns with jumps to thunk, without emitting the thunk.
3462+
ThunkExtern,
3463+
}

compiler/rustc_session/src/errors.rs

+8
Original file line numberDiff line numberDiff line change
@@ -436,3 +436,11 @@ pub struct IncompatibleLinkerFlavor {
436436
pub flavor: &'static str,
437437
pub compatible_list: String,
438438
}
439+
440+
#[derive(Diagnostic)]
441+
#[diag(session_function_return_requires_x86_or_x86_64)]
442+
pub(crate) struct FunctionReturnRequiresX86OrX8664;
443+
444+
#[derive(Diagnostic)]
445+
#[diag(session_function_return_thunk_extern_requires_non_large_code_model)]
446+
pub(crate) struct FunctionReturnThunkExternRequiresNonLargeCodeModel;

compiler/rustc_session/src/options.rs

+12
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@ mod desc {
427427
pub const parse_proc_macro_execution_strategy: &str =
428428
"one of supported execution strategies (`same-thread`, or `cross-thread`)";
429429
pub const parse_dump_solver_proof_tree: &str = "one of: `always`, `on-request`, `on-error`";
430+
pub const parse_function_return: &str = "`keep` or `thunk-extern`";
430431
}
431432

432433
mod parse {
@@ -1284,6 +1285,15 @@ mod parse {
12841285
};
12851286
true
12861287
}
1288+
1289+
pub(crate) fn parse_function_return(slot: &mut FunctionReturn, v: Option<&str>) -> bool {
1290+
match v {
1291+
Some("keep") => *slot = FunctionReturn::Keep,
1292+
Some("thunk-extern") => *slot = FunctionReturn::ThunkExtern,
1293+
_ => return false,
1294+
}
1295+
true
1296+
}
12871297
}
12881298

12891299
options! {
@@ -1530,6 +1540,8 @@ options! {
15301540
"force all crates to be `rustc_private` unstable (default: no)"),
15311541
fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
15321542
"set the optimization fuel quota for a crate"),
1543+
function_return: FunctionReturn = (FunctionReturn::default(), parse_function_return, [TRACKED],
1544+
"replace returns with jumps to `__x86_return_thunk` (default: `keep`)"),
15331545
function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
15341546
"whether each function should go in its own section"),
15351547
future_incompat_test: bool = (false, parse_bool, [UNTRACKED],

compiler/rustc_session/src/session.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use crate::code_stats::CodeStats;
22
pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
33
use crate::config::{
4-
self, CrateType, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
4+
self, CrateType, FunctionReturn, InstrumentCoverage, OptLevel, OutFileName, OutputType,
5+
SwitchWithOptPath,
56
};
67
use crate::config::{ErrorOutputType, Input};
78
use crate::errors;
@@ -1643,6 +1644,25 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
16431644
sess.emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
16441645
}
16451646
}
1647+
1648+
if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1649+
if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1650+
sess.emit_err(errors::FunctionReturnRequiresX86OrX8664);
1651+
}
1652+
}
1653+
1654+
// This applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is kept as a
1655+
// `match` to force a change even if we only support `thunk-extern` like Clang.
1656+
match sess.opts.unstable_opts.function_return {
1657+
FunctionReturn::Keep => (),
1658+
FunctionReturn::ThunkExtern => {
1659+
// FIXME: In principle, the LLVM default code model could be large, but this only checks
1660+
// whether we were passed one explicitly (like Clang does).
1661+
if let Some(code_model) = sess.code_model() && code_model == CodeModel::Large {
1662+
sess.emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1663+
}
1664+
}
1665+
}
16461666
}
16471667

16481668
/// Holds data on the current incremental compilation session, if there is one.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# `function-return`
2+
3+
The tracking issue for this feature is: https://github.com/rust-lang/rust/issues/116853.
4+
5+
------------------------
6+
7+
Option `-Zfunction-return` controls how function returns are converted.
8+
9+
It is equivalent to [Clang]'s and [GCC]'s `-mfunction-return`. The Linux kernel
10+
uses it for RETHUNK builds. For details, see [LLVM commit 2240d72f15f3] ("[X86]
11+
initial -mfunction-return=thunk-extern support") which introduces the feature.
12+
13+
Supported values for this option are:
14+
15+
- `keep`: do not convert function returns.
16+
- `thunk-extern`: convert function returns (`ret`) to jumps (`jmp`)
17+
to an external symbol called `__x86_return_thunk`.
18+
19+
Like in Clang, GCC's values `thunk` and `thunk-inline` are not supported.
20+
21+
Only x86 and non-large code models are supported.
22+
23+
[Clang]: https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mfunction-return
24+
[GCC]: https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-mfunction-return
25+
[LLVM commit 2240d72f15f3]: https://github.com/llvm/llvm-project/commit/2240d72f15f3b7b9d9fb65450f9bf635fd310f6f
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Test that the function return is (not) converted into a jump to the thunk
2+
// when the `-Zfunction-return={keep,thunk-extern}` flag is (not) set.
3+
4+
// revisions: unset keep thunk-extern keep-thunk-extern thunk-extern-keep
5+
// assembly-output: emit-asm
6+
// compile-flags: -O
7+
// [keep] compile-flags: -Zfunction-return=keep
8+
// [thunk-extern] compile-flags: -Zfunction-return=thunk-extern
9+
// [keep-thunk-extern] compile-flags: -Zfunction-return=keep -Zfunction-return=thunk-extern
10+
// [thunk-extern-keep] compile-flags: -Zfunction-return=thunk-extern -Zfunction-return=keep
11+
// only-x86_64
12+
13+
#![crate_type = "lib"]
14+
15+
// CHECK-LABEL: foo:
16+
#[no_mangle]
17+
pub unsafe fn foo() {
18+
// unset: ret
19+
// unset-NOT: jmp __x86_return_thunk
20+
// keep: ret
21+
// keep-NOT: jmp __x86_return_thunk
22+
// thunk-extern: jmp __x86_return_thunk
23+
// thunk-extern-NOT: ret
24+
// keep-thunk-extern: jmp __x86_return_thunk
25+
// keep-thunk-extern-NOT: ret
26+
// thunk-extern-keep: ret
27+
// thunk-extern-keep-NOT: jmp __x86_return_thunk
28+
}

tests/codegen/function-return.rs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Test that the `fn_ret_thunk_extern` function attribute is (not) emitted when
2+
// the `-Zfunction-return={keep,thunk-extern}` flag is (not) set.
3+
4+
// revisions: unset keep thunk-extern keep-thunk-extern thunk-extern-keep
5+
// needs-llvm-components: x86
6+
// compile-flags: --target x86_64-unknown-linux-gnu
7+
// [keep] compile-flags: -Zfunction-return=keep
8+
// [thunk-extern] compile-flags: -Zfunction-return=thunk-extern
9+
// [keep-thunk-extern] compile-flags: -Zfunction-return=keep -Zfunction-return=thunk-extern
10+
// [thunk-extern-keep] compile-flags: -Zfunction-return=thunk-extern -Zfunction-return=keep
11+
12+
#![crate_type = "lib"]
13+
#![feature(no_core, lang_items)]
14+
#![no_core]
15+
16+
#[lang = "sized"]
17+
trait Sized {}
18+
19+
#[no_mangle]
20+
pub fn foo() {
21+
// CHECK: @foo() unnamed_addr #0
22+
23+
// unset-NOT: fn_ret_thunk_extern
24+
// keep-NOT: fn_ret_thunk_extern
25+
// thunk-extern: attributes #0 = { {{.*}}fn_ret_thunk_extern{{.*}} }
26+
// keep-thunk-extern: attributes #0 = { {{.*}}fn_ret_thunk_extern{{.*}} }
27+
// thunk-extern-keep-NOT: fn_ret_thunk_extern
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
error: `-Zfunction-return` (except `keep`) is only supported on x86 and x86_64
2+
3+
error: aborting due to previous error
4+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// revisions: x86 x86_64 aarch64
2+
3+
// compile-flags: -Zfunction-return=thunk-extern
4+
5+
//[x86] check-pass
6+
//[x86] needs-llvm-components: x86
7+
//[x86] compile-flags: --target i686-unknown-linux-gnu
8+
9+
//[x86_64] check-pass
10+
//[x86_64] needs-llvm-components: x86
11+
//[x86_64] compile-flags: --target x86_64-unknown-linux-gnu
12+
13+
//[aarch64] check-fail
14+
//[aarch64] needs-llvm-components: aarch64
15+
//[aarch64] compile-flags: --target aarch64-unknown-linux-gnu
16+
//[aarch64] error-pattern: `-Zfunction-return` (except `keep`) is only supported on x86 and x86_64
17+
18+
#![feature(no_core)]
19+
#![no_core]
20+
#![no_main]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
error: `-Zfunction-return=thunk-extern` is only supported on non-large code models
2+
3+
error: aborting due to previous error
4+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// revisions: small kernel medium large
2+
3+
// needs-llvm-components: x86
4+
// compile-flags: --target x86_64-unknown-linux-gnu -Zfunction-return=thunk-extern
5+
6+
//[small] check-pass
7+
//[small] compile-flags: -Ccode-model=small
8+
9+
//[kernel] check-pass
10+
//[kernel] compile-flags: -Ccode-model=kernel
11+
12+
//[medium] check-pass
13+
//[medium] compile-flags: -Ccode-model=medium
14+
15+
//[large] check-fail
16+
//[large] compile-flags: -Ccode-model=large
17+
//[large] error-pattern: `-Zfunction-return=thunk-extern` is only supported on non-large code models
18+
19+
#![feature(no_core)]
20+
#![no_core]
21+
#![no_main]

0 commit comments

Comments
 (0)