Skip to content

Commit cb00398

Browse files
author
Ariel Ben-Yehuda
committed
Stabilize -Zstack-protector as -Cstack-protector
I propose stabilizing `-Cstack-protector` as `-Zstack-protector`. This PR adds a new `-Cstack-protector` flag, leaving the unstable `-Z` flag as is to ease the transition period. The `-Z` flag will be removed in the future. No RFC/MCP, this flag was added in 84197 and was not deemed large enough to require additional process. The tracking issue for this feature is 114903. The `-Cstack-protector=strong` mode uses the same underlying heuristics as Clang's `-fstack-protector-strong`. These heuristics weren't designed for Rust, and may be over-conservative in some cases - for example, if Rust stores a field's data in an alloca using an LLVM array type, LLVM regard the alloca as meaning that the function has a C array, and enable stack overflow canaries even if the function accesses the alloca in a safe way. Some people thought we should wait on stabilization until there are better heuristics, but I didn't hear about any concrete case where this unduly harms performance, and I think that when a need comes, we can improve the heuristics in LLVM after stabilization. The heuristics do seem to not be under-conservative, so this should not be a security risk. The `-Cstack-protector=basic` mode (`-fstack-protector`) uses heuristics that are specifically designed to catch old-C-style string manipulation. This is not a good fit to Rust, which does not perform much unsafe C-style string manipulation. As far as I can tell, nobody has been asking for it, and few people are using it even in today's C - modern distros (e.g. [Debian]) tend to use `-fstack-protector-strong`. Therefore, `-Cstack-protector=basic` has been **removed**. If anyone is interested in it, they are welcome to add it back as an unstable option. [Debian]: https://wiki.debian.org/Hardening#DEB_BUILD_HARDENING_STACKPROTECTOR_.28gcc.2Fg.2B-.2B-_-fstack-protector-strong.29 Most implementation was done in <#84197>. The command-line attribute enables the relevant LLVM attribute on all functions in <https://github.com/rust-lang/rust/blob/68baa87ba6f03f8b6af2a368690161f1601e4040/compiler/rustc_codegen_llvm/src/attributes.rs#L267-L276>. Each target can indicate that it does not support stack canaries - currently, the GPU platforms `nvptx64-nvidia-cuda` and `amdgcn-amd-amdhsa`. On these platforms, use of `-Cstack-protector` causes an error. The feature has tests that make sure that the LLVM heuristic gives reasonable results for several functions, by checking for `__security_check_cookie` (on Windows) or `__stack_chk_fail` (on Linux). See <https://github.com/rust-lang/rust/tree/68baa87ba6f03f8b6af2a368690161f1601e4040/tests/assembly-llvm/stack-protector> No call-for-testing has been conducted, but the feature seems to be in use. No reported bugs seem to exist. - bbjornse was the original implementor at 84197 - mrcnski documented it at 111722 - wesleywiser added tests for Windows at 116037 - davidtwco worked on the feature at 121742 - nikic provided support from the LLVM side (on Zulip on <https://rust-lang.zulipchat.com/#narrow/channel/233931-t-compiler.2Fmajor-changes/topic/Proposal.20for.20Adapt.20Stack.20Protector.20for.20Ru.E2.80.A6.20compiler-team.23841> and elsewhere), thanks nikic! No FIXMEs related to this feature. This feature cannot cause undefined behavior. No changes to reference/spec, docs added to the codegen docs as part of the stabilization PR. No. None. No support needed for rustdoc, clippy, rust-analyzer, rustfmt or rustup. Cargo could expose this as an option in build profiles but I would expect the decision as to what version should be used would be made for the entire crate graph at build time rather than by individual package authors. `-C stack-protector` is propagated to C compilers using cc-rs via rust-lang/cc-rs issue 1550
1 parent 0006519 commit cb00398

30 files changed

Lines changed: 195 additions & 178 deletions

bootstrap.example.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -760,10 +760,9 @@
760760
#rust.frame-pointers = false
761761

762762
# Indicates whether stack protectors should be used
763-
# via the unstable option `-Zstack-protector`.
763+
# via `-Cstack-protector`.
764764
#
765-
# Valid options are : `none`(default),`basic`,`strong`, or `all`.
766-
# `strong` and `basic` options may be buggy and are not recommended, see rust-lang/rust#114903.
765+
# Valid options are : `none`(default), `strong`, or `all`.
767766
#rust.stack-protector = "none"
768767

769768
# Prints each test name as it is executed, to help debug issues in the test harness itself.

