From 1bc05628b3c7b4fce74a263c22abc79f13553e56 Mon Sep 17 00:00:00 2001 From: Josh Goebel Date: Sun, 3 May 2020 14:06:00 -0400 Subject: [PATCH] fix(parser) Fix freezing issue with illegal 0 width matches (#2524) * fix[parser] add edge case handle for illegal 0 width matches * add last ditch catch all that tries to detect other uncaught freezes --- CHANGES.md | 3 +-- src/highlight.js | 27 ++++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0bb8118b1d..694c3390dd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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 diff --git a/src/highlight.js b/src/highlight.js index 526b509a30..43adf25258 100644 --- a/src/highlight.js +++ b/src/highlight.js @@ -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` @@ -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