Skip to content

Commit 4e7ae1e

Browse files
committed
macOS: Fix crash on out-of-bounds text input ranges
`TextInputModel` assumes its selection and composing range fall within its text, but nothing in the text input plugin enforced that. When they don't, we index past the end of `text_` which triggers an abort due to out of range access. ``` out_of_range was thrown in -fno-exceptions mode with message "basic_string" ``` Previously, `setMarkedText:selectedRange:replacementRange:` passed `selectedRange` unvalidated. IMEs report `NSNotFound` to indicate no selection within the mark text. That maps to `NSIntegerMax` rather than an offset, and we incorrectly stored that as the selection. Clearing the marked text collapses the composing range, so the next update replaces the selection instead and calls `replace` with a position `NSIntegerMax`. Clear and re-mark is what an input method emits when the input source is switched mid-composition. `SetText` was also unsafe: it assigned `text_` before validating the ranges, so a rejected update left us with the new text but the old (now out-of-bounds) ranges still pointing into it. This fixes that by clamping both ranges before any operation that indexes the text, applying either all of `SetText`'s fields or none, and clamping `selectedRange` and `replacementRange` in the plugin. `setMarkedText:` also null-checks the UTF-16 buffer, which `cStringUsingEncoding:` can return as nullptr. Fixes: flutter#190704
1 parent 0d23a03 commit 4e7ae1e

7 files changed

Lines changed: 398 additions & 30 deletions

File tree

‎engine/src/flutter/shell/platform/common/text_input_model.cc‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
#include <algorithm>
88
#include <string>
9+
#include <utility>
910

11+
#include "flutter/fml/logging.h"
1012
#include "flutter/fml/string_conversion.h"
1113

