Skip to content

Commit ac7595f

Browse files
maurernebulark
authored andcommitted
Support for -Z patchable-function-entry
`-Z patchable-function-entry` works like `-fpatchable-function-entry` on clang/gcc. The arguments are total nop count and function offset. See MCP rust-lang/compiler-team#704
1 parent d929a42 commit ac7595f

File tree

7 files changed

+139
-1
lines changed

7 files changed

+139
-1
lines changed

compiler/rustc_codegen_llvm/src/attributes.rs

+26
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,31 @@ fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll
5353
}
5454
}
5555

56+
#[inline]
57+
fn patchable_function_entry_attrs<'ll>(
58+
cx: &CodegenCx<'ll, '_>,
59+
) -> SmallVec<[&'ll Attribute; 2]> {
60+
let mut attrs = SmallVec::new();
61+
let patchable_spec = cx.tcx.sess.opts.unstable_opts.patchable_function_entry;
62+
let entry = patchable_spec.entry();
63+
let prefix = patchable_spec.prefix();
64+
if entry > 0 {
65+
attrs.push(llvm::CreateAttrStringValue(
66+
cx.llcx,
67+
"patchable-function-entry",
68+
&format!("{}", entry),
69+
));
70+
}
71+
if prefix > 0 {
72+
attrs.push(llvm::CreateAttrStringValue(
73+
cx.llcx,
74+
"patchable-function-prefix",
75+
&format!("{}", prefix),
76+
));
77+
}
78+
attrs
79+
}
80+
5681
/// Get LLVM sanitize attributes.
5782
#[inline]
5883
pub fn sanitize_attrs<'ll>(
@@ -421,6 +446,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
421446
llvm::set_alignment(llfn, align);
422447
}
423448
to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
449+
to_add.extend(patchable_function_entry_attrs(cx));
424450

425451
// Always annotate functions with the target-cpu they are compiled for.
426452
// Without this, ThinLTO won't inline Rust functions into Clang generated

compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,7 @@ fn test_unstable_options_tracking_hash() {
813813
tracked!(packed_bundled_libs, true);
814814
tracked!(panic_abort_tests, true);
815815
tracked!(panic_in_drop, PanicStrategy::Abort);
816+
tracked!(patchable_function_entry, PatchableFunctionEntry::from_nop_count_and_offset(3, 4));
816817
tracked!(plt, Some(true));
817818
tracked!(polonius, Polonius::Legacy);
818819
tracked!(precise_enum_drop_elaboration, false);

compiler/rustc_middle/src/middle/codegen_fn_attrs.rs

+23
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,29 @@ pub struct CodegenFnAttrs {
4747
pub alignment: Option<Align>,
4848
}
4949

50+
#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
51+
pub struct PatchableFunctionEntry {
52+
/// Nops to prepend to the function
53+
prefix: u8,
54+
/// Nops after entry, but before body
55+
entry: u8,
56+
}
57+
58+
impl PatchableFunctionEntry {
59+
pub fn from_config(config: rustc_session::config::PatchableFunctionEntry) -> Self {
60+
Self { prefix: config.prefix(), entry: config.entry() }
61+
}
62+
pub fn from_prefix_and_entry(prefix: u8, entry: u8) -> Self {
63+
Self { prefix, entry }
64+
}
65+
pub fn prefix(&self) -> u8 {
66+
self.prefix
67+
}
68+
pub fn entry(&self) -> u8 {
69+
self.entry
70+
}
71+
}
72+
5073
#[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
5174
pub struct CodegenFnAttrFlags(u32);
5275
bitflags::bitflags! {

compiler/rustc_session/src/config.rs

+28-1
Original file line numberDiff line numberDiff line change
@@ -2963,7 +2963,7 @@ pub(crate) mod dep_tracking {
29632963
CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FunctionReturn,
29642964
InliningThreshold, InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail,
29652965
LtoCli, NextSolverConfig, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes,
2966-
Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
2966+
PatchableFunctionEntry, Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
29672967
SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
29682968
};
29692969
use crate::lint;
@@ -3071,6 +3071,7 @@ pub(crate) mod dep_tracking {
30713071
OomStrategy,
30723072
LanguageIdentifier,
30733073
NextSolverConfig,
3074+
PatchableFunctionEntry,
30743075
Polonius,
30753076
InliningThreshold,
30763077
FunctionReturn,
@@ -3248,6 +3249,32 @@ impl DumpMonoStatsFormat {
32483249
}
32493250
}
32503251

3252+
/// `-Z patchable-function-entry` representation - how many nops to put before and after function
3253+
/// entry.
3254+
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]
3255+
pub struct PatchableFunctionEntry {
3256+
/// Nops before the entry
3257+
prefix: u8,
3258+
/// Nops after the entry
3259+
entry: u8,
3260+
}
3261+
3262+
impl PatchableFunctionEntry {
3263+
pub fn from_nop_count_and_offset(nop_count: u8, offset: u8) -> Option<PatchableFunctionEntry> {
3264+
if nop_count < offset {
3265+
None
3266+
} else {
3267+
Some(Self { prefix: offset, entry: nop_count - offset })
3268+
}
3269+
}
3270+
pub fn prefix(&self) -> u8 {
3271+
self.prefix
3272+
}
3273+
pub fn entry(&self) -> u8 {
3274+
self.entry
3275+
}
3276+
}
3277+
32513278
/// `-Zpolonius` values, enabling the borrow checker polonius analysis, and which version: legacy,
32523279
/// or future prototype.
32533280
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]

