Skip to content

Commit

Permalink
ICU-21032 Backport of ICU-20958 to 61.x
Browse files Browse the repository at this point in the history
Backport of:
ICU-20958 Prevent SEGV_MAPERR in append

See #971

(cherry picked from commit b7d08bc)
  • Loading branch information
FrankYFTang authored and srl295 committed Mar 27, 2020
1 parent c01cb39 commit cafe6a0
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
21 changes: 20 additions & 1 deletion icu4c/source/common/unistr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,26 @@ UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLeng
}

int32_t oldLength = length();
int32_t newLength = oldLength + srcLength;
int32_t newLength;
if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {
setToBogus();
return *this;
}

// Check for append onto ourself
const UChar* oldArray = getArrayStart();
if (isBufferWritable() &&
oldArray < srcChars + srcLength &&
srcChars < oldArray + oldLength) {
// Copy into a new UnicodeString and start over
UnicodeString copy(srcChars, srcLength);
if (copy.isBogus()) {
setToBogus();
return *this;
}
return doAppend(copy.getArrayStart(), 0, srcLength);
}

// optimize append() onto a large-enough, owned string
if((newLength <= getCapacity() && isBufferWritable()) ||
cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {
Expand Down
3 changes: 2 additions & 1 deletion icu4c/source/test/intltest/ustrtest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ void UnicodeStringTest::runIndexedTest( int32_t index, UBool exec, const char* &
TESTCASE_AUTO(TestUInt16Pointers);
TESTCASE_AUTO(TestWCharPointers);
TESTCASE_AUTO(TestNullPointers);
TESTCASE_AUTO(TestUnicodeStringInsertAppendToSelf);
TESTCASE_AUTO(TestLargeAppend);
TESTCASE_AUTO_END;
}

Expand Down Expand Up @@ -2246,7 +2248,6 @@ UnicodeStringTest::TestNullPointers() {
UnicodeString(u"def").extract(nullptr, 0, errorCode);
assertEquals("buffer overflow extracting to nullptr", U_BUFFER_OVERFLOW_ERROR, errorCode);
}

void UnicodeStringTest::TestUnicodeStringInsertAppendToSelf() {
IcuTestErrorCode status(*this, "TestUnicodeStringAppendToSelf");

Expand Down
2 changes: 2 additions & 0 deletions icu4c/source/test/intltest/ustrtest.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ class UnicodeStringTest: public IntlTest {
void TestUInt16Pointers();
void TestWCharPointers();
void TestNullPointers();
void TestUnicodeStringInsertAppendToSelf();
void TestLargeAppend();
};

#endif

0 comments on commit cafe6a0

Please sign in to comment.