1214
namespace flutter {
@@ -31,12 +33,14 @@ TextInputModel::~TextInputModel() = default;
3133
bool TextInputModel::SetText(const std::string& text,
3234
const TextRange& selection,
3335
const TextRange& composing_range) {
34-
text_ = fml::Utf8ToUtf16(text);
35-
if (!text_range().Contains(selection) ||
36-
!text_range().Contains(composing_range)) {
36+
std::u16string new_text = fml::Utf8ToUtf16(text);
37+
const TextRange new_text_range(0, new_text.length());
38+
if (!new_text_range.Contains(selection) ||
39+
!new_text_range.Contains(composing_range)) {
3740
return false;
3841
}
3942

43+
text_ = std::move(new_text);
4044
selection_ = selection;
4145
composing_range_ = composing_range;
4246
composing_ = !composing_range.collapsed();
@@ -56,7 +60,8 @@ bool TextInputModel::SetSelection(const TextRange& range) {
5660

5761
bool TextInputModel::SetComposingRange(const TextRange& range,
5862
size_t cursor_offset) {
59-
if (!composing_ || !text_range().Contains(range)) {
63+
if (!composing_ || !text_range().Contains(range) ||
64+
cursor_offset > text_.length() - range.start()) {
6065
return false;
6166
}
6267
composing_range_ = range;
@@ -71,6 +76,12 @@ void TextInputModel::BeginComposing() {
7176

7277
void TextInputModel::UpdateComposingText(const std::u16string& text,
7378
const TextRange& selection) {
79+
// Re-clamp current selection and composing range to text.
80+
FML_DCHECK(text_range().Contains(selection_) &&
81+
text_range().Contains(composing_range_));
82+
selection_ = selection_.ClampedTo(text_.length());
83+
composing_range_ = composing_range_.ClampedTo(text_.length());
84+
7485
// Preserve selection if we get a no-op update to the composing region.
7586
if (text.length() == 0 && composing_range_.collapsed()) {
7687
return;
@@ -79,8 +90,11 @@ void TextInputModel::UpdateComposingText(const std::u16string& text,
7990
composing_range_.collapsed() ? selection_ : composing_range_;
8091
text_.replace(rangeToDelete.start(), rangeToDelete.length(), text);
8192
composing_range_.set_end(composing_range_.start() + text.length());
82-
selection_ = TextRange(selection.start() + composing_range_.start(),
83-
selection.extent() + composing_range_.start());
93+
94+
// Updated |selection| is supplied by the IME. Clamp to text length.
95+
const TextRange clamped_selection = selection.ClampedTo(text.length());
96+
selection_ = TextRange(clamped_selection.start() + composing_range_.start(),
97+
clamped_selection.extent() + composing_range_.start());
8498
}
8599

86100
void TextInputModel::UpdateComposingText(const std::u16string& text) {

‎engine/src/flutter/shell/platform/common/text_input_model.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ class TextInputModel {
2424
//
2525
// This method is typically used to update the TextInputModel's editing state
2626
// when the Flutter framework sends its latest text editing state.
27+
//
28+
// Returns false and leaves the model untouched if |selection| or
29+
// |composing_range| does not fit within |text|. Either all three are applied
30+
// or none are, so that the model never holds a range that indexes past the
31+
// end of its own text.
2732
bool SetText(const std::string& text,
2833
const TextRange& selection = TextRange(0),
2934
const TextRange& composing_range = TextRange(0));

‎engine/src/flutter/shell/platform/common/text_input_model_unittests.cc‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,53 @@ TEST(TextInputModel, SetTextResetsSelection) {
4747
EXPECT_EQ(model->selection(), TextRange(0));
4848
}
4949

50+
TEST(TextInputModel, SetTextRejectingSelectionLeavesModelUnchanged) {
51+
auto model = std::make_unique<TextInputModel>();
52+
EXPECT_TRUE(model->SetText("ABCDE", TextRange(3), TextRange(0)));
53+
// A rejected update must not apply the text either. Applying it alone would
54+
// leave the selection pointing past the end of the new text, and every
55+
// subsequent edit indexes into the text with that selection.
56+
EXPECT_FALSE(model->SetText("AB", TextRange(5), TextRange(0)));
57+
EXPECT_STREQ(model->GetText().c_str(), "ABCDE");
58+
EXPECT_EQ(model->selection(), TextRange(3));
59+
EXPECT_EQ(model->composing_range(), TextRange(0));
60+
}
61+
62+
TEST(TextInputModel, SetTextRejectingComposingRangeLeavesModelUnchanged) {
63+
auto model = std::make_unique<TextInputModel>();
64+
EXPECT_TRUE(model->SetText("ABCDE", TextRange(2), TextRange(1, 3)));
65+
EXPECT_FALSE(model->SetText("AB", TextRange(2), TextRange(1, 3)));
66+
EXPECT_STREQ(model->GetText().c_str(), "ABCDE");
67+
EXPECT_EQ(model->selection(), TextRange(2));
68+
EXPECT_EQ(model->composing_range(), TextRange(1, 3));
69+
EXPECT_TRUE(model->composing());
70+
}
71+
72+
TEST(TextInputModel, UpdateComposingTextWithSelectionPastComposingText) {
73+
auto model = std::make_unique<TextInputModel>();
74+
EXPECT_TRUE(model->SetText("ABCDE", TextRange(5), TextRange(0)));
75+
model->BeginComposing();
76+
77+
// The selection accompanying composing text is relative to that text, but an
78+
// input method is free to report one that does not fit inside it. The offset
79+
// must not reach the text buffer, where a later edit would index out of
80+
// bounds and abort the process from inside the standard library.
81+
model->UpdateComposingText(u"n", TextRange(99));
82+
EXPECT_STREQ(model->GetText().c_str(), "ABCDEn");
83+
EXPECT_EQ(model->selection(), TextRange(6));
84+
EXPECT_EQ(model->composing_range(), TextRange(5, 6));
85+
86+
// Clearing the composing text collapses the composing range, which makes the
87+
// next update replace the selection instead. This is the point at which an
88+
// unclamped offset becomes an out of bounds index into the text.
89+
model->UpdateComposingText(u"", TextRange(99));
90+
EXPECT_EQ(model->composing_range(), TextRange(5));
91+
EXPECT_EQ(model->selection(), TextRange(5));
92+
model->UpdateComposingText(u"m", TextRange(1));
93+
EXPECT_STREQ(model->GetText().c_str(), "ABCDEm");
94+
EXPECT_EQ(model->selection(), TextRange(6));
95+
}
96+
5097
TEST(TextInputModel, SetSelectionStart) {
5198
auto model = std::make_unique<TextInputModel>();
5299
model->SetText("ABCDE");
@@ -217,6 +264,19 @@ TEST(TextInputModel, SetComposingRangeReverseExtent) {
217264
EXPECT_STREQ(model->GetText().c_str(), "ABCDE");
218265
}
219266

267+
TEST(TextInputModel, SetComposingRangeWithOffsetOutsideString) {
268+
auto model = std::make_unique<TextInputModel>();
269+
model->SetText("ABCDE");
270+
model->BeginComposing();
271+
// The offset positions the caret relative to the composing range, and reaches
272+
// the text as an index. An offset that runs past the end of the text must be
273+
// rejected rather than stored as a selection.
274+
EXPECT_FALSE(model->SetComposingRange(TextRange(1, 4), 5));
275+
EXPECT_EQ(model->selection(), TextRange(0));
276+
EXPECT_TRUE(model->SetComposingRange(TextRange(1, 4), 4));
277+
EXPECT_EQ(model->selection(), TextRange(5));
278+
}
279+
220280
TEST(TextInputModel, SetComposingRangeOutsideString) {
221281
auto model = std::make_unique<TextInputModel>();
222282
model->SetText("ABCDE");

‎engine/src/flutter/shell/platform/common/text_range.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,13 @@ class TextRange {
8989
return range.start() >= start() && range.end() <= end();
9090
}
9191

92+
// Returns the range with both endpoints clamped to |length|.
93+
//
94+
// The base/extent ordering is preserved, so a reversed range stays reversed.
95+
TextRange ClampedTo(size_t length) const {
96+
return TextRange(std::min(base_, length), std::min(extent_, length));
97+
}
98+
9299
bool operator==(const TextRange& other) const {
93100
return base_ == other.base_ && extent_ == other.extent_;
94101
}

‎engine/src/flutter/shell/platform/common/text_range_unittests.cc‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,4 +245,18 @@ TEST(TextRange, ReversedReversedRange) {
245245
EXPECT_TRUE(range.reversed());
246246
}
247247

248+
TEST(TextRange, ClampedToLongerLength) {
249+
EXPECT_EQ(TextRange(2, 6).ClampedTo(10), TextRange(2, 6));
250+
}
251+
252+
TEST(TextRange, ClampedToShorterLength) {
253+
EXPECT_EQ(TextRange(2, 6).ClampedTo(4), TextRange(2, 4));
254+
}
255+
256+
TEST(TextRange, ClampedToShorterLengthReversed) {
257+
// A reversed range must stay reversed: callers derive the cursor position
258+
// from the extent, not from the lesser endpoint.
259+
EXPECT_EQ(TextRange(6, 2).ClampedTo(4), TextRange(4, 2));
260+
}
261+
248262
} // namespace flutter

‎engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm‎

Lines changed: 52 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#include <algorithm>
1111
#include <memory>
12+
#include <string>
1213

1314
#include "flutter/common/constants.h"
1415
#include "flutter/fml/platform/darwin/string_range_sanitization.h"
@@ -95,6 +96,19 @@ typedef NS_ENUM(NSUInteger, FlutterTextAffinity) {
9596
return flutter::TextRange([base unsignedLongValue], [extent unsignedLongValue]);
9697
}
9798

99+
// Returns |range| as a TextRange clamped to |length|.
100+
//
101+
// A selection made backwards is reported as a range whose length is negative
102+
// when read as a signed value, so the length is interpreted signed and the
103+
// direction of the range is preserved. A location of NSNotFound clamps to
104+
// |length|.
105+
static flutter::TextRange ClampNSRange(NSRange range, size_t length) {
106+
const long text_length = static_cast<long>(length);
107+
const long signed_length = std::clamp(static_cast<long>(range.length), -text_length, text_length);
108+
const long base = std::clamp(static_cast<long>(range.location), 0L, text_length);
109+
return flutter::TextRange(base, std::clamp(base + signed_length, 0L, text_length));
110+
}
111+
98112
// Returns the autofill hint content type, if specified; otherwise nil.
99113
static NSString* GetAutofillHint(NSDictionary* autofill) {
100114
NSArray<NSString*>* hints = autofill[kAutofillHints];
@@ -535,6 +549,9 @@ - (void)updateCaretRect:(NSDictionary*)dictionary {
535549
}
536550

537551
- (void)setEditingState:(NSDictionary*)state {
552+
if (_activeModel == nullptr) {
553+
return;
554+
}
538555
NSString* selectionAffinity = state[kSelectionAffinityKey];
539556
if (selectionAffinity != nil) {
540557
_textAffinity = [selectionAffinity isEqualToString:kTextAffinityUpstream]
@@ -543,13 +560,25 @@ - (void)setEditingState:(NSDictionary*)state {
543560
}
544561

545562
NSString* text = state[kTextKey];
563+
if (![text isKindOfClass:[NSString class]]) {
564+
text = @"";
565+
}
546566

547-
flutter::TextRange selected_range = RangeFromBaseExtent(
548-
state[kSelectionBaseKey], state[kSelectionExtentKey], _activeModel->selection());
549-
_activeModel->SetSelection(selected_range);
550-
551-
flutter::TextRange composing_range = RangeFromBaseExtent(
552-
state[kComposingBaseKey], state[kComposingExtentKey], _activeModel->composing_range());
567+
// The framework computes these ranges against its own copy of the text, which may be a different
568+
// revision than the text it sends here, and the ranges are dropped entirely by |SetText| if they
569+
// don't fit.
570+
//
571+
// Clamp them to the incoming text so a stale offset degrades the caret position rather than
572+
// discarding the text update.
573+
size_t text_length = text.length;
574+
flutter::TextRange selected_range =
575+
RangeFromBaseExtent(state[kSelectionBaseKey], state[kSelectionExtentKey],
576+
_activeModel->selection())
577+
.ClampedTo(text_length);
578+
flutter::TextRange composing_range =
579+
RangeFromBaseExtent(state[kComposingBaseKey], state[kComposingExtentKey],
580+
_activeModel->composing_range())
581+
.ClampedTo(text_length);
553582

554583
const bool wasComposing = _activeModel->composing();
555584
_activeModel->SetText([text UTF8String], selected_range, composing_range);
@@ -772,17 +801,7 @@ - (void)insertText:(id)string replacementRange:(NSRange)range {
772801
_eventProducedOutput |= true;
773802

774803
if (range.location != NSNotFound) {
775-
// The selected range can actually have negative numbers, since it can start
776-
// at the end of the range if the user selected the text going backwards.
777-
// Cast to a signed type to determine whether or not the selection is reversed.
778-
long signedLength = static_cast<long>(range.length);
779-
long location = range.location;
780-
long textLength = _activeModel->text_range().end();
781-
782-
size_t base = std::clamp(location, 0L, textLength);
783-
size_t extent = std::clamp(location + signedLength, 0L, textLength);
784-
785-
_activeModel->SetSelection(flutter::TextRange(base, extent));
804+
_activeModel->SetSelection(ClampNSRange(range, _activeModel->text_range().end()));
786805
} else if (_activeModel->composing() &&
787806
!(_activeModel->composing_range() == _activeModel->selection())) {
788807
// When confirmed by Japanese IME, string replaces range of composing_range.
@@ -902,10 +921,11 @@ - (void)setMarkedText:(id)string
902921
// the case, because in situations where the replacementRange is actually
903922
// specified (i.e. when switching between characters equivalent after long
904923
// key press) the replacementRange is provided while there is no composition.
924+
//
925+
// The range is clamped to the text because SetComposingRange rejects ranges
926+
// that don't fit.
905927
_activeModel->SetComposingRange(
906-
flutter::TextRange(replacementRange.location,
907-
replacementRange.location + replacementRange.length),
908-
0);
928+
ClampNSRange(replacementRange, _activeModel->text_range().end()), 0);
909929
}
910930

911931
flutter::TextRange composingBeforeChange = _activeModel->composing_range();
@@ -914,12 +934,20 @@ - (void)setMarkedText:(id)string
914934
// Input string may be NSString or NSAttributedString.
915935
BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
916936
const NSString* rawString = isAttributedString ? [string string] : string;
917-
_activeModel->UpdateComposingText(
918-
(const char16_t*)[rawString cStringUsingEncoding:NSUTF16StringEncoding],
919-
flutter::TextRange(selectedRange.location, selectedRange.location + selectedRange.length));
937+
938+
// Copy the UTF-16 code units directly. The C string form truncates at an
939+
// embedded NUL and returns NULL when the string cannot be converted.
940+
std::u16string marked_text_utf16(rawString.length, u'\0');
941+
[rawString getCharacters:reinterpret_cast<unichar*>(marked_text_utf16.data())
942+
range:NSMakeRange(0, marked_text_utf16.length())];
943+
944+
// selectedRange is provided by the IME. Re-clamp to the text.
945+
// NSNotFound (no selection), clamps to end of the marked text.
946+
_activeModel->UpdateComposingText(marked_text_utf16,
947+
ClampNSRange(selectedRange, marked_text_utf16.length()));
920948

921949
if (_enableDeltaModel) {
922-
std::string marked_text = [rawString UTF8String];
950+
std::string marked_text = rawString ? [rawString UTF8String] : "";
923951
[self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange,
924952
selectionBeforeChange.collapsed()
925953
? composingBeforeChange

0 commit comments

Comments
 (0)