8000 Fix crash when emoji precedes a later block by feng2919013386-oss · Pull Request #25 · jahala/mrkd · GitHub
[go: up one dir, main page]

Skip to content

Fix crash when emoji precedes a later block - #25

Open
feng2919013386-oss wants to merge 1 commit into
jahala:masterfrom
feng2919013386-oss:fix/utf16-index-crash
Open

feng2919013386-oss wants to merge 1 commit into
jahala:masterfrom
feng2919013386-oss:fix/utf16-index-crash

Conversation

@feng2919013386-oss
Copy link
Copy Markdown

Bug

MarkdownRenderer.applyContextualSpacing crashed with String index is out of bounds (EXC_BREAKPOINT/SIGTRAP) on documents containing supplementary-plane characters (emoji, ZWJ family emoji, flags, etc.) before a later block.

Root cause: startPosition is result.length — a count of UTF-16 code units — but the code advanced a Swift String.Index with text.index(text.startIndex, offsetBy: startPosition), which counts Characters (grapheme clusters). For any multi-unit character rendered before the block, the offset exceeds the Character count and Swift traps — an immediate crash on open for any such document.

Reproduced with open mrkd.app fulla.md, a file whose first paragraph is 150 × 👨👩👧👦 (1050 UTF-16 units, 150 Characters), followed by a second paragraph: the pre-fix build crashes on launch, the fixed build renders normally.

Fix

  • Index by UTF-16 offset: String.Index(utf16Offset:startPosition, in: text)
  • Measure the paragraph length in the UTF-16 view (text.utf16.distance(...)), since it is used as an NSRange length (also UTF-16)

Tests

Added two regression tests in MarkdownRendererTests:

  • testRenderDoesNotCrashWhenEmojiPrecedesLaterBlock — the minimal crash case, also asserts contextual spacing is still applied
  • testRenderSurvivesEmojiInsideLongerDocument — emoji in headings, lists, blockquotes, code fences and tables

applyContextualSpacing indexed the attributed string's UTF-16 length
(result.length) into a Swift String by Character offset. Any
supplementary-plane character (emoji) rendered before the block makes
UTF-16 length exceed the Character count, and String.index(_:offsetBy:)
traps with 'String index is out of bounds' — a hard crash on launch for
any emoji-containing document with two or more blocks.

Index by UTF-16 offset (String.Index(utf16Offset:in:)) and measure the
paragraph length in the UTF-16 view, since NSRange lengths are UTF-16.

Adds regression tests covering emoji before later blocks and a longer
emoji-heavy document (headings, lists, blockquotes, code, tables).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0