1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
--- a/gif2apng.cpp
+++ b/gif2apng.cpp
@@ -99,7 +99,7 @@ int cmp_colors( const void *arg1, const
return (int)(((COLORS*)arg1)->b) - (int)(((COLORS*)arg2)->b);
}
-void DecodeLZW(unsigned char * img, FILE * f1)
+void DecodeLZW(unsigned char * img, unsigned int img_size, FILE * f1)
{
int i, bits, codesize, codemask, clearcode, nextcode, lastcode;
unsigned int j;
@@ -113,6 +113,7 @@ void DecodeLZW(unsigned char * img, FILE
unsigned char *pstr = str;
unsigned char *pout = img;
unsigned char mincodesize;
+ unsigned int bytes_written = 0;
if (fread(&mincodesize, 1, 1, f1) != 1) return;
@@ -156,7 +157,15 @@ void DecodeLZW(unsigned char * img, FILE
if (lastcode == -1)
{
- *pout++ = suffix[code];
+ if (bytes_written < img_size)
+ {
+ *pout++ = suffix[code];
+ bytes_written++;
+ } else
+ {
+ printf("Invalid image size\n");
+ exit(1);
+ }
firstchar = lastcode = code;
continue;
}
@@ -191,7 +200,14 @@ void DecodeLZW(unsigned char * img, FILE
do
{
- *pout++ = *--pstr;
+ if (bytes_written < img_size)
+ {
+ *pout++ = *--pstr;
+ bytes_written++;
+ } else {
+ printf("Invalid image size\n");
+ exit(1);
+ }
}
while (pstr > str);
}
@@ -478,6 +494,7 @@ int main(int argc, char** argv)
unsigned char * over2;
unsigned char * over3;
unsigned short * delays;
+ unsigned int buffer_size = 0; // size of the buffer
printf("\ngif2apng 1.9");
@@ -598,8 +615,9 @@ int main(int argc, char** argv)
rowbytes = w;
imagesize = w*h;
grayscale = 1;
+ buffer_size = imagesize*2; // imagesize is overwritten at some point
- buffer = (unsigned char *)malloc(imagesize*2);
+ buffer = (unsigned char *)malloc(buffer_size);
if (buffer == NULL)
{
printf("Error: not enough memory\n");
@@ -660,7 +678,7 @@ int main(int argc, char** argv)
}
imagesize = w0*h0;
- DecodeLZW(buffer, f1);
+ DecodeLZW(buffer, buffer_size, f1);
for (i=0; i<256; i++)
num[i] = 0;
@@ -1110,7 +1128,7 @@ int main(int argc, char** argv)
memcpy(rest, frame0, imagesize);
- DecodeLZW(buffer, f1);
+ DecodeLZW(buffer, buffer_size, f1);
h2 = (h0-1)/2;
|