From 5906cfb06085a4ae7ae2e5ac5bb190e0c1e90a42 Mon Sep 17 00:00:00 2001 From: Rohan Kulkarni Date: Wed, 12 Aug 2026 08:22:32 -0700 Subject: [PATCH] Fix Text truncation at NULL character on iOS and Android (#24129) (#57906) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Fixes https://github.com/react/react-native/issues/24129 **Problem:** `{'Hello \u0000 World'}` renders as "Hello" (truncated at \u0000). Does NOT reproduce when Debug JS Remotely (JSON preserves \u0000), but reproduces in production Hermes+Fabric on iOS and Android. **Root cause:** JS String preserves \u0000 (length includes it), C++ std::string from JSI utf8() also preserves via size. Truncation happens at platform bridge where C-string NUL-terminated APIs are used: - iOS: RCTAttributedTextUtils.mm:420 stringWithUTF8String:fragment.string.c_str() stops at embedded \0 - iOS: RCTConversions.h RCTNSStringFromString via stringWithCString: and reverse std::string{UTF8String} - iOS: RCTTurboModule.mm convertJSIStringToNSString same - Android: JavaTurboModule.cpp NewStringUTF(c_str()) expects NUL-terminated **Fix (no new API):** Replace the C-string APIs with length-aware equivalents. On iOS, `[[NSString alloc] initWithBytes:length:encoding:]` for std::string to NSString, and `dataUsingEncoding:` for the reverse, matching the existing correct pattern in FollyConvert.mm:31 and MapBufferBuilder.cpp. On Android the conversion now goes through UTF-16 in both directions rather than UTF-8: - outbound: `rt.utf16(...)` then `NewString(jchar*, len)` - inbound: `GetStringLength()` + `GetStringChars()` then `jsi::String::createFromUtf16(...)`, released with `ReleaseStringChars` That is worth calling out because it fixes a second latent bug. `NewStringUTF` expects *modified* UTF-8 (CESU-8), so it already mishandled 4-byte sequences such as emoji and other supplementary-plane characters. Going UTF-16 to UTF-16 avoids both problems. All surfaces (Text, TextInput, accessibility, TurboModule params) are fixed at once because the shared converters are fixed. ## NOTE: nil becomes empty string at two call sites RCTTurboModule.mm and RCTAttributedTextUtils.mm gain a `?: @""` fallback. Previously `stringWithUTF8String:` returned `nil` for invalid UTF-8 and callers received nil; they now receive `@""`. This matches the fallback `RCTNSStringFromString` already had, and `@""` is safer than nil for the ObjC call sites involved, but it is a behaviour change rather than a pure refactor. ## Changelog: [GENERAL] [FIXED] - Fix Text truncation when string contains NULL character \u0000 (https://github.com/react/react-native/issues/24129) Pull Request resolved: https://github.com/react/react-native/pull/57906 Test Plan: **Reproduction (RNTester):** - Add screen Text > NullCharacter with {'Hello\u0000World'} and 'A\u0000B\u0000C' - Before: "Hello" truncated - After: "HelloWorld" full (invisible \0 zero-width but World visible, length preserved) Closes https://github.com/react/react-native/issues/24129 ## Added on import: regression tests Four cases added to the existing `React/Tests/Text/RCTAttributedTextUtilsTest.mm`, which is owned by `TextTestsApple`: ``` buck2 test fbsource//xplat/js/react-native-github:TextTestsApple → Pass 31. Fail 0. ``` Restoring the pre-fix `RCTConversions.h` and `RCTAttributedTextUtils.mm` and re-running fails all four and nothing else: ``` ✗ RCTAttributedTextUtilsTest/testNSStringFromStringPreservesEmbeddedNull ✗ RCTAttributedTextUtilsTest/testStringFromNSStringPreservesEmbeddedNull ✗ RCTAttributedTextUtilsTest/testStringConversionRoundTripsEmbeddedNull ✗ RCTAttributedTextUtilsTest/testAttributedStringFromFragmentPreservesEmbeddedNull Tests finished: Pass 27. Fail 4. ``` They cover `RCTNSStringFromString`, `RCTStringFromNSString`, a round trip through both, and the real AttributedString to NSAttributedString path. The changed function in RCTAttributedTextUtils.mm (`RCTNSAttributedStringFragmentFromFragment`) is static, so that last one goes through the public `RCTNSAttributedStringFromAttributedString`. This replaces the original `node -p "'a\u0000b'.length"` check, which exercised JavaScript string length rather than any of the changed code. The Android hunks are not covered by these tests. They are iOS-only test targets and there is no equivalent JNI-level unit test in tree, so the Android side rests on code review. ## On the reverse-direction allocation `RCTStringFromNSString` now allocates an `NSData` where it previously used `UTF8String` (an interior pointer). That converter has 6 callers. The hot one is `RCTNSStringFromString` with 43 callers, and it does not add an allocation: `stringWithCString:` and `initWithBytes:` both allocate an NSString. Keeping the `NSData` form deliberately, because the cheaper alternative relies on `UTF8String`'s buffer containing embedded NULs, which is exactly the ambiguity this diff removes. `arc lint -e extra` on the test file reports only pre-existing warnings plus a NULLSAFECLANG infrastructure failure. Reviewed By: cipolleschi Differential Revision: D115707536 Pulled By: fabriziocucci fbshipit-source-id: 4cde8d4b584e0305fcfc3a4520f3690b411500cb --- .../React/Fabric/RCTConversions.h | 12 ++++- .../Tests/Text/RCTAttributedTextUtilsTest.mm | 54 +++++++++++++++++++ .../android/ReactCommon/JavaTurboModule.cpp | 19 ++++--- .../ios/ReactCommon/RCTTurboModule.mm | 4 +- .../RCTAttributedTextUtils.mm | 5 +- .../textlayoutmanager/RCTTextLayoutManager.mm | 6 ++- 6 files changed, 87 insertions(+), 13 deletions(-) diff --git a/packages/react-native/React/Fabric/RCTConversions.h b/packages/react-native/React/Fabric/RCTConversions.h index 21e6310c62b..d4f705c82b6 100644 --- a/packages/react-native/React/Fabric/RCTConversions.h +++ b/packages/react-native/React/Fabric/RCTConversions.h @@ -34,7 +34,8 @@ inline NSString *RCTNSStringFromString( const std::string &string, const NSStringEncoding &encoding = NSUTF8StringEncoding) { - return [NSString stringWithCString:string.c_str() encoding:encoding] ?: @""; + NSString *result = [[NSString alloc] initWithBytes:string.data() length:string.size() encoding:encoding]; + return result != nil ? result : @""; } inline NSString *_Nullable RCTNSStringFromStringNilIfEmpty( @@ -46,7 +47,14 @@ inline NSString *_Nullable RCTNSStringFromStringNilIfEmpty( inline std::string RCTStringFromNSString(NSString *string) { - return std::string{string.UTF8String ?: ""}; + if (string == nil) { + return ""; + } + NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; + if (data == nil) { + return ""; + } + return std::string{static_cast(data.bytes), data.length}; } inline UIColor *_Nullable RCTUIColorFromSharedColor(const facebook::react::SharedColor &sharedColor) diff --git a/packages/react-native/React/Tests/Text/RCTAttributedTextUtilsTest.mm b/packages/react-native/React/Tests/Text/RCTAttributedTextUtilsTest.mm index e14c46fd528..a02622d5d7d 100644 --- a/packages/react-native/React/Tests/Text/RCTAttributedTextUtilsTest.mm +++ b/packages/react-native/React/Tests/Text/RCTAttributedTextUtilsTest.mm @@ -9,12 +9,14 @@ #import #import +#import #import #import #include #include +#include #include using namespace facebook::react; @@ -384,4 +386,56 @@ static NSDictionary *FontVariationsFromSettings(std::opt attributedString2, attributedString1, insensitiveAttributes, textAttributes)); } +// A std::string may legitimately contain an embedded NUL. The C-string APIs +// these converters used to call stop at it, silently truncating user text. + +- (void)testNSStringFromStringPreservesEmbeddedNull +{ + std::string withNull("Hello\0World", 11); + XCTAssertEqual(withNull.size(), 11u); + + NSString *converted = RCTNSStringFromString(withNull); + + XCTAssertEqual(converted.length, 11u); + XCTAssertTrue([converted hasPrefix:@"Hello"]); + XCTAssertTrue([converted hasSuffix:@"World"]); +} + +- (void)testStringFromNSStringPreservesEmbeddedNull +{ + std::array chars{'a', 0, 'b'}; + NSString *withNull = [NSString stringWithCharacters:chars.data() length:chars.size()]; + XCTAssertEqual(withNull.length, 3u); + + std::string converted = RCTStringFromNSString(withNull); + + XCTAssertEqual(converted.size(), 3u); + XCTAssertEqual(converted[0], 'a'); + XCTAssertEqual(converted[1], '\0'); + XCTAssertEqual(converted[2], 'b'); +} + +- (void)testStringConversionRoundTripsEmbeddedNull +{ + std::string original("A\0B\0C", 5); + + std::string roundTripped = RCTStringFromNSString(RCTNSStringFromString(original)); + + XCTAssertEqual(roundTripped.size(), original.size()); + XCTAssertTrue(roundTripped == original); +} + +- (void)testAttributedStringFromFragmentPreservesEmbeddedNull +{ + AttributedString attributedString; + AttributedString::Fragment fragment; + fragment.string = std::string("Hello\0World", 11); + attributedString.appendFragment(std::move(fragment)); + + NSAttributedString *result = RCTNSAttributedStringFromAttributedString(attributedString); + + XCTAssertEqual(result.string.length, 11u); + XCTAssertTrue([result.string hasSuffix:@"World"]); +} + @end diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp index 944b59c4f49..cec9eaf5f02 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.cpp @@ -406,8 +406,10 @@ JNIArgs convertJSIArgsToJNIArgs( throw JavaTurboModuleArgumentConversionException( "string", argIndex, methodName, arg, &rt); } - jarg->l = makeGlobalIfNecessary( - env->NewStringUTF(arg->getString(rt).utf8(rt).c_str())); + auto utf16 = rt.utf16(arg->getString(rt)); + jarg->l = makeGlobalIfNecessary(env->NewString( + reinterpret_cast(utf16.data()), + static_cast(utf16.size()))); } else if (type == "Lcom/facebook/react/bridge/Callback;") { if (!(arg->isObject() && arg->getObject(rt).isFunction(rt))) { throw JavaTurboModuleArgumentConversionException( @@ -785,11 +787,14 @@ jsi::Value JavaTurboModule::invokeJavaMethod( jsi::Value returnValue = jsi::Value::null(); if (returnString != nullptr) { - const char* js = env->GetStringUTFChars(returnString, nullptr); - std::string result = js; - env->ReleaseStringUTFChars(returnString, js); - returnValue = - jsi::Value(runtime, jsi::String::createFromUtf8(runtime, result)); + jsize length = env->GetStringLength(returnString); + const jchar* chars = env->GetStringChars(returnString, nullptr); + auto jsiString = jsi::String::createFromUtf16( + runtime, + reinterpret_cast(chars), + static_cast(length)); + env->ReleaseStringChars(returnString, chars); + returnValue = jsi::Value(runtime, jsiString); } TMPL::syncMethodCallReturnConversionEnd(moduleName, methodName); diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm index ac075393452..3da49c39a08 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm @@ -143,7 +143,9 @@ jsi::Value convertObjCObjectToJSIValue(jsi::Runtime &runtime, id value) static NSString *convertJSIStringToNSString(jsi::Runtime &runtime, const jsi::String &value) { - return [NSString stringWithUTF8String:value.utf8(runtime).c_str()]; + auto utf8 = value.utf8(runtime); + NSString *result = [[NSString alloc] initWithBytes:utf8.data() length:utf8.size() encoding:NSUTF8StringEncoding]; + return result != nil ? result : @""; } static NSArray *convertJSIArrayToNSArray( diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm index 346ff459dd2..95ff5a0d180 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm @@ -417,7 +417,10 @@ static NSMutableAttributedString *RCTNSAttributedStringFragmentFromFragment( return [[NSMutableAttributedString attributedStringWithAttachment:attachment] mutableCopy]; } else { - NSString *string = [NSString stringWithUTF8String:fragment.string.c_str()]; + NSString *decoded = [[NSString alloc] initWithBytes:fragment.string.data() + length:fragment.string.size() + encoding:NSUTF8StringEncoding]; + NSString *string = decoded != nil ? decoded : @""; if (fragment.textAttributes.textTransform.has_value()) { auto textTransform = fragment.textAttributes.textTransform.value(); diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm index ac9b63e1e5e..5f9847a398f 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm @@ -400,9 +400,11 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi .width = usedRect.size.width, .height = usedRect.size.height}}; CGFloat baseline = [layoutManager locationForGlyphAtIndex:range.location].y; - const char *renderedUTF8 = [renderedString UTF8String]; + NSData *renderedData = [renderedString dataUsingEncoding:NSUTF8StringEncoding]; auto line = LineMeasurement{ - std::string(renderedUTF8 != nullptr ? renderedUTF8 : ""), + std::string( + renderedData != nil ? static_cast(renderedData.bytes) : "", + renderedData != nil ? renderedData.length : 0), rect, overallRect.size.height - baseline, font.capHeight,