compiler/rustc_session/src/options.rs

+29
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,8 @@ mod desc {
379379
pub const parse_passes: &str = "a space-separated list of passes, or `all`";
380380
pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
381381
pub const parse_on_broken_pipe: &str = "either `kill`, `error`, or `inherit`";
382+
pub const parse_patchable_function_entry: &str =
383+
"nop_count,entry_offset or nop_count (defaulting entry_offset=0)";
382384
pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
383385
pub const parse_oom_strategy: &str = "either `panic` or `abort`";
384386
pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
@@ -723,6 +725,7 @@ mod parse {
723725
true
724726
}
725727

728+
726729
pub(crate) fn parse_on_broken_pipe(slot: &mut OnBrokenPipe, v: Option<&str>) -> bool {
727730
match v {
728731
// OnBrokenPipe::Default can't be explicitly specified
@@ -734,6 +737,30 @@ mod parse {
734737
true
735738
}
736739

740+
pub(crate) fn parse_patchable_function_entry(
741+
slot: &mut PatchableFunctionEntry,
742+
v: Option<&str>,
743+
) -> bool {
744+
let mut nop_count = 0;
745+
let mut offset = 0;
746+
747+
if !parse_number(&mut nop_count, v) {
748+
let parts = v.and_then(|v| v.split_once(',')).unzip();
749+
if !parse_number(&mut nop_count, parts.0) {
750+
return false;
751+
}
752+
if !parse_number(&mut offset, parts.1) {
753+
return false;
754+
}
755+
}
756+
757+
if let Some(pfe) = PatchableFunctionEntry::from_nop_count_and_offset(nop_count, offset) {
758+
*slot = pfe;
759+
return true;
760+
}
761+
false
762+
}
763+
737764
pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool {
738765
match v {
739766
Some("panic") => *slot = OomStrategy::Panic,
@@ -1859,6 +1886,8 @@ options! {
18591886
"panic strategy for panics in drops"),
18601887
parse_only: bool = (false, parse_bool, [UNTRACKED],
18611888
"parse only; do not compile, assemble, or link (default: no)"),
1889+
patchable_function_entry: PatchableFunctionEntry = (PatchableFunctionEntry::default(), parse_patchable_function_entry, [TRACKED],
1890+
"nop padding at function entry"),
18621891
plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
18631892
"whether to use the PLT when calling into shared libraries;
18641893
only has effect for PIC code on systems with ELF binaries
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# `patchable-function-entry`
2+
3+
--------------------
4+
5+
The `-Z patchable-function-entry=M,N` or `-Z patchable-function-entry=M`
6+
compiler flag enables nop padding of function entries with M nops, with
7+
an offset for the entry of the function at N nops. In the second form,
8+
N defaults to 0.
9+
10+
As an illustrative example, `-Z patchable-function-entry=3,2` would produce:
11+
12+
```
13+
nop
14+
nop
15+
function_label:
16+
nop
17+
//Actual function code begins here
18+
```
19+
20+
This flag is used for hotpatching, especially in the Linux kernel. The flag
21+
arguments are modeled after hte `-fpatchable-function-entry` flag as defined
22+
for both [Clang](https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fpatchable-function-entry)
23+
and [gcc](https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fpatchable-function-entry)
24+
and is intended to provide the same effect.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// compile-flags: -Z patchable-function-entry=15,10
2+
3+
#![crate_type = "lib"]
4+
5+
#[no_mangle]
6+
pub fn foo() {}
7+
// CHECK: @foo() unnamed_addr #0
8+
// CHECK: attributes #0 = { {{.*}}"patchable-function-entry"="5"{{.*}}"patchable-function-prefix"="10" {{.*}} }

0 commit comments

Comments
 (0)