compiler/rustc_codegen_llvm/src/attributes.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,6 @@ fn stackprotector_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll A
297297
StackProtector::None => return None,
298298
StackProtector::All => AttributeKind::StackProtectReq,
299299
StackProtector::Strong => AttributeKind::StackProtectStrong,
300-
StackProtector::Basic => AttributeKind::StackProtect,
301300
};
302301

303302
Some(sspattr.create_attr(cx.llcx))

compiler/rustc_codegen_llvm/src/lib.rs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -279,18 +279,19 @@ impl CodegenBackend for LlvmCodegenBackend {
279279
Generate stack canaries in all functions.
280280
281281
strong
282-
Generate stack canaries in a function if it either:
283-
- has a local variable of `[T; N]` type, regardless of `T` and `N`
284-
- takes the address of a local variable.
285-
286-
(Note that a local variable being borrowed is not equivalent to its
287-
address being taken: e.g. some borrows may be removed by optimization,
288-
while by-value argument passing may be implemented with reference to a
289-
local stack variable in the ABI.)
290-
291-
basic
292-
Generate stack canaries in functions with local variables of `[T; N]`
293-
type, where `T` is byte-sized and `N` >= 8.
282+
Generate stack canaries for all functions, unless the compiler
283+
can prove these functions can't be the source of a stack
284+
buffer overflow (even in the presence of undefined behavior).
285+
286+
This provides similar security guarantees to Clang's
287+
`-fstack-protector-strong`.
288+
289+
The exact rules are unstable and subject to change, but
290+
currently, it generates stack protectors for functions that,
291+
*post-optimization*, contain LLVM allocas (which
292+
include all stack allocations - including fixed-size
293+
allocations - that are used in a way that is not completely
294+
determined by static control flow).
294295
295296
none
296297
Do not generate stack canaries.

compiler/rustc_interface/src/tests.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,7 @@ fn test_codegen_options_tracking_hash() {
638638
tracked!(relocation_model, Some(RelocModel::Pic));
639639
tracked!(relro_level, Some(RelroLevel::Full));
640640
tracked!(split_debuginfo, Some(SplitDebuginfo::Packed));
641+
tracked!(stack_protector, Some(StackProtector::All));
641642
tracked!(symbol_mangling_version, Some(SymbolManglingVersion::V0));
642643
tracked!(target_cpu, Some(String::from("abc")));
643644
tracked!(target_feature, String::from("all the features, all of them"));
@@ -868,7 +869,7 @@ fn test_unstable_options_tracking_hash() {
868869
tracked!(small_data_threshold, Some(16));
869870
tracked!(split_lto_unit, Some(true));
870871
tracked!(src_hash_algorithm, Some(SourceFileHashAlgorithm::Sha1));
871-
tracked!(stack_protector, StackProtector::All);
872+
tracked!(stack_protector, Some(StackProtector::All));
872873
tracked!(teach, true);
873874
tracked!(thinlto, Some(true));
874875
tracked!(tiny_const_eval_limit, true);

compiler/rustc_session/src/errors.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ pub(crate) struct EmbedSourceRequiresDebugInfo;
206206

207207
#[derive(Diagnostic)]
208208
#[diag(
209-
"`-Z stack-protector={$stack_protector}` is not supported for target {$target_triple} and will be ignored"
209+
"`-C stack-protector={$stack_protector}` is not supported for target {$target_triple} and will be ignored"
210210
)]
211211
pub(crate) struct StackProtectorNotSupportedForTarget<'a> {
212212
pub(crate) stack_protector: StackProtector,

compiler/rustc_session/src/options.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -932,8 +932,7 @@ mod desc {
932932
pub(crate) const parse_polonius: &str = "either no value or `legacy` (the default), or `next`";
933933
pub(crate) const parse_annotate_moves: &str =
934934
"either a boolean (`yes`, `no`, `on`, `off`, etc.), or a size limit in bytes";
935-
pub(crate) const parse_stack_protector: &str =
936-
"one of (`none` (default), `basic`, `strong`, or `all`)";
935+
pub(crate) const parse_stack_protector: &str = "one of (`none` (default), `strong`, or `all`)";
937936
pub(crate) const parse_branch_protection: &str = "a `,` separated combination of `bti`, `gcs`, `pac-ret`, (optionally with `pc`, `b-key`, `leaf` if `pac-ret` is set)";
938937
pub(crate) const parse_proc_macro_execution_strategy: &str =
939938
"one of supported execution strategies (`same-thread`, or `cross-thread`)";
@@ -1959,9 +1958,12 @@ pub mod parse {
19591958
true
19601959
}
19611960

1962-
pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1961+
pub(crate) fn parse_stack_protector(
1962+
slot: &mut Option<StackProtector>,
1963+
v: Option<&str>,
1964+
) -> bool {
19631965
match v.and_then(|s| StackProtector::from_str(s).ok()) {
1964-
Some(ssp) => *slot = ssp,
1966+
Some(ssp) => *slot = Some(ssp),
19651967
_ => return false,
19661968
}
19671969
true
@@ -2269,6 +2271,9 @@ options! {
22692271
#[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
22702272
split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
22712273
"how to handle split-debuginfo, a platform-specific option"),
2274+
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2275+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED MITIGATION],
2276+
"control stack smashing protection strategy (`rustc --print stack-protector-strategies` for details)"),
22722277
strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
22732278
"tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
22742279
symbol_mangling_version: Option<SymbolManglingVersion> = (None,
@@ -2760,8 +2765,8 @@ written to standard error output)"),
27602765
src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
27612766
"hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
27622767
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2763-
stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED MITIGATION],
2764-
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
2768+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED MITIGATION],
2769+
"control stack smashing protection strategy (`rustc --print stack-protector-strategies` for details)"),
27652770
staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
27662771
"allow staticlibs to have rust dylib dependencies"),
27672772
staticlib_prefer_dynamic: bool = (false, parse_bool, [TRACKED],

compiler/rustc_session/src/options/mitigation_coverage.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ impl DeniedPartialMitigationLevel {
2020
pub fn level_str(&self) -> &'static str {
2121
match self {
2222
DeniedPartialMitigationLevel::StackProtector(StackProtector::All) => "=all",
23-
DeniedPartialMitigationLevel::StackProtector(StackProtector::Basic) => "=basic",
2423
DeniedPartialMitigationLevel::StackProtector(StackProtector::Strong) => "=strong",
2524
// currently `=disabled` should not appear
2625
DeniedPartialMitigationLevel::Enabled(false) => "=disabled",
@@ -36,9 +35,6 @@ impl std::fmt::Display for DeniedPartialMitigationLevel {
3635
DeniedPartialMitigationLevel::StackProtector(StackProtector::All) => {
3736
write!(f, "all")
3837
}
39-
DeniedPartialMitigationLevel::StackProtector(StackProtector::Basic) => {
40-
write!(f, "basic")
41-
}
4238
DeniedPartialMitigationLevel::StackProtector(StackProtector::Strong) => {
4339
write!(f, "strong")
4440
}

compiler/rustc_session/src/session.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -748,11 +748,12 @@ impl Session {
748748
}
749749

750750
pub fn stack_protector(&self) -> StackProtector {
751-
if self.target.options.supports_stack_protector {
752-
self.opts.unstable_opts.stack_protector
753-
} else {
754-
StackProtector::None
755-
}
751+
// -C stack-protector overwrites -Z stack-protector, default to StackProtector::None
752+
self.opts
753+
.cg
754+
.stack_protector
755+
.or(self.opts.unstable_opts.stack_protector)
756+
.unwrap_or(StackProtector::None)
756757
}
757758

758759
pub fn must_emit_unwind_tables(&self) -> bool {
@@ -1262,10 +1263,10 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
12621263
}
12631264
}
12641265

1265-
if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1266+
if sess.stack_protector() != StackProtector::None {
12661267
if !sess.target.options.supports_stack_protector {
1267-
sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1268-
stack_protector: sess.opts.unstable_opts.stack_protector,
1268+
sess.dcx().emit_err(errors::StackProtectorNotSupportedForTarget {
1269+
stack_protector: sess.stack_protector(),
12691270
target_triple: &sess.opts.target_triple,
12701271
});
12711272
}

compiler/rustc_target/src/spec/mod.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,12 +1352,6 @@ crate::target_spec_enum! {
13521352
/// Disable stack canary generation.
13531353
None = "none",
13541354

1355-
/// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
1356-
/// llvm/docs/LangRef.rst). This triggers stack canary generation in
1357-
/// functions which contain an array of a byte-sized type with more than
1358-
/// eight elements.
1359-
Basic = "basic",
1360-
13611355
/// On LLVM, mark all generated LLVM functions with the `sspstrong`
13621356
/// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
13631357
/// generation in functions which either contain an array, or which take

src/bootstrap/src/core/builder/cargo.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -972,7 +972,7 @@ impl Builder<'_> {
972972
cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
973973

974974
if let Some(stack_protector) = &self.config.rust_stack_protector {
975-
rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
975+
rustflags.arg(&format!("-Cstack-protector={stack_protector}"));
976976
}
977977

978978
let debuginfo_level = match mode {

0 commit comments

Comments
 (0)