Skip to content

dfa: fix inverted pointer subtraction disabling slow-bailout in reverse DFA - #704

Open
hyc-alt wants to merge 1 commit into
google:mainfrom
hyc-alt:fix/dfa-reverse-bailout
Open

hyc-alt wants to merge 1 commit into
google:mainfrom
hyc-alt:fix/dfa-reverse-bailout

Conversation

@hyc-alt

@hyc-alt hyc-alt commented Nov 27, 2026

Copy link
Copy Markdown

Summary

In DFA::InlinedSearchLoop() (re2/dfa.cc:1439-1444), when the DFA state cache fills and flushes repeatedly, RE2 checks progress since the previous flush so a thrashing DFA can bail out to the NFA:

if (resetp != NULL &&
    static_cast<size_t>(p - resetp) < 10*state_cache_.size()) {
  params->failed = true;
  return false;
}
resetp = p;

When run_forward == false (reverse DFA search), p decrements on every byte (c = *--p, re2/dfa.cc:1406) and can_prefix_accel is strictly false (re2/compile.cc:1180). Thus on every cache flush after the first, bp <= p < resetp < bp + size, making p - resetp strictly negative. Casting the negative ptrdiff_t to size_t wraps near SIZE_MAX, so < 10*state_cache_.size() is always false and a thrashing reverse DFA never bails out to the NFA.

Fix

  • Compute static_cast<size_t>(run_forward ? p - resetp : resetp - p) in re2/dfa.cc:1440.
  • Add regression test DFA.ReverseBailoutWhenSlow in re2/testing/dfa_test.cc.

Verification

  • Built with Clang -fsanitize=address,undefined -fno-sanitize-recover=all -O1 -g -DNDEBUG.
  • Before: On ^[01]{18}0 with DeBruijnString(18), ReverseProg ran 1,291 state-cache resets and never bailed out (failed=0).
  • After: ReverseProg bails out after 1 reset (failed=1, resets=1, failures=1); dfa_test passes 7/7 with 0 warnings and 0 ASan/UBSan errors.

…se DFA

In DFA::InlinedSearchLoop(), when run_forward is false, p decrements on
every step so p < resetp on subsequent state-cache flushes. Casting the
negative ptrdiff_t (p - resetp) to size_t wrapped near SIZE_MAX, making
the < 10*state_cache_.size() slow-bailout condition always false and
preventing a thrashing reverse DFA from falling back to the NFA.

Use run_forward ? p - resetp : resetp - p and add regression test
DFA.ReverseBailoutWhenSlow in re2/testing/dfa_test.cc.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant