Skip to content

Commit ca34f91

Browse files
authored
Merge pull request #1537 from Nadrieril/catch-panics
Catch panics during transformations
2 parents 1294b25 + fdb69b1 commit ca34f91

6 files changed

Lines changed: 83 additions & 38 deletions

File tree

‎charon/src/errors.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,8 @@ impl ErrorCtx {
241241
pub fn has_errors(&self) -> bool {
242242
self.error_count > 0
243243
}
244-
pub fn item_has_errors(&self, id: ItemId) -> bool {
245-
self.items_with_errors.contains(&id)
244+
pub fn item_has_errors(&self, id: impl Into<ItemId>) -> bool {
245+
self.items_with_errors.contains(&id.into())
246246
}
247247

248248
/// Report an error without registering anything.

‎charon/src/transform/ctx.rs‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::formatter::{FmtCtx, IntoFormatter};
44
use crate::llbc_ast;
55
use crate::options::TranslateOptions;
66
use crate::pretty::FmtWithCtx;
7+
use crate::register_error;
78
use crate::transform::CowBox;
89
use crate::ullbc_ast;
910
use std::cell::RefCell;
@@ -121,24 +122,29 @@ impl TransformCtx {
121122
self.options.opacity_for_name(&self.translated, name)
122123
}
123124

124-
pub(crate) fn with_def_id<F, T>(
125+
/// Run an item transformation with its error context, reporting any panic on that item.
126+
pub(crate) fn with_def_id(
125127
&mut self,
126128
def_id: impl Into<ItemId>,
127129
def_id_is_local: bool,
128-
f: F,
129-
) -> T
130-
where
131-
F: FnOnce(&mut Self) -> T,
132-
{
130+
span: Span,
131+
f: impl FnOnce(&mut Self),
132+
) {
133+
let def_id = def_id.into();
133134
let mut errors = self.errors.borrow_mut();
134-
let current_def_id = errors.def_id.replace(def_id.into());
135+
let current_def_id = errors.def_id.replace(def_id);
135136
let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id_is_local);
136137
drop(errors); // important: release the refcell "lock"
137-
let ret = f(self);
138+
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))).is_err() {
139+
register_error!(
140+
self,
141+
span,
142+
"Thread panicked while transforming item `{def_id:?}`."
143+
);
144+
}
138145
let mut errors = self.errors.borrow_mut();
139146
errors.def_id = current_def_id;
140147
errors.def_id_is_local = current_def_id_is_local;
141-
ret
142148
}
143149

