Skip to content

Commit 3bf0b57

Browse files
committed
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 ff2c563 commit 3bf0b57

File tree

7 files changed

+140
-3
lines changed

7 files changed

+140
-3
lines changed

compiler/rustc_codegen_llvm/src/attributes.rs

Lines changed: 26 additions & 0 deletions
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>(
@@ -422,6 +447,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
422447
llvm::set_alignment(llfn, align as usize);
423448
}
424449
to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
450+
to_add.extend(patchable_function_entry_attrs(cx));
425451

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

compiler/rustc_interface/src/tests.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,7 @@ fn test_unstable_options_tracking_hash() {
791791
tracked!(packed_bundled_libs, true);
792792
tracked!(panic_abort_tests, true);
793793
tracked!(panic_in_drop, PanicStrategy::Abort);
794+
tracked!(patchable_function_entry, PatchableFunctionEntry::from_nop_count_and_offset(3, 4));
794795
tracked!(plt, Some(true));
795796
tracked!(polonius, Polonius::Legacy);
796797
tracked!(precise_enum_drop_elaboration, false);

compiler/rustc_middle/src/middle/codegen_fn_attrs.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ pub struct CodegenFnAttrs {
4545
pub alignment: Option<u32>,
4646
}
4747

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

compiler/rustc_session/src/config.rs

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3221,9 +3221,9 @@ pub(crate) mod dep_tracking {
32213221
BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, DebugInfoCompression,
32223222
ErrorOutputType, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay,
32233223
LinkerPluginLto, LocationDetail, LtoCli, OomStrategy, OptLevel, OutFileName, OutputType,
3224-
OutputTypes, Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
3225-
SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, TraitSolver, TrimmedDefPaths,
3226-
WasiExecModel,
3224+
OutputTypes, PatchableFunctionEntry, Polonius, RemapPathScopeComponents, ResolveDocLinks,
3225+
SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion,
3226+
TraitSolver, TrimmedDefPaths, WasiExecModel,
32273227
};
32283228
use crate::lint;
32293229
use crate::utils::NativeLib;
@@ -3327,6 +3327,7 @@ pub(crate) mod dep_tracking {
33273327
OomStrategy,
33283328
LanguageIdentifier,
33293329
TraitSolver,
3330+
PatchableFunctionEntry,
33303331
Polonius,
33313332
InliningThreshold,
33323333
FunctionReturn,
@@ -3484,6 +3485,32 @@ impl DumpMonoStatsFormat {
34843485
}
34853486
}
34863487

3488+
/// `-Z patchable-function-entry` representation - how many nops to put before and after function
3489+
/// entry.
3490+
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]
3491+
pub struct PatchableFunctionEntry {
3492+
/// Nops before the entry
3493+
prefix: u8,
3494+
/// Nops after the entry
3495+
entry: u8,
3496+
}
3497+
3498+
impl PatchableFunctionEntry {
3499+
pub fn from_nop_count_and_offset(nop_count: u8, offset: u8) -> Option<PatchableFunctionEntry> {
3500+
if nop_count < offset {
3501+
None
3502+
} else {
3503+
Some(Self { prefix: offset, entry: nop_count - offset })
3504+
}
3505+
}
3506+
pub fn prefix(&self) -> u8 {
3507+
self.prefix
3508+
}
3509+
pub fn entry(&self) -> u8 {
3510+
self.entry
3511+
}
3512+
}
3513+
34873514
/// `-Zpolonius` values, enabling the borrow checker polonius analysis, and which version: legacy,
34883515
/// or future prototype.
34893516
#[derive(Clone, Copy, PartialEq, Hash, Debug, Default)]

compiler/rustc_session/src/options.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,8 @@ mod desc {
376376
pub const parse_time_passes_format: &str = "`text` (default) or `json`";
377377
pub const parse_passes: &str = "a space-separated list of passes, or `all`";
378378
pub const parse_panic_strategy: &str = "either `unwind` or `abort`";
379+
pub const parse_patchable_function_entry: &str =
380+
"nop_count,entry_offset or nop_count (defaulting entry_offset=0)";
379381
pub const parse_opt_panic_strategy: &str = parse_panic_strategy;
380382
pub const parse_oom_strategy: &str = "either `panic` or `abort`";
381383
pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`";
@@ -691,6 +693,30 @@ mod parse {
691693
true
692694
}
693695

696+
pub(crate) fn parse_patchable_function_entry(
697+
slot: &mut PatchableFunctionEntry,
698+
v: Option<&str>,
699+
) -> bool {
700+
let mut nop_count = 0;
701+
let mut offset = 0;
702+
703+
if !parse_number(&mut nop_count, v) {
704+
let parts = v.and_then(|v| v.split_once(',')).unzip();
705+
if !parse_number(&mut nop_count, parts.0) {
706+
return false;
707+
}
708+
if !parse_number(&mut offset, parts.1) {
709+
return false;
710+
}
711+
}
712+
713+
if let Some(pfe) = PatchableFunctionEntry::from_nop_count_and_offset(nop_count, offset) {
714+
*slot = pfe;
715+
return true;
716+
}
717+
false
718+
}
719+
694720
pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool {
695721
match v {
696722
Some("panic") => *slot = OomStrategy::Panic,
@@ -1758,6 +1784,8 @@ options! {
17581784
"panic strategy for panics in drops"),
17591785
parse_only: bool = (false, parse_bool, [UNTRACKED],
17601786
"parse only; do not compile, assemble, or link (default: no)"),
1787+
patchable_function_entry: PatchableFunctionEntry = (PatchableFunctionEntry::default(), parse_patchable_function_entry, [TRACKED],
1788+
"nop padding at function entry"),
17611789
plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
17621790
"whether to use the PLT when calling into shared libraries;
17631791
only has effect for PIC code on systems with ELF binaries
Lines changed: 24 additions & 0 deletions
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.
Lines changed: 8 additions & 0 deletions
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)