Merge cherrypicks of [12364563, 12364330, 12364331, 12364332, 12363743, 12364605, 12363956, 12363957, 12363958, 12364309, 12364483, 12364484, 12364564, 12364333, 12364334, 12364335, 12364336, 12364337, 12364607] into rvc-release am: a790490ec9
Original change: https://googleplex-android-review.googlesource.com/c/platform/system/core/+/12364682
Change-Id: I5d460e022ec749177c37301bed64f48d8b8d272e
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index d13548e..9d50e0b 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -322,8 +322,14 @@
n = vsnprintf(nullptr, 0, fmt, tmp_args);
va_end(tmp_args);
- if (n != 0) {
+ if (n < 0) return UNKNOWN_ERROR;
+
+ if (n > 0) {
size_t oldLength = length();
+ if ((size_t)n > SIZE_MAX - 1 ||
+ oldLength > SIZE_MAX - (size_t)n - 1) {
+ return NO_MEMORY;
+ }
char* buf = lockBuffer(oldLength + n);
if (buf) {
vsnprintf(buf + oldLength, n + 1, fmt, args);