Skip to content

Commit 97f3eee

Browse files
committed
Auto merge of #55617 - oli-obk:stacker, r=nagisa,oli-obk
Prevent compiler stack overflow for deeply recursive code I was unable to write a test that 1. runs in under 1s 2. overflows on my machine without this patch The following reproduces the issue, but I don't think it's sensible to include a test that takes 30s to compile. We can now easily squash newly appearing overflows by the strategic insertion of calls to `ensure_sufficient_stack`. ```rust // compile-pass #![recursion_limit="1000000"] macro_rules! chain { (EE $e:expr) => {$e.sin()}; (RECURSE $i:ident $e:expr) => {chain!($i chain!($i chain!($i chain!($i $e))))}; (Z $e:expr) => {chain!(RECURSE EE $e)}; (Y $e:expr) => {chain!(RECURSE Z $e)}; (X $e:expr) => {chain!(RECURSE Y $e)}; (A $e:expr) => {chain!(RECURSE X $e)}; (B $e:expr) => {chain!(RECURSE A $e)}; (C $e:expr) => {chain!(RECURSE B $e)}; // causes overflow on x86_64 linux // less than 1 second until overflow on test machine // after overflow has been fixed, takes 30s to compile :/ (D $e:expr) => {chain!(RECURSE C $e)}; (E $e:expr) => {chain!(RECURSE D $e)}; (F $e:expr) => {chain!(RECURSE E $e)}; // more than 10 seconds (G $e:expr) => {chain!(RECURSE F $e)}; (H $e:expr) => {chain!(RECURSE G $e)}; (I $e:expr) => {chain!(RECURSE H $e)}; (J $e:expr) => {chain!(RECURSE I $e)}; (K $e:expr) => {chain!(RECURSE J $e)}; (L $e:expr) => {chain!(RECURSE L $e)}; } fn main() { let x = chain!(D 42.0_f32); } ``` fixes #55471 fixes #41884 fixes #40161 fixes #34844 fixes #32594 cc @alexcrichton @rust-lang/compiler I looked at all code that checks the recursion limit and inserted stack growth calls where appropriate.
2 parents 29457dd + 935a05f commit 97f3eee

File tree

16 files changed

+447
-351
lines changed

16 files changed

+447
-351
lines changed

Cargo.lock

+23
Original file line numberDiff line numberDiff line change
@@ -2639,6 +2639,15 @@ dependencies = [
26392639
"core",
26402640
]
26412641

2642+
[[package]]
2643+
name = "psm"
2644+
version = "0.1.8"
2645+
source = "registry+https://github.com/rust-lang/crates.io-index"
2646+
checksum = "659ecfea2142a458893bb7673134bad50b752fea932349c213d6a23874ce3aa7"
2647+
dependencies = [
2648+
"cc",
2649+
]
2650+
26422651
[[package]]
26432652
name = "publicsuffix"
26442653
version = "1.5.3"
@@ -3708,6 +3717,7 @@ dependencies = [
37083717
"serialize",
37093718
"smallvec 1.4.0",
37103719
"stable_deref_trait",
3720+
"stacker",
37113721
"winapi 0.3.8",
37123722
]
37133723

@@ -4669,6 +4679,19 @@ version = "1.1.0"
46694679
source = "registry+https://github.com/rust-lang/crates.io-index"
46704680
checksum = "ffbc596e092fe5f598b12ef46cc03754085ac2f4d8c739ad61c4ae266cc3b3fa"
46714681

4682+
[[package]]
4683+
name = "stacker"
4684+
version = "0.1.8"
4685+
source = "registry+https://github.com/rust-lang/crates.io-index"
4686+
checksum = "32c2467b8abbb417e4e62fd62229719b9c9d77714a7fa989f1afad16ba9c9743"
4687+
dependencies = [
4688+
"cc",
4689+
"cfg-if",
4690+
"libc",
4691+
"psm",
4692+
"winapi 0.3.8",
4693+
]
4694+
46724695
[[package]]
46734696
name = "std"
46744697
version = "0.0.0"

src/librustc_ast_lowering/expr.rs

+191-176
Large diffs are not rendered by default.

src/librustc_ast_lowering/pat.rs

+75-69
Original file line numberDiff line numberDiff line change
@@ -2,83 +2,89 @@ use super::{ImplTraitContext, LoweringContext, ParamMode};
22

33
use rustc_ast::ast::*;
44
use rustc_ast::ptr::P;
5+
use rustc_data_structures::stack::ensure_sufficient_stack;
56
use rustc_hir as hir;
67
use rustc_hir::def::Res;
78
use rustc_span::{source_map::Spanned, Span};
89

