MdeModulePkg BrotliLib: Fix the regression logic issue in loop
[mirror_edk2.git] / MdeModulePkg / Library / BrotliCustomDecompressLib / dec / decode.c
index 7ba1d0512e251f806d56aff5b7c6c2791b8bf465..6557ba67d56b6fb043a3bc30e3391b72e3a2ec64 100644 (file)
@@ -802,6 +802,7 @@ static BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table,
   uint32_t code;\r
   uint32_t nbits;\r
   code = ReadSymbol(table, br);\r
+  if (code >= BROTLI_NUM_BLOCK_LEN_SYMBOLS) code = BROTLI_NUM_BLOCK_LEN_SYMBOLS - 1;\r
   nbits = kBlockLengthPrefixCode[code].nbits; /* nbits == 2..24 */\r
   return kBlockLengthPrefixCode[code].offset + BrotliReadBits(br, nbits);\r
 }\r
@@ -854,6 +855,7 @@ static BROTLI_NOINLINE void InverseMoveToFrontTransform(
   uint32_t i = 4;\r
   uint32_t upper_bound = state->mtf_upper_bound;\r
   uint8_t* mtf = &state->mtf[4];  /* Make mtf[-1] addressable. */\r
+  uint8_t* mtft = &state->mtf[3];\r
   /* Load endian-aware constant. */\r
   const uint8_t b0123[4] = {0, 1, 2, 3};\r
   uint32_t pattern;\r
@@ -872,13 +874,13 @@ static BROTLI_NOINLINE void InverseMoveToFrontTransform(
   for (i = 0; i < v_len; ++i) {\r
     int index = v[i];\r
     uint8_t value = mtf[index];\r
-    upper_bound |= v[i];\r
+    upper_bound |= (uint32_t)v[i];\r
     v[i] = value;\r
-    mtf[-1] = value;\r
-    do {\r
+    mtft[0] = value;\r
+    while (index >= 0) {\r
+      mtft[index + 1] = mtft[index];\r
       index--;\r
-      mtf[index + 1] = mtf[index];\r
-    } while (index >= 0);\r
+    }\r
   }\r
   /* Remember amount of elements to be reinitialized. */\r
   state->mtf_upper_bound = upper_bound;\r
@@ -1498,6 +1500,7 @@ static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
       return BROTLI_FALSE;\r
     }\r
   }\r
+  if (cmd_code >= BROTLI_NUM_COMMAND_SYMBOLS) cmd_code = BROTLI_NUM_COMMAND_SYMBOLS - 1;\r
   v = kCmdLut[cmd_code];\r
   s->distance_code = v.distance_code;\r
   s->distance_context = v.context;\r
@@ -2209,7 +2212,9 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
         }\r
         s->max_distance = s->max_backward_distance;\r
         if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {\r
-          memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);\r
+          if (s->ringbuffer != 0) {\r
+            memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);\r
+          }\r
           if (s->meta_block_remaining_len == 0) {\r
             /* Next metablock, if any */\r
             s->state = BROTLI_STATE_METABLOCK_DONE;\r