libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index 771d312..755e0d1 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -104,20 +104,21 @@
{
if (len == 0) return getEmptyString();
- const ssize_t bytes = utf16_to_utf8_length(in, len);
- if (bytes < 0) {
+ // Allow for closing '\0'
+ const ssize_t resultStrLen = utf16_to_utf8_length(in, len) + 1;
+ if (resultStrLen < 1) {
return getEmptyString();
}
- SharedBuffer* buf = SharedBuffer::alloc(bytes+1);
+ SharedBuffer* buf = SharedBuffer::alloc(resultStrLen);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
- char* str = (char*)buf->data();
- utf16_to_utf8(in, len, str);
- return str;
+ char* resultStr = (char*)buf->data();
+ utf16_to_utf8(in, len, resultStr, resultStrLen);
+ return resultStr;
}
static char* allocFromUTF32(const char32_t* in, size_t len)
@@ -126,21 +127,21 @@
return getEmptyString();
}
- const ssize_t bytes = utf32_to_utf8_length(in, len);
- if (bytes < 0) {
+ const ssize_t resultStrLen = utf32_to_utf8_length(in, len) + 1;
+ if (resultStrLen < 1) {
return getEmptyString();
}
- SharedBuffer* buf = SharedBuffer::alloc(bytes+1);
+ SharedBuffer* buf = SharedBuffer::alloc(resultStrLen);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
- char* str = (char*) buf->data();
- utf32_to_utf8(in, len, str);
+ char* resultStr = (char*) buf->data();
+ utf32_to_utf8(in, len, resultStr, resultStrLen);
- return str;
+ return resultStr;
}
// ---------------------------------------------------------------------------