910
impl<'a, 'hir> LoweringContext<'a, 'hir> {
1011
crate fn lower_pat(&mut self, p: &Pat) -> &'hir hir::Pat<'hir> {
11-
let node = match p.kind {
12-
PatKind::Wild => hir::PatKind::Wild,
13-
PatKind::Ident(ref binding_mode, ident, ref sub) => {
14-
let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(&*s));
15-
let node = self.lower_pat_ident(p, binding_mode, ident, lower_sub);
16-
node
17-
}
18-
PatKind::Lit(ref e) => hir::PatKind::Lit(self.lower_expr(e)),
19-
PatKind::TupleStruct(ref path, ref pats) => {
20-
let qpath = self.lower_qpath(
21-
p.id,
22-
&None,
23-
path,
24-
ParamMode::Optional,
25-
ImplTraitContext::disallowed(),
26-
);
27-
let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
28-
hir::PatKind::TupleStruct(qpath, pats, ddpos)
29-
}
30-
PatKind::Or(ref pats) => {
31-
hir::PatKind::Or(self.arena.alloc_from_iter(pats.iter().map(|x| self.lower_pat(x))))
32-
}
33-
PatKind::Path(ref qself, ref path) => {
34-
let qpath = self.lower_qpath(
35-
p.id,
36-
qself,
37-
path,
38-
ParamMode::Optional,
39-
ImplTraitContext::disallowed(),
40-
);
41-
hir::PatKind::Path(qpath)
42-
}
43-
PatKind::Struct(ref path, ref fields, etc) => {
44-
let qpath = self.lower_qpath(
45-
p.id,
46-
&None,
47-
path,
48-
ParamMode::Optional,
49-
ImplTraitContext::disallowed(),
50-
);
12+
ensure_sufficient_stack(|| {
13+
let node = match p.kind {
14+
PatKind::Wild => hir::PatKind::Wild,
15+
PatKind::Ident(ref binding_mode, ident, ref sub) => {
16+
let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(&*s));
17+
let node = self.lower_pat_ident(p, binding_mode, ident, lower_sub);
18+
node
19+
}
20+
PatKind::Lit(ref e) => hir::PatKind::Lit(self.lower_expr(e)),
21+
PatKind::TupleStruct(ref path, ref pats) => {
22+
let qpath = self.lower_qpath(
23+
p.id,
24+
&None,
25+
path,
26+
ParamMode::Optional,
27+
ImplTraitContext::disallowed(),
28+
);
29+
let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
30+
hir::PatKind::TupleStruct(qpath, pats, ddpos)
31+
}
32+
PatKind::Or(ref pats) => hir::PatKind::Or(
33+
self.arena.alloc_from_iter(pats.iter().map(|x| self.lower_pat(x))),
34+
),
35+
PatKind::Path(ref qself, ref path) => {
36+
let qpath = self.lower_qpath(
37+
p.id,
38+
qself,
39+
path,
40+
ParamMode::Optional,
41+
ImplTraitContext::disallowed(),
42+
);
43+
hir::PatKind::Path(qpath)
44+
}
45+
PatKind::Struct(ref path, ref fields, etc) => {
46+
let qpath = self.lower_qpath(
47+
p.id,
48+
&None,
49+
path,
50+
ParamMode::Optional,
51+
ImplTraitContext::disallowed(),
52+
);
5153

52-
let fs = self.arena.alloc_from_iter(fields.iter().map(|f| hir::FieldPat {
53-
hir_id: self.next_id(),
54-
ident: f.ident,
55-
pat: self.lower_pat(&f.pat),
56-
is_shorthand: f.is_shorthand,
57-
span: f.span,
58-
}));
59-
hir::PatKind::Struct(qpath, fs, etc)
60-
}
61-
PatKind::Tuple(ref pats) => {
62-
let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
63-
hir::PatKind::Tuple(pats, ddpos)
64-
}
65-
PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
66-
PatKind::Ref(ref inner, mutbl) => hir::PatKind::Ref(self.lower_pat(inner), mutbl),
67-
PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range(
68-
e1.as_deref().map(|e| self.lower_expr(e)),
69-
e2.as_deref().map(|e| self.lower_expr(e)),
70-
self.lower_range_end(end, e2.is_some()),
71-
),
72-
PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
73-
PatKind::Rest => {
74-
// If we reach here the `..` pattern is not semantically allowed.
75-
self.ban_illegal_rest_pat(p.span)
76-
}
77-
PatKind::Paren(ref inner) => return self.lower_pat(inner),
78-
PatKind::MacCall(_) => panic!("Shouldn't exist here"),
79-
};
54+
let fs = self.arena.alloc_from_iter(fields.iter().map(|f| hir::FieldPat {
55+
hir_id: self.next_id(),
56+
ident: f.ident,
57+
pat: self.lower_pat(&f.pat),
58+
is_shorthand: f.is_shorthand,
59+
span: f.span,
60+
}));
61+
hir::PatKind::Struct(qpath, fs, etc)
62+
}
63+
PatKind::Tuple(ref pats) => {
64+
let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
65+
hir::PatKind::Tuple(pats, ddpos)
66+
}
67+
PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)),
68+
PatKind::Ref(ref inner, mutbl) => hir::PatKind::Ref(self.lower_pat(inner), mutbl),
69+
PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => {
70+
hir::PatKind::Range(
71+
e1.as_deref().map(|e| self.lower_expr(e)),
72+
e2.as_deref().map(|e| self.lower_expr(e)),
73+
self.lower_range_end(end, e2.is_some()),
74+
)
75+
}
76+
PatKind::Slice(ref pats) => self.lower_pat_slice(pats),
77+
PatKind::Rest => {
78+
// If we reach here the `..` pattern is not semantically allowed.
79+
self.ban_illegal_rest_pat(p.span)
80+
}
81+
// FIXME: consider not using recursion to lower this.
82+
PatKind::Paren(ref inner) => return self.lower_pat(inner),
83+
PatKind::MacCall(_) => panic!("{:?} shouldn't exist here", p.span),
84+
};
8085

