Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw, if BlockSyntax.parseLines loops indefinitely #533

Merged
merged 1 commit into from
Apr 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion lib/src/block_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,9 @@ class BlockParser {
// number of cells, which makes a table like structure not be recognized.
BlockSyntax? neverMatch;

var iterationsWithoutProgress = 0;
while (!isDone) {
final positionBefore = _pos;
for (final syntax in blockSyntaxes) {
if (neverMatch == syntax) {
continue;
Expand All @@ -173,7 +175,6 @@ class BlockParser {
if (syntax.canParse(this)) {
_previousSyntax = _currentSyntax;
_currentSyntax = syntax;
final positionBefore = _pos;
final block = syntax.parse(this);
if (block != null) {
blocks.add(block);
Expand All @@ -189,6 +190,25 @@ class BlockParser {
break;
}
}
// Count the number of iterations without progress.
// This ensures that we don't have an infinite loop. And if we have an
// infinite loop, it's easier to gracefully recover from an error, than
// it is to discover an kill an isolate that's stuck in an infinite loop.
// Technically, it should be perfectly safe to remove this check
// But as it's possible to inject custom BlockSyntax implementations and
// combine existing ones, it is hard to promise that no combination can't
// trigger an infinite loop
if (positionBefore == _pos) {
iterationsWithoutProgress++;
if (iterationsWithoutProgress > 2) {
// If this happens we throw an error to avoid having the parser
// running in an infinite loop. An error is easier to handle.
// If you see this error in production please file a bug!
throw AssertionError('BlockParser.parseLines is not advancing');
}
} else {
iterationsWithoutProgress = 0;
}
}

return blocks;
Expand Down