144150
/// Mutably iterate over the bodies.
@@ -153,8 +159,11 @@ impl TransformCtx {
153159
let mut body = mem::replace(&mut decl.body, Body::Opaque);
154160
let fun_decl_id = decl.def_id;
155161
let is_local = decl.item_meta.is_local;
156-
self.with_def_id(fun_decl_id, is_local, |ctx| f(ctx, &mut body));
157-
self.translated.fun_decls[id].body = body;
162+
let span = decl.item_meta.span;
163+
self.with_def_id(fun_decl_id, is_local, span, |ctx| f(ctx, &mut body));
164+
let decl = &mut self.translated.fun_decls[id];
165+
decl.body = body;
166+
decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(fun_decl_id);
158167
}
159168
}
160169
}
@@ -168,7 +177,9 @@ impl TransformCtx {
168177
if let Some(mut decl) = self.translated.fun_decls.remove(id) {
169178
let fun_decl_id = decl.def_id;
170179
let is_local = decl.item_meta.is_local;
171-
self.with_def_id(fun_decl_id, is_local, |ctx| f(ctx, &mut decl));
180+
let span = decl.item_meta.span;
181+
self.with_def_id(fun_decl_id, is_local, span, |ctx| f(ctx, &mut decl));
182+
decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(fun_decl_id);
172183
self.translated.fun_decls.set_slot(id, decl);
173184
}
174185
}
@@ -183,7 +194,9 @@ impl TransformCtx {
183194
if let Some(mut decl) = self.translated.type_decls.remove(id) {
184195
let type_decl_id = decl.def_id;
185196
let is_local = decl.item_meta.is_local;
186-
self.with_def_id(type_decl_id, is_local, |ctx| f(ctx, &mut decl));
197+
let span = decl.item_meta.span;
198+
self.with_def_id(type_decl_id, is_local, span, |ctx| f(ctx, &mut decl));
199+
decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(type_decl_id);
187200
self.translated.type_decls.set_slot(id, decl);
188201
}
189202
}
@@ -195,10 +208,9 @@ impl TransformCtx {
195208
for id in self.translated.all_ids() {
196209
if let Some(mut decl) = self.translated.remove_item_temporarily(id) {
197210
let is_local = decl.as_ref().item_meta().is_local;
198-
self.with_def_id(id, is_local, |ctx| f(ctx, decl.as_mut()));
199-
if self.errors.borrow().item_has_errors(id) {
200-
decl.as_mut().item_meta().has_errors = true;
201-
}
211+
let span = decl.as_ref().item_meta().span;
212+
self.with_def_id(id, is_local, span, |ctx| f(ctx, decl.as_mut()));
213+
decl.as_mut().item_meta().has_errors |= self.errors.borrow().item_has_errors(id);
202214
self.translated.put_item_back(id, decl);
203215
}
204216
}

‎charon/src/transform/normalize/expand_associated_types.rs‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ use crate::{
7979
ids::IndexMap,
8080
pretty::FmtWithCtx,
8181
register_error,
82-
utils::{CycleDetector, ensure_sufficient_stack},
82+
utils::{CycleDetector, StackDepthLimitExceeded, try_ensure_sufficient_stack},
8383
};
8484

8585
use crate::transform::{TransformCtx, ctx::TransformPass, utils::GenericsSource};
@@ -972,7 +972,6 @@ impl<'a> ComputeItemModifications<'a> {
972972
/// The tricky part is that to update `GenericArgs` that apply to traits, we need to know the
973973
/// `TraitRef` they apply to in order to get the values of the appropriate types. To do this,
974974
/// `visit_generic_args` will skip `GenericArgs` meant for traits, and we must manually catch
975-
#[derive(Visitor)]
976975
struct UpdateItemBody<'a> {
977976
/// Warning: we keep the ctx around but we can't meaningfully use it for inspecting items as we
978977
/// remporarily remove them for in-place modification.
@@ -985,6 +984,10 @@ struct UpdateItemBody<'a> {
985984
type_replacements: BindingStack<TypeConstraintSet>,
986985
}
987986

987+
impl Visitor for UpdateItemBody<'_> {
988+
type Break = StackDepthLimitExceeded;
989+
}
990+
988991
impl UpdateItemBody<'_> {
989992
fn under_binder<R>(&mut self, repls: TypeConstraintSet, f: impl FnOnce(&mut Self) -> R) -> R {
990993
self.type_replacements.push(repls);
@@ -1405,7 +1408,7 @@ impl VisitAstMut for UpdateItemBody<'_> {
14051408

14061409
// Normalize associated types.
14071410
fn visit_ty_kind(&mut self, kind: &mut TyKind) -> ControlFlow<Self::Break> {
1408-
ensure_sufficient_stack(|| {
1411+
match try_ensure_sufficient_stack(|| {
14091412
if let TyKind::TraitType(tref, type_id, _args) = kind {
14101413
let path = TraitRefPath::self_ref(tref.trait_id()).with_assoc_type(*type_id);
14111414
if let Some(new_ty) = self.lookup_path_on_trait_ref(&path, tref) {
@@ -1420,7 +1423,13 @@ impl VisitAstMut for UpdateItemBody<'_> {
14201423
}
14211424
}
14221425
self.visit_inner(kind)
1423-
})
1426+
}) {
1427+
Ok(flow) => flow,
1428+
Err(err) => {
1429+
*kind = TyKind::Error("Stack depth limit exceeded".to_owned());
1430+
Break(err)
1431+
}
1432+
}
14241433
}
14251434

14261435
// Track span for more precise error messages.
@@ -1536,13 +1545,16 @@ impl TransformPass for Transform {
15361545
// Update the rest of the items: all the `GenericArgs` and the non-top-level binders
15371546
// (trait methods and inherent impls in `Name`s).
15381547
let is_type_alias = matches!(&item, ItemRefMut::Type(tdecl) if matches!(tdecl.kind, TypeDeclKind::Alias(..)));
1539-
let _ = item.drive_mut(&mut UpdateItemBody {
1548+
let mut visitor = UpdateItemBody {
15401549
ctx,
15411550
span,
15421551
is_type_alias,
15431552
item_modifications: &item_modifications,
15441553
type_replacements: BindingStack::new(type_replacements),
1545-
});
1554+
};
1555+
if let Break(_) = item.drive_mut(&mut visitor) {
1556+
register_error!(ctx, visitor.span, "Stack depth limit exceeded while expanding associated types");
1557+
}
15461558
});
15471559
}
15481560
}

