Fix Text truncation at NULL character on iOS and Android (#24129) (#57906)

Summary:
Fixes https://github.com/react/react-native/issues/24129

**Problem:** `<Text>{'Hello \u0000 World'}</Text>` 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 <Text>{'Hello\u0000World'}</Text> 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
This commit is contained in:
Rohan Kulkarni authored and meta-codesync[bot] committed 2026-08-12 08:22:32 -07:00
1 parent 93284f5c5a
commit 5906cfb060
6 files changed
+87 -13

No files matched your search

@@ -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<const char *>(data.bytes), data.length};
}
inline UIColor *_Nullable RCTUIColorFromSharedColor(const facebook::react::SharedColor &sharedColor)
@@ -9,12 +9,14 @@
#import <Foundation/Foundation.h>
#import <XCTest/XCTest.h>
#import <React/RCTConversions.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
#import <react/renderer/textlayoutmanager/RCTFontUtils.h>
#include <react/renderer/attributedstring/conversions.h>
#include <react/renderer/core/RawValue.h>
#include <array>
#include <utility>
using namespace facebook::react;
@@ -384,4 +386,56 @@ static NSDictionary<NSNumber *, NSNumber *> *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<unichar, 3> 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
@@ -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<const jchar*>(utf16.data()),
static_cast<jsize>(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<const char16_t*>(chars),
static_cast<size_t>(length));
env->ReleaseStringChars(returnString, chars);
returnValue = jsi::Value(runtime, jsiString);
}
TMPL::syncMethodCallReturnConversionEnd(moduleName, methodName);
@@ -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(
@@ -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();
@@ -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<const char *>(renderedData.bytes) : "",
renderedData != nil ? renderedData.length : 0),
rect,
overallRect.size.height - baseline,
font.capHeight,