81-
self.pat_with_node_id_of(p, node)
86+
self.pat_with_node_id_of(p, node)
87+
})
8288
}
8389

8490
fn lower_pat_tuple(

src/librustc_data_structures/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ rustc_index = { path = "../librustc_index", package = "rustc_index" }
2828
bitflags = "1.2.1"
2929
measureme = "0.7.1"
3030
libc = "0.2"
31+
stacker = "0.1.6"
3132

3233
[dependencies.parking_lot]
3334
version = "0.10"

src/librustc_data_structures/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ pub mod stable_set;
8080
#[macro_use]
8181
pub mod stable_hasher;
8282
pub mod sharded;
83+
pub mod stack;
8384
pub mod sync;
8485
pub mod thin_vec;
8586
pub mod tiny_list;

src/librustc_data_structures/stack.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// This is the amount of bytes that need to be left on the stack before increasing the size.
2+
// It must be at least as large as the stack required by any code that does not call
3+
// `ensure_sufficient_stack`.
4+
const RED_ZONE: usize = 100 * 1024; // 100k
5+
6+
// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then
7+
// on. This flag has performance relevant characteristics. Don't set it too high.
8+
const STACK_PER_RECURSION: usize = 1 * 1024 * 1024; // 1MB
9+
10+
/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations
11+
/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit
12+
/// from this.
13+
///
14+
/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.
15+
pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
16+
stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)
17+
}

src/librustc_interface/util.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,7 @@ pub fn create_session(
8181
(Lrc::new(sess), Lrc::new(codegen_backend), source_map)
8282
}
8383

84-
// Temporarily have stack size set to 32MB to deal with various crates with long method
85-
// chains or deep syntax trees, except when on Haiku.
86-
// FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
87-
#[cfg(not(target_os = "haiku"))]
88-
const STACK_SIZE: usize = 32 * 1024 * 1024;
89-
90-
#[cfg(target_os = "haiku")]
91-
const STACK_SIZE: usize = 16 * 1024 * 1024;
84+
const STACK_SIZE: usize = 8 * 1024 * 1024;
9285

9386
fn get_stack_size() -> Option<usize> {
9487
// FIXME: Hacks on hacks. If the env is trying to override the stack size

src/librustc_middle/ty/inhabitedness/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::ty::TyKind::*;
66
use crate::ty::{AdtDef, FieldDef, Ty, TyS, VariantDef};
77
use crate::ty::{AdtKind, Visibility};
88
use crate::ty::{DefId, SubstsRef};
9+
use rustc_data_structures::stack::ensure_sufficient_stack;
910

1011
mod def_id_forest;
1112

@@ -196,7 +197,9 @@ impl<'tcx> TyS<'tcx> {
196197
/// Calculates the forest of `DefId`s from which this type is visibly uninhabited.
197198
fn uninhabited_from(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> DefIdForest {
198199
match self.kind {
199-
Adt(def, substs) => def.uninhabited_from(tcx, substs, param_env),
200+
Adt(def, substs) => {
201+
ensure_sufficient_stack(|| def.uninhabited_from(tcx, substs, param_env))
202+
}
200203

201204
Never => DefIdForest::full(tcx),
202205

src/librustc_middle/ty/query/plumbing.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ impl QueryContext for TyCtxt<'tcx> {
6868
};
6969

7070
// Use the `ImplicitCtxt` while we execute the query.
71-
tls::enter_context(&new_icx, |_| compute(*self))
71+
tls::enter_context(&new_icx, |_| {
72+
rustc_data_structures::stack::ensure_sufficient_stack(|| compute(*self))
73+
})
7274
})
7375
}
7476
}