‎charon/src/utils.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -419,12 +419,26 @@ thread_local! {
419419
#[inline]
420420
#[track_caller]
421421
pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
422+
match try_ensure_sufficient_stack(f) {
423+
Ok(value) => value,
424+
Err(_) => panic!("stack depth limit exceeded"),
425+
}
426+
}
427+
428+
#[derive(Debug)]
429+
pub struct StackDepthLimitExceeded;
430+
431+
/// Like `ensure_sufficient_stack`, but lets callers recover when recursion is too deep.
432+
#[inline]
433+
pub fn try_ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> Result<R, StackDepthLimitExceeded> {
422434
let depth = STACK_DEPTH.get();
423-
assert!(depth < MAX_STACK_DEPTH, "stack depth limit exceeded");
435+
if depth >= MAX_STACK_DEPTH {
436+
return Err(StackDepthLimitExceeded);
437+
}
424438
STACK_DEPTH.set(depth + 1);
425439
// Re-set the depth on return or unwind.
426440
let _guard = DropGuard::new((), |()| STACK_DEPTH.set(depth));
427-
stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)
441+
Ok(stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f))
428442
}
429443

430444
/// Returns the values of the command-line options that match `find_arg`. The options are built-in
@@ -466,14 +480,16 @@ pub fn arg_value<'a, T: AsRef<str>>(args: &'a [T], needle: &'a str) -> Option<&'
466480

467481
#[test]
468482
fn catch_stack_overflow() {
469-
fn recurse(depth: usize) {
470-
ensure_sufficient_stack(|| {
483+
fn recurse(depth: usize) -> Result<(), StackDepthLimitExceeded> {
484+
try_ensure_sufficient_stack(|| {
471485
if depth > 0 {
472-
recurse(depth - 1);
486+
recurse(depth - 1)
487+
} else {
488+
Ok(())
473489
}
474-
});
490+
})?
475491
}
476492

477-
assert!(std::panic::catch_unwind(|| recurse(1024)).is_err());
478-
assert_eq!(ensure_sufficient_stack(|| 42), 42);
493+
assert!(recurse(1024).is_err());
494+
assert_eq!(try_ensure_sufficient_stack(|| 42).unwrap(), 42);
479495
}
Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1+
error: Stack depth limit exceeded while expanding associated types
2+
--> tests/ui/associated_types/issue-1519-recursive-lifting.rs:9:1
3+
|
4+
9 | / impl HasAssoc for () {
5+
10 | | // Lifting this type visits NeedsAssoc<()>, which requires (): HasAssoc again.
6+
11 | | type Assoc = NeedsAssoc<()>;
7+
12 | | }
8+
| |_^
19

2-
thread 'main' panicked at src/transform/normalize/expand_associated_types.rs:1408:9:
3-
stack depth limit exceeded
4-
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
5-
ERROR Compilation panicked
10+
ERROR Charon failed to translate this code (1 errors)

‎charon/tests/ui/associated_types/issue-1519-recursive-lifting.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ known-panic
1+
//@ known-failure
22
//@ charon-args=--lift-associated-types=*
33
pub trait HasAssoc {
44
type Assoc;

0 commit comments

Comments
 (0)