
Index: LibRaw-0.21.4/src/decoders/decoders_dcraw.cpp
===================================================================
--- LibRaw-0.21.4.orig/src/decoders/decoders_dcraw.cpp
+++ LibRaw-0.21.4/src/decoders/decoders_dcraw.cpp
@@ -96,13 +96,37 @@ ushort *LibRaw::make_decoder_ref(const u
   count = (*source += 16) - 17;
   for (max = 16; max && !count[max]; max--)
     ;
-  huff = (ushort *)calloc(1 + (1 << max), sizeof *huff);
+
+  uint32_t tsize = 1 << max;
+  huff = (ushort *)calloc(1 + tsize, sizeof *huff);
+  if (!huff) throw LIBRAW_EXCEPTION_ALLOC;
+
   huff[0] = max;
+  int pos = 0;
+
   for (h = len = 1; len <= max; len++)
+  {
     for (i = 0; i < count[len]; i++, ++*source)
+    {
+      pos++;
+      if (pos > 256)
+      {
+        free(huff);
+        throw LIBRAW_EXCEPTION_IO_CORRUPT;
+      }
+
       for (j = 0; j < 1 << (max - len); j++)
-        if (h <= 1 << max)
-          huff[h++] = len << 8 | **source;
+      {
+        if (h > (int)tsize)
+        {
+          free(huff);
+          throw LIBRAW_EXCEPTION_IO_CORRUPT;
+        }
+        huff[h++] = len << 8 | **source;
+      }
+    }
+  }
+
   return huff;
 }
 
