Skip to content

Commit

Permalink
fix(parser) Fix freezing issue with illegal 0 width matches (highligh…
Browse files Browse the repository at this point in the history
…tjs#2524)

* fix[parser] add edge case handle for illegal 0 width matches
* add last ditch catch all that tries to detect other uncaught freezes
  • Loading branch information
joshgoebel committed May 3, 2020
1 parent 82ae7ce commit 1bc0562
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
3 changes: 1 addition & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ Brower build:
- [Issue](https://github.com/highlightjs/highlight.js/issues/2505) (bug) Fix: Version 10 fails to load as CommonJS module. (#2511) [Josh Goebel][]
- [Issue](https://github.com/highlightjs/highlight.js/issues/2505) (removal) AMD module loading support has been removed. (#2511) [Josh Goebel][]


Parser Engine Changes:

- ...
- [Issue](https://github.com/highlightjs/highlight.js/issues/2522) fix(parser) Fix freez issue with illegal 0 width matches (#2524) [Josh Goebel][]


[Josh Goebel]: https://github.com/yyyc514
Expand Down
27 changes: 24 additions & 3 deletions src/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,23 @@ const HLJS = function(hljs) {
return processed;
}

// edge case for when illegal matches $ (end of line) which is technically
// a 0 width match but not a begin/end match so it's not caught by the
// first handler (when ignoreIllegals is true)
if (match.type === "illegal" && lexeme === "") {
// advance so we aren't stuck in an infinite loop
return 1;
}

// infinite loops are BAD, this is a last ditch catch all. if we have a
// decent number of iterations yet our index (cursor position in our
// parsing) still 3x behind our index then something is very wrong
// so we bail
if (iterations > 100000 && iterations > match.index * 3) {
const err = new Error('potential infinite loop, way more iterations than matches');
throw err;
}

/*
Why might be find ourselves here? Only one occasion now. An end match that was
triggered but could not be completed. When might this happen? When an `endSameasBegin`
Expand Down Expand Up @@ -378,13 +395,17 @@ const HLJS = function(hljs) {
processContinuations();
var mode_buffer = '';
var relevance = 0;
var match, processedCount, index = 0;
var match;
var processedCount;
var index = 0;
var iterations = 0;
var continueScanAtSamePosition = false;

try {
var continueScanAtSamePosition = false;
top.matcher.considerAll();

while (true) {
for (;;) {
iterations++;
if (continueScanAtSamePosition) {
continueScanAtSamePosition = false;
// only regexes not matched previously will now be
Expand Down

0 comments on commit 1bc0562

Please sign in to comment.