src/librustc_mir/monomorphize/collector.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,9 @@ fn collect_items_rec<'tcx>(
369369
recursion_depth_reset = Some(check_recursion_limit(tcx, instance, recursion_depths));
370370
check_type_length_limit(tcx, instance);
371371

372-
collect_neighbours(tcx, instance, &mut neighbors);
372+
rustc_data_structures::stack::ensure_sufficient_stack(|| {
373+
collect_neighbours(tcx, instance, &mut neighbors);
374+
});
373375
}
374376
MonoItem::GlobalAsm(..) => {
375377
recursion_depth_reset = None;
@@ -1146,7 +1148,9 @@ fn collect_miri<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut Vec<Mon
11461148
Some(GlobalAlloc::Memory(alloc)) => {
11471149
trace!("collecting {:?} with {:#?}", alloc_id, alloc);
11481150
for &((), inner) in alloc.relocations().values() {
1149-
collect_miri(tcx, inner, output);
1151+
rustc_data_structures::stack::ensure_sufficient_stack(|| {
1152+
collect_miri(tcx, inner, output);
1153+
});
11501154
}
11511155
}
11521156
Some(GlobalAlloc::Function(fn_instance)) => {

src/librustc_mir_build/build/expr/as_temp.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use crate::build::scope::DropKind;
44
use crate::build::{BlockAnd, BlockAndExtension, Builder};
55
use crate::hair::*;
6+
use rustc_data_structures::stack::ensure_sufficient_stack;
67
use rustc_hir as hir;
78
use rustc_middle::middle::region;
89
use rustc_middle::mir::*;
@@ -21,7 +22,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
2122
M: Mirror<'tcx, Output = Expr<'tcx>>,
2223
{
2324
let expr = self.hir.mirror(expr);
24-
self.expr_as_temp(block, temp_lifetime, expr, mutability)
25+
//
26+
// this is the only place in mir building that we need to truly need to worry about
27+
// infinite recursion. Everything else does recurse, too, but it always gets broken up
28+
// at some point by inserting an intermediate temporary
29+
ensure_sufficient_stack(|| self.expr_as_temp(block, temp_lifetime, expr, mutability))
2530
}
2631

2732
fn expr_as_temp(

src/librustc_trait_selection/traits/project.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
1818
use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
1919
use crate::traits::error_reporting::InferCtxtExt;
2020
use rustc_ast::ast::Ident;
21+
use rustc_data_structures::stack::ensure_sufficient_stack;
2122
use rustc_errors::ErrorReported;
2223
use rustc_hir::def_id::DefId;
2324
use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
@@ -261,7 +262,7 @@ where
261262
{
262263
debug!("normalize_with_depth(depth={}, value={:?})", depth, value);
263264
let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations);
264-
let result = normalizer.fold(value);
265+
let result = ensure_sufficient_stack(|| normalizer.fold(value));
265266
debug!(
266267
"normalize_with_depth: depth={} result={:?} with {} obligations",
267268
depth,

src/librustc_trait_selection/traits/query/normalize.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::infer::canonical::OriginalQueryValues;
77
use crate::infer::{InferCtxt, InferOk};
88
use crate::traits::error_reporting::InferCtxtExt;
99
use crate::traits::{Obligation, ObligationCause, PredicateObligation, Reveal};
10+
use rustc_data_structures::stack::ensure_sufficient_stack;
1011
use rustc_infer::traits::Normalized;
1112
use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
1213
use rustc_middle::ty::subst::Subst;
@@ -131,7 +132,7 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for QueryNormalizer<'cx, 'tcx> {
131132
ty
132133
);
133134
}
134-
let folded_ty = self.fold_ty(concrete_ty);
135+
let folded_ty = ensure_sufficient_stack(|| self.fold_ty(concrete_ty));
135136
self.anon_depth -= 1;
136137
folded_ty
137138
}

0 commit comments

Comments
 (0)