Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2d47622

Browse files
committedNov 30, 2023
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 d3c9964 commit 2d47622

File tree

17 files changed

+215
-9
lines changed

17 files changed

+215
-9
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

+6-4
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_session::config::{
66
build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg,
77
DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs,
8-
InliningThreshold, Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained,
9-
LinkerPluginLto, LocationDetail, LtoCli, MirSpanview, OomStrategy, Options, OutFileName,
10-
OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius, ProcMacroExecutionStrategy, Strip,
11-
SwitchWithOptPath, SymbolManglingVersion, TraitSolver, WasiExecModel,
8+
FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay,
9+
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirSpanview, OomStrategy, Options,
10+
OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
11+
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, TraitSolver,
12+
WasiExecModel,
1213
};
1314
use rustc_session::lint::Level;
1415
use rustc_session::search_paths::SearchPath;
@@ -758,6 +759,7 @@ fn test_unstable_options_tracking_hash() {
758759
tracked!(flatten_format_args, false);
759760
tracked!(force_unstable_if_unmarked, true);
760761
tracked!(fuel, Some(("abc".to_string(), 99)));
762+
tracked!(function_return, FunctionReturn::ThunkExtern);
761763
tracked!(function_sections, Some(false));
762764
tracked!(human_readable_cgu_names, true);
763765
tracked!(incremental_ignore_spans, true);

‎compiler/rustc_llvm/llvm-wrapper/LLVMWrapper.h

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ enum LLVMRustAttribute {
8989
AllocatedPointer = 38,
9090
AllocAlign = 39,
9191
SanitizeSafeStack = 40,
92+
FnRetThunkExtern = 41,
9293
};
9394

9495
typedef struct OpaqueRustString *RustStringRef;

‎compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,8 @@ static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
278278
return Attribute::AllocAlign;
279279
case SanitizeSafeStack:
280280
return Attribute::SafeStack;
281+
case FnRetThunkExtern:
282+
return Attribute::FnRetThunkExtern;
281283
}
282284
report_fatal_error("bad AttributeKind");
283285
}

‎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
@@ -3164,9 +3164,9 @@ impl PpMode {
31643164
pub(crate) mod dep_tracking {
31653165
use super::{
31663166
BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, DebugInfoCompression,
3167-
ErrorOutputType, InliningThreshold, InstrumentCoverage, InstrumentXRay, LinkerPluginLto,
3168-
LocationDetail, LtoCli, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes,
3169-
Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
3167+
ErrorOutputType, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay,
3168+
LinkerPluginLto, LocationDetail, LtoCli, OomStrategy, OptLevel, OutFileName, OutputType,
3169+
OutputTypes, Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
31703170
SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, TraitSolver, TrimmedDefPaths,
31713171
};
31723172
use crate::lint;
@@ -3273,6 +3273,7 @@ pub(crate) mod dep_tracking {
32733273
TraitSolver,
32743274
Polonius,
32753275
InliningThreshold,
3276+
FunctionReturn,
32763277
);
32773278

32783279
impl<T1, T2> DepTrackingHash for (T1, T2)
@@ -3451,3 +3452,14 @@ impl Default for InliningThreshold {
34513452
Self::Sometimes(100)
34523453
}
34533454
}
3455+
3456+
/// The different settings that the `-Zfunction-return` flag can have.
3457+
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]
3458+
pub enum FunctionReturn {
3459+
/// Keep the function return unmodified.
3460+
#[default]
3461+
Keep,
3462+
3463+
/// Replace returns with jumps to thunk, without emitting the thunk.
3464+
ThunkExtern,
3465+
}

‎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
@@ -430,6 +430,7 @@ mod desc {
430430
pub const parse_inlining_threshold: &str =
431431
"either a boolean (`yes`, `no`, `on`, `off`, etc), or a non-negative number";
432432
pub const parse_llvm_module_flag: &str = "<key>:<type>:<value>:<behavior>. Type must currently be `u32`. Behavior should be one of (`error`, `warning`, `require`, `override`, `append`, `appendunique`, `max`, `min`)";
433+
pub const parse_function_return: &str = "`keep` or `thunk-extern`";
433434
}
434435

435436
mod parse {
@@ -1359,6 +1360,15 @@ mod parse {
13591360
slot.push((key.to_string(), value, behavior));
13601361
true
13611362
}
1363+
1364+
pub(crate) fn parse_function_return(slot: &mut FunctionReturn, v: Option<&str>) -> bool {
1365+
match v {
1366+
Some("keep") => *slot = FunctionReturn::Keep,
1367+
Some("thunk-extern") => *slot = FunctionReturn::ThunkExtern,
1368+
_ => return false,
1369+
}
1370+
true
1371+
}
13621372
}
13631373

13641374
options! {
@@ -1603,6 +1613,8 @@ options! {
16031613
"force all crates to be `rustc_private` unstable (default: no)"),
16041614
fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
16051615
"set the optimization fuel quota for a crate"),
1616+
function_return: FunctionReturn = (FunctionReturn::default(), parse_function_return, [TRACKED],
1617+
"replace returns with jumps to `__x86_return_thunk` (default: `keep`)"),
16061618
function_sections: Option<bool> = (None, parse_opt_bool, [TRACKED],
16071619
"whether each function should go in its own section"),
16081620
future_incompat_test: bool = (false, parse_bool, [UNTRACKED],

‎compiler/rustc_session/src/session.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
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,
4+
self, CrateType, FunctionReturn, InstrumentCoverage, OptLevel, OutFileName, OutputType,
55
RemapPathScopeComponents, SwitchWithOptPath,
66
};
77
use crate::config::{ErrorOutputType, Input};
@@ -1678,6 +1678,28 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
16781678
sess.emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
16791679
}
16801680
}
1681+
1682+
if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1683+
if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1684+
sess.emit_err(errors::FunctionReturnRequiresX86OrX8664);
1685+
}
1686+
}
1687+
1688+
// The code model check applies to `thunk` and `thunk-extern`, but not `thunk-inline`, so it is
1689+
// kept as a `match` to force a change if new ones are added, even if we currently only support
1690+
// `thunk-extern` like Clang.
1691+
match sess.opts.unstable_opts.function_return {
1692+
FunctionReturn::Keep => (),
1693+
FunctionReturn::ThunkExtern => {
1694+
// FIXME: In principle, the inherited base LLVM target code model could be large,
1695+
// but this only checks whether we were passed one explicitly (like Clang does).
1696+
if let Some(code_model) = sess.code_model()
1697+
&& code_model == CodeModel::Large
1698+
{
1699+
sess.emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1700+
}
1701+
}
1702+
}
16811703
}
16821704

16831705
/// 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
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
// ignore-x86_64-apple-darwin Symbol is called `___x86_return_thunk` (Darwin's extra underscore)
13+
// ignore-sgx Tests incompatible with LVI mitigations
14+
15+
#![crate_type = "lib"]
16+
17+
// CHECK-LABEL: foo:
18+
#[no_mangle]
19+
pub unsafe fn foo() {
20+
// unset: ret
21+
// unset-NOT: jmp __x86_return_thunk
22+
// keep: ret
23+
// keep-NOT: jmp __x86_return_thunk
24+
// thunk-extern: jmp __x86_return_thunk
25+
// thunk-extern-NOT: ret
26+
// keep-thunk-extern: jmp __x86_return_thunk
27+
// keep-thunk-extern-NOT: ret
28+
// thunk-extern-keep: ret
29+
// thunk-extern-keep-NOT: jmp __x86_return_thunk
30+
}

‎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 1 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 1 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)
Failed to load comments.