0022-jp2_apply_pclr_overflow.patch revision 4d3acf4ec42bf6e838f9060103aff98fbf170794
1diff --git a/third_party/libopenjpeg20/jp2.c b/third_party/libopenjpeg20/jp2.c
2index a6648f6..8128d98 100644
3--- a/third_party/libopenjpeg20/jp2.c
4+++ b/third_party/libopenjpeg20/jp2.c
5@@ -972,6 +972,14 @@ static void opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color)
6 	nr_channels = color->jp2_pclr->nr_channels;
7 
8 	old_comps = image->comps;
9+	/* Overflow check: prevent integer overflow */
10+	for (i = 0; i < nr_channels; ++i) {
11+		cmp = cmap[i].cmp;
12+		if (old_comps[cmp].h == 0 || old_comps[cmp].w > ((OPJ_UINT32)-1) / sizeof(OPJ_INT32) / old_comps[cmp].h) {
13+			return;
14+		}
15+	}
16+
17 	new_comps = (opj_image_comp_t*)
18 			opj_malloc(nr_channels * sizeof(opj_image_comp_t));
19 	if (!new_comps) {
20@@ -1011,22 +1019,28 @@ static void opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color)
21 		/* Palette mapping: */
22 		cmp = cmap[i].cmp; pcol = cmap[i].pcol;
23 		src = old_comps[cmp].data;
24-    assert( src );
25+		dst = new_comps[i].data;
26 		max = new_comps[i].w * new_comps[i].h;
27 
28+		/* Prevent null pointer access */
29+		if (!src || !dst) {
30+			for (j = 0; j < nr_channels; ++j) {
31+				opj_free(new_comps[j].data);
32+			}
33+			opj_free(new_comps);
34+			new_comps = NULL;
35+			return;
36+		}
37+
38 		/* Direct use: */
39     if(cmap[i].mtyp == 0) {
40       assert( cmp == 0 ); // probably wrong.
41-      dst = new_comps[i].data;
42-      assert( dst );
43       for(j = 0; j < max; ++j) {
44         dst[j] = src[j];
45       }
46     }
47     else {
48       assert( i == pcol ); // probably wrong?
49-      dst = new_comps[i].data;
50-      assert( dst );
51       for(j = 0; j < max; ++j) {
52         /* The index */
53         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
54