Skip to content

Commit 26edcee

Browse files
oli-obkmati865
authored andcommitted
Prevent stack overflow for deeply recursive code
1 parent 7184d13 commit 26edcee

File tree

14 files changed

+445
-351
lines changed

14 files changed

+445
-351
lines changed

Cargo.lock

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2630,6 +2630,15 @@ dependencies = [
26302630
"core",
26312631
]
26322632

2633+
[[package]]
2634+
name = "psm"
2635+
version = "0.1.6"
2636+
source = "registry+https://github.com/rust-lang/crates.io-index"
2637+
checksum = "b14fc68b454f875abc8354c2555e1d56596f74833ddc0f77f87f4871ed6a30e0"
2638+
dependencies = [
2639+
"cc",
2640+
]
2641+
26332642
[[package]]
26342643
name = "publicsuffix"
26352644
version = "1.5.3"
@@ -3152,6 +3161,7 @@ checksum = "81dfcfbb0ddfd533abf8c076e3b49d1e5042d1962526a12ce2c66d514b24cca3"
31523161
dependencies = [
31533162
"rustc-ap-rustc_data_structures",
31543163
"smallvec 1.0.0",
3164+
"stacker",
31553165
]
31563166

31573167
[[package]]
@@ -4657,6 +4667,19 @@ version = "1.1.0"
46574667
source = "registry+https://github.com/rust-lang/crates.io-index"
46584668
checksum = "ffbc596e092fe5f598b12ef46cc03754085ac2f4d8c739ad61c4ae266cc3b3fa"
46594669

4670+
[[package]]
4671+
name = "stacker"
4672+
version = "0.1.6"
4673+
source = "registry+https://github.com/rust-lang/crates.io-index"
4674+
checksum = "d96fc4f13a0ac088e9a3cd9af1cc8c5cc1ab5deb2145cef661267dfc9c542f8a"
4675+
dependencies = [
4676+
"cc",
4677+
"cfg-if",
4678+
"libc",
4679+
"psm",
4680+
"winapi 0.3.8",
4681+
]
4682+
46604683
[[package]]
46614684
name = "std"
46624685
version = "0.0.0"

src/librustc_ast_lowering/expr.rs

Lines changed: 191 additions & 176 deletions
Large diffs are not rendered by default.

src/librustc_ast_lowering/pat.rs

Lines changed: 75 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -4,81 +4,87 @@ use rustc_ast::ast::*;
44
use rustc_ast::ptr::P;
55
use rustc_hir as hir;
66
use rustc_hir::def::Res;
7+
use rustc_middle::limits::ensure_sufficient_stack;
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_interface/util.rs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,7 @@ pub fn create_session(
8080
(Lrc::new(sess), Lrc::new(codegen_backend), source_map)
8181
}
8282

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

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

src/librustc_middle/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ byteorder = { version = "1.3" }
3434
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
3535
measureme = "0.7.1"
3636
rustc_session = { path = "../librustc_session" }
37+
stacker = "0.1.6"

src/librustc_middle/middle/limits.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,24 @@ use rustc_span::symbol::{sym, Symbol};
1313

1414
use std::num::IntErrorKind;
1515

16+
// This is the amount of bytes that need to be left on the stack before increasing the size.
17+
// It must be at least as large as the stack required by any code that does not call
18+
// `ensure_sufficient_stack`.
19+
const RED_ZONE: usize = 100 * 1024; // 100k
20+
21+
// Ony the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then
22+
// on. This flag has performance relevant characteristics. Don't set it too high.
23+
const STACK_PER_RECURSION: usize = 1 * 1024 * 1024; // 1MB
24+
25+
/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations
26+
/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit
27+
/// from this.
28+
///
29+
/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.
30+
pub fn ensure_sufficient_stack<R, F: FnOnce() -> R>(f: F) -> R {
31+
stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)
32+
}
33+
1634
pub fn update_limits(sess: &Session, krate: &ast::Crate) {
1735
update_limit(sess, krate, &sess.recursion_limit, sym::recursion_limit, 128);
1836
update_limit(sess, krate, &sess.type_length_limit, sym::type_length_limit, 1048576);

src/librustc_middle/ty/inhabitedness/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub use self::def_id_forest::DefIdForest;
22

3+
use crate::middle::limits::ensure_sufficient_stack;
34
use crate::ty;
45
use crate::ty::context::TyCtxt;
56
use crate::ty::TyKind::*;
@@ -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

Lines changed: 3 additions & 1 deletion
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+
crate::middle::limits::ensure_sufficient_stack(|| compute(*self))
73+
})
7274
})
7375
}
7476
}

src/librustc_mir/monomorphize/collector.rs

Lines changed: 6 additions & 2 deletions
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::middle::limits::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_middle::limits::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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::build::scope::DropKind;
44
use crate::build::{BlockAnd, BlockAndExtension, Builder};
55
use crate::hair::*;
66
use rustc_hir as hir;
7+
use rustc_middle::limits::ensure_sufficient_stack;
78
use rustc_middle::middle::region;
89
use rustc_middle::mir::*;
910

@@ -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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::traits::error_reporting::InferCtxtExt;
2020
use rustc_ast::ast::Ident;
2121
use rustc_errors::ErrorReported;
2222
use rustc_hir::def_id::DefId;
23+
use rustc_middle::limits::ensure_sufficient_stack;
2324
use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
2425
use rustc_middle::ty::subst::{InternalSubsts, Subst};
2526
use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
@@ -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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::infer::{InferCtxt, InferOk};
88
use crate::traits::error_reporting::InferCtxtExt;
99
use crate::traits::{Obligation, ObligationCause, PredicateObligation, Reveal};
1010
use rustc_infer::traits::Normalized;
11+
use rustc_middle::limits::ensure_sufficient_stack;
1112
use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
1213
use rustc_middle::ty::subst::Subst;
1314
use rustc_middle::ty::{self, Ty, TyCtxt};
@@ -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)