Check size before writting

Before writting to the stream buffer make sure that we won't walk off the end
of the allocated size.

In this specific case the dest_size of the buffer is 0, so we're basically just
looping over to free the temp results.

BUG=chromium:697847

Change-Id: I229eea96179692216cb2685facbb7d5379c501c7
Reviewed-on: https://pdfium-review.googlesource.com/2903
Commit-Queue: dsinclair <dsinclair@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
diff --git a/core/fxcodec/codec/fx_codec_flate.cpp b/core/fxcodec/codec/fx_codec_flate.cpp
index 3cffc0b..b17e202 100644
--- a/core/fxcodec/codec/fx_codec_flate.cpp
+++ b/core/fxcodec/codec/fx_codec_flate.cpp
@@ -587,6 +587,10 @@
       cur_buf = FX_Alloc(uint8_t, buf_size + 1);
       cur_buf[buf_size] = '\0';
     }
+
+    // The TotalOut size returned from the library may not be big enough to
+    // handle the content the library returns. We can only handle items
+    // up to 4GB in size.
     dest_size = FPDFAPI_FlateGetTotalOut(context);
     offset = FPDFAPI_FlateGetTotalIn(context);
     if (result_tmp_bufs.size() == 1) {
@@ -594,14 +598,17 @@
     } else {
       uint8_t* result_buf = FX_Alloc(uint8_t, dest_size);
       uint32_t result_pos = 0;
+      uint32_t remaining = dest_size;
       for (size_t i = 0; i < result_tmp_bufs.size(); i++) {
         uint8_t* tmp_buf = result_tmp_bufs[i];
         uint32_t tmp_buf_size = buf_size;
         if (i == result_tmp_bufs.size() - 1) {
           tmp_buf_size = last_buf_size;
         }
-        FXSYS_memcpy(result_buf + result_pos, tmp_buf, tmp_buf_size);
-        result_pos += tmp_buf_size;
+        uint32_t cp_size = std::min(tmp_buf_size, remaining);
+        FXSYS_memcpy(result_buf + result_pos, tmp_buf, cp_size);
+        result_pos += cp_size;
+        remaining -= cp_size;
         FX_Free(result_tmp_bufs[i]);
       }
       dest_buf = result_buf;