Skip to content

Commit

Permalink
fix(parser) Fix freezing issue with illegal 0 width matches (#2524)
Browse files Browse the repository at this point in the history
* 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 authored May 3, 2020
1 parent 8f5290e commit acbbac8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
3 changes: 1 addition & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,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
19 changes: 19 additions & 0 deletions src/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,23 @@ const HLJS = function(hljs) {
}
}

// 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 @@ -396,12 +413,14 @@ const HLJS = function(hljs) {
var mode_buffer = '';
var relevance = 0;
var index = 0;
var iterations = 0;
var continueScanAtSamePosition = false;

try {
top.matcher.considerAll();

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

0 comments on commit acbbac8

Please sign in to comment.