Skip to content

IndexOutOfRangeException in EmphasisInlineParser with CjkFriendlyEmphasis #941

Closed

Description

@yamanaiyuki

When using UseCjkFriendlyEmphasis(), there are cases where an IndexOutOfRangeException will occur. The main cause is attempting to access twoPreviousChar beyond the string boundary when retrieving it.

To verify reproducibility, add the following tests to TestCjkFriendlyEmphasis.cs.

    [Test]
    [TestCase("**First**&#10;**Second**", "<p><strong>First</strong>\n<strong>Second</strong></p>\n")]
    public void TestCjkFriendlyEmphasis_ReproduceIndexOutOfRangeException(string source, string expected)
    {
        var pipeline = GetPipeline();
        var actual = Markdown.ToHtml(source, pipeline);
        Assert.AreEqual(expected, actual);
    }

Test results:

 TestCjkFriendlyEmphasis_ReproduceIndexOutOfRangeException("**First**&#10;**Second**","<p><strong>First</strong>\n<strong>Second</strong></p>\n")
   ソース: TestCjkFriendlyEmphasis.cs 行 107
   期間: 37 ミリ秒

  メッセージ: 
System.IndexOutOfRangeException : Index was outside the bounds of the array.

  スタック トレース: 
String.get_Chars(Int32 index)
StringSlice.RuneAt(Int32 index) 行 195
EmphasisInlineParser.Match(InlineProcessor processor, StringSlice& slice) 行 180
InlineProcessor.ProcessInlineLeaf(LeafBlock leafBlock) 行 285
MarkdownParser.ProcessInlines(InlineProcessor inlineProcessor, MarkdownDocument document) 行 176
MarkdownParser.Parse(String text, MarkdownPipeline pipeline, MarkdownParserContext context) 行 76
Markdown.ToHtml(String markdown, MarkdownPipeline pipeline, MarkdownParserContext context) 行 104
TestCjkFriendlyEmphasis.TestCjkFriendlyEmphasis_ReproduceIndexOutOfRangeException(String source, String expected) 行 110
MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)

Causes and solutions

slice.PeekRuneExtra(-1 - pc.Utf16SequenceLength) has a problem when pc is \n (newline):

  1. If pc (the preceding character) is \n, then pc.Utf16SequenceLength is 1.
  2. Calling slice.PeekRuneExtra(-2) may result in out-of-bounds access.

Additionally, if the HTML entity (&#10;) is treated as a newline character, the following problem occurs in the calculation of twoPreviousChar:

// If pc = '\n'
pc = htmlEntityInline.Transcoded.RuneAt(htmlEntityInline.Transcoded.End);
// pc.Utf16SequenceLength = 1
twoPreviousChar = htmlEntityInline.Transcoded.RuneAt(htmlEntityInline.Transcoded.End - pc.Utf16SequenceLength);
// htmlEntityInline.Transcoded.End - 1 may point to ';', resulting in an invalid index.

Patch to fix EmphasisInlineParser.cs

From a148f77f0f3164fc5a2ea79e84644212ea2f1507 Mon Sep 17 00:00:00 2001
From: yamanaiyuki <yamanaiyuki@vivaldi.net>
Date: Thu, 11 Jun 2026 12:00:56 +0900
Subject: [PATCH] Fix IndexOutOfRangeException in EmphasisInlineParser with
 CjkFriendlyEmphasis=true

---
 src/Markdig.Tests/TestCjkFriendlyEmphasis.cs      | 15 +++++++++++++++
 .../Parsers/Inlines/EmphasisInlineParser.cs       | 14 +++++++++++---
 2 files changed, 26 insertions(+), 3 deletions(-)

diff --git a/src/Markdig.Tests/TestCjkFriendlyEmphasis.cs b/src/Markdig.Tests/TestCjkFriendlyEmphasis.cs
index b0f55b65..5b2f9ba8 100644
--- a/src/Markdig.Tests/TestCjkFriendlyEmphasis.cs
+++ b/src/Markdig.Tests/TestCjkFriendlyEmphasis.cs
@@ -106,6 +106,21 @@ public void TestCjkFriendlyPseudoEmoji(string source, string expected)
             Assert.AreEqual(expected, actual);
         }
 
+        [Test]
+        [TestCase("**Start**", "<p><strong>Start</strong></p>\n")]
+        [TestCase("\n**Newline**", "<p><strong>Newline</strong></p>\n")]
+        [TestCase("&#10;**Entity**", "<p>\n<strong>Entity</strong></p>\n")]
+        [TestCase("**First**\n**Second**", "<p><strong>First</strong>\n<strong>Second</strong></p>\n")]
+        [TestCase("**First**&#10;**Second**", "<p><strong>First</strong>\n<strong>Second</strong></p>\n")]
+        [TestCase("&#13;**CRLF**", "<p>\r<strong>CRLF</strong></p>\n")]
+        [TestCase("𠮷**SurrogatePair**", "<p>𠮷<strong>SurrogatePair</strong></p>\n")]
+        public void TestCjkFriendlyEmphasis_ReproduceIndexOutOfRangeException(string source, string expected)
+        {
+            var pipeline = GetPipeline();
+            var actual = Markdown.ToHtml(source, pipeline);
+            Assert.AreEqual(expected, actual);
+        }
+
 #if !NET || !MARKDIG_NO_RUNE_TESTS
         // delimiter: '*', '_' = each character, '?' = either
         // can open/close = whether the places can be in the range of emphasis
diff --git a/src/Markdig/Parsers/Inlines/EmphasisInlineParser.cs b/src/Markdig/Parsers/Inlines/EmphasisInlineParser.cs
index 92ae6d37..6aacc6f1 100644
--- a/src/Markdig/Parsers/Inlines/EmphasisInlineParser.cs
+++ b/src/Markdig/Parsers/Inlines/EmphasisInlineParser.cs
@@ -177,7 +177,11 @@ public override bool Match(InlineProcessor processor, ref StringSlice slice)
 
                 if (CjkFriendlyEmphasis)
                 {
-                    twoPreviousChar = htmlEntityInline.Transcoded.RuneAt(htmlEntityInline.Transcoded.End - pc.Utf16SequenceLength);
+                    var twoPrevPos = htmlEntityInline.Transcoded.End - pc.Utf16SequenceLength;
+                    if (twoPrevPos >= 0)
+                    {
+                        twoPreviousChar = htmlEntityInline.Transcoded.RuneAt(twoPrevPos);
+                    }
                 }
             }
         }
@@ -186,8 +190,12 @@ public override bool Match(InlineProcessor processor, ref StringSlice slice)
             pc = slice.PeekRuneExtra(-1);
             if (CjkFriendlyEmphasis)
             {
-                // This cannot be a delegate (Func<Rune>?) because slice is a reference
-                twoPreviousChar = slice.PeekRuneExtra(-1 - pc.Utf16SequenceLength);
+                var peekPos = -1 - pc.Utf16SequenceLength;
+                if (slice.Start + peekPos >= 0)
+                {
+                    // This cannot be a delegate (Func<Rune>?) because slice is a reference
+                    twoPreviousChar = slice.PeekRuneExtra(peekPos);
+                }
             }
             // delimiterChar is BMP, so slice.PeekCharExtra(-2) is (a part of) the character two positions back.
             if (pc == (Rune)delimiterChar && slice.PeekCharExtra(-2) != '\\')
-- 
2.51.0.windows.1

Activity

  1. xoofx commented on Jun 13, 2026

    @xoofx
    Owner

    Fixed via fcbf817

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions