Add CFX_WideTextBuf::ExpandWideBuf().

Consolidate all of CFX_WideTextBuf's ExpandBuf() calls into one place.
Use FX_SAFE_SIZE_T in ExpandWideBuf() to make sure the buffer size does
not overflow.

Change-Id: I374170f225d44c1e7d920fe900090da010e9bf00
Reviewed-on: https://pdfium-review.googlesource.com/c/pdfium/+/67970
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Commit-Queue: Lei Zhang <thestig@chromium.org>
diff --git a/core/fxcrt/cfx_widetextbuf.cpp b/core/fxcrt/cfx_widetextbuf.cpp
index 44b649d..90e4de5 100644
--- a/core/fxcrt/cfx_widetextbuf.cpp
+++ b/core/fxcrt/cfx_widetextbuf.cpp
@@ -6,6 +6,8 @@
 
 #include "core/fxcrt/cfx_widetextbuf.h"
 
+#include "core/fxcrt/fx_safe_types.h"
+
 size_t CFX_WideTextBuf::GetLength() const {
   return m_DataSize / sizeof(wchar_t);
 }
@@ -29,7 +31,7 @@
 }
 
 void CFX_WideTextBuf::AppendChar(wchar_t ch) {
-  ExpandBuf(sizeof(wchar_t));
+  ExpandWideBuf(1);
   *reinterpret_cast<wchar_t*>(m_pBuffer.get() + m_DataSize) = ch;
   m_DataSize += sizeof(wchar_t);
 }
@@ -39,7 +41,7 @@
 }
 
 CFX_WideTextBuf& CFX_WideTextBuf::operator<<(ByteStringView ascii) {
-  ExpandBuf(ascii.GetLength() * sizeof(wchar_t));
+  ExpandWideBuf(ascii.GetLength());
   for (uint8_t ch : ascii) {
     *reinterpret_cast<wchar_t*>(m_pBuffer.get() + m_DataSize) = ch;
     m_DataSize += sizeof(wchar_t);
@@ -61,7 +63,7 @@
   char buf[32];
   FXSYS_itoa(i, buf, 10);
   size_t len = strlen(buf);
-  ExpandBuf(len * sizeof(wchar_t));
+  ExpandWideBuf(len);
   wchar_t* str = reinterpret_cast<wchar_t*>(m_pBuffer.get() + m_DataSize);
   for (size_t j = 0; j < len; j++) {
     *str++ = buf[j];
@@ -73,7 +75,7 @@
 CFX_WideTextBuf& CFX_WideTextBuf::operator<<(double f) {
   char buf[32];
   size_t len = FloatToString((float)f, buf);
-  ExpandBuf(len * sizeof(wchar_t));
+  ExpandWideBuf(len);
   wchar_t* str = reinterpret_cast<wchar_t*>(m_pBuffer.get() + m_DataSize);
   for (size_t i = 0; i < len; i++) {
     *str++ = buf[i];
@@ -91,3 +93,9 @@
   AppendBlock(buf.m_pBuffer.get(), buf.m_DataSize);
   return *this;
 }
+
+void CFX_WideTextBuf::ExpandWideBuf(size_t char_count) {
+  FX_SAFE_SIZE_T safe_count = char_count;
+  safe_count *= sizeof(wchar_t);
+  ExpandBuf(safe_count.ValueOrDie());
+}
diff --git a/core/fxcrt/cfx_widetextbuf.h b/core/fxcrt/cfx_widetextbuf.h
index 2232799..90daa48 100644
--- a/core/fxcrt/cfx_widetextbuf.h
+++ b/core/fxcrt/cfx_widetextbuf.h
@@ -32,6 +32,9 @@
   CFX_WideTextBuf& operator<<(WideStringView str);
   CFX_WideTextBuf& operator<<(const WideString& str);
   CFX_WideTextBuf& operator<<(const CFX_WideTextBuf& buf);
+
+ private:
+  void ExpandWideBuf(size_t char_count);
 };
 
 #endif  // CORE_FXCRT_CFX_WIDETEXTBUF_H_