Restrict code size in CGifLZWDecoder

The code_size variable is the number of bits. We should make sure that
the size is at most 31 to avoid having undefined shifts etc.

BUG=620661

Change-Id: Ia533386d01de93a55048cfd63d63989b2731a210
Reviewed-on: https://pdfium-review.googlesource.com/2161
Reviewed-by: dsinclair <dsinclair@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Commit-Queue: Nicolás Peña <npm@chromium.org>
diff --git a/core/fxcodec/lgif/fx_gif.cpp b/core/fxcodec/lgif/fx_gif.cpp
index 0e26269..87525b2 100644
--- a/core/fxcodec/lgif/fx_gif.cpp
+++ b/core/fxcodec/lgif/fx_gif.cpp
@@ -37,6 +37,7 @@
 
 void CGifLZWDecoder::InitTable(uint8_t code_len) {
   code_size = code_len;
+  ASSERT(code_size < 32);
   code_clear = 1 << code_size;
   code_end = code_clear + 1;
   bits_left = 0;
@@ -230,6 +231,7 @@
                            uint8_t*& dst_buf,
                            uint32_t& offset) {
   code_size = code_len + 1;
+  ASSERT(code_size < 32);
   src_bit_cut = code_size;
   if (code_len == 0) {
     src_bit_cut = 1;
@@ -889,6 +891,12 @@
         return 0;
       }
     }
+    if (gif_image_ptr->image_code_size >= 32) {
+      FX_Free(gif_image_ptr->image_row_buf);
+      gif_image_ptr->image_row_buf = nullptr;
+      gif_error(gif_ptr, "Error Invalid Code Size");
+      return 0;
+    }
     if (!gif_ptr->img_decoder_ptr)
       gif_ptr->img_decoder_ptr = new CGifLZWDecoder(gif_ptr->err_ptr);
     gif_ptr->img_decoder_ptr->InitTable(gif_image_ptr->image_code_size);
@@ -1156,6 +1164,8 @@
     GifGF& gf = (GifGF&)gif_ptr->lsd_ptr->global_flag;
     code_bit = gf.pal_bits;
   }
+  if (code_bit >= 31)
+    return false;
   gif_ptr->img_encoder_ptr->Start(code_bit, gif_ptr->src_buf, dst_buf,
                                   gif_ptr->cur_offset);
   uint32_t i;