Skip to content

Commit

Permalink
Fix underflow in recursion limit code
Browse files Browse the repository at this point in the history
The recursion limiter didn't prevent underflow. Fixed properly
and also switched to `Cell` because atomic support seems fairly
variable.
  • Loading branch information
46bit committed May 18, 2022
1 parent 9a753ec commit d274c9f
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use core::fmt;
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(feature = "std")]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::cell::Cell;

use log::debug;
#[cfg(feature = "std")]
Expand Down Expand Up @@ -62,11 +62,12 @@ macro_rules! return_ok_if_some {
macro_rules! check_recursion_depth {
($this:ident) => {
let remaining_depth = $this.remaining_depth.clone();
if remaining_depth.fetch_sub(1, Ordering::SeqCst) <= 0 {
remaining_depth.set(remaining_depth.get().saturating_sub(1));
if remaining_depth.get() == 0 {
return Err(ParserError::RecursionLimitExceeded);
}
defer! {
remaining_depth.fetch_add(1, Ordering::SeqCst);
remaining_depth.set(remaining_depth.get() + 1);
}
};
}
Expand Down Expand Up @@ -136,7 +137,7 @@ pub struct Parser<'a> {
index: usize,
dialect: &'a dyn Dialect,
#[cfg(feature = "std")]
remaining_depth: Rc<AtomicUsize>,
remaining_depth: Rc<Cell<usize>>,
}

impl<'a> Parser<'a> {
Expand All @@ -147,7 +148,7 @@ impl<'a> Parser<'a> {
index: 0,
dialect,
#[cfg(feature = "std")]
remaining_depth: Rc::new(AtomicUsize::new(96)),
remaining_depth: Rc::new(Cell::new(96)),
}
}

Expand Down

0 comments on commit d274c9f

Please sign in to comment.