Fix: Infinite recursion crash in wikitext parser #308
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The app kept crashing with a StackOverflowError on some Wikipedia pages because the
toWikitextAnnotatedStringfunction was getting stuck in an endless loop. Certain templates like{{small}}were sending the same wikitext back into the parser again and again, which caused the function to call itself repeatedly until the app crashed.Stack Trace Sample
Solution
Implemented a two-part fix:
1. Recursion Depth Guard
AnnotatedString(this)) instead of crashingtry/finallyblock to ensure proper cleanup of the recursion counter2. Template Branch Hardening
substringAfter('|')tosubstringAfter('|', "")for templates like:{{abbr}},{{efn}},{{val}},{{var}},{{small}}family,{{dfn}},{{US$}},{{hatnote}},{{rp}},{{isbn}},{{sfrac}},{{unichar}},{{char}},{{noflag}},{{nowrap}}family,{{url}},{{format price}},{{transliteration}}|parameter, the parser receives an empty string instead of the full template text, preventing self-recursionChanges
app/src/main/java/org/nsh07/wikireader/parser/wikitextToAnnotatedString.ktMAX_WIKITEXT_RECURSION_DEPTHconstant (64)WikitextParserStateobject with thread-local recursion countertoWikitextAnnotatedStringfunctionTesting
StackOverflowErrorNotes