xref: /PHP-7.1/ext/gd/libgd/gd_gd2.c (revision d2274b01)
1 /*
2    * gd_gd2.c
3    *
4    * Implements the I/O and support for the GD2 format.
5    *
6    * Changing the definition of GD2_DBG (below) will cause copious messages
7    * to be displayed while it processes requests.
8    *
9    * Designed, Written & Copyright 1999, Philip Warner.
10    *
11  */
12 
13 #include <stdio.h>
14 #include <errno.h>
15 #include <math.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include "gd.h"
19 #include "gdhelpers.h"
20 
21 #include <zlib.h>
22 
23 #define TRUE 1
24 #define FALSE 0
25 
26 /* 2.11: not part of the API, as the save routine can figure it out
27  *	from im->trueColor, and the load routine doesn't need to tell
28  *	the end user the saved format. NOTE: adding 2 is assumed
29  *	to result in the correct format value for truecolor!
30 */
31 #define GD2_FMT_TRUECOLOR_RAW 3
32 #define GD2_FMT_TRUECOLOR_COMPRESSED 4
33 
34 #define gd2_compressed(fmt) (((fmt) == GD2_FMT_COMPRESSED) || ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
35 #define gd2_truecolor(fmt) (((fmt) == GD2_FMT_TRUECOLOR_RAW) || ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
36 
37 /* Use this for commenting out debug-print statements. */
38 /* Just use the first '#define' to allow all the prints... */
39 /* #define GD2_DBG(s) (s) */
40 #define GD2_DBG(s)
41 
42 typedef struct
43 {
44 	int offset;
45 	int size;
46 } t_chunk_info;
47 
48 extern int _gdGetColors(gdIOCtx * in, gdImagePtr im, int gd2xFlag);
49 extern void _gdPutColors(gdImagePtr im, gdIOCtx * out);
50 
51 /* */
52 /* Read the extra info in the gd2 header. */
53 /* */
_gd2GetHeader(gdIOCtxPtr in,int * sx,int * sy,int * cs,int * vers,int * fmt,int * ncx,int * ncy,t_chunk_info ** chunkIdx)54 static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)
55 {
56 	int i;
57 	int ch;
58 	char id[5];
59 	t_chunk_info *cidx;
60 	int sidx;
61 	int nc;
62 
63 	GD2_DBG(php_gd_error("Reading gd2 header info"));
64 
65 	for (i = 0; i < 4; i++) {
66 		ch = gdGetC(in);
67 		if (ch == EOF) {
68 			goto fail1;
69 		}
70 		id[i] = ch;
71 	}
72 	id[4] = 0;
73 
74 	GD2_DBG(php_gd_error("Got file code: %s", id));
75 
76 	/* Equiv. of 'magick'.  */
77 	if (strcmp(id, GD2_ID) != 0) {
78 		GD2_DBG(php_gd_error("Not a valid gd2 file"));
79 		goto fail1;
80 	}
81 
82 	/* Version */
83 	if (gdGetWord(vers, in) != 1) {
84 		goto fail1;
85 	}
86 	GD2_DBG(php_gd_error("Version: %d", *vers));
87 
88 	if ((*vers != 1) && (*vers != 2)) {
89 		GD2_DBG(php_gd_error("Bad version: %d", *vers));
90 		goto fail1;
91 	}
92 
93 	/* Image Size */
94 	if (!gdGetWord(sx, in)) {
95 		GD2_DBG(php_gd_error("Could not get x-size"));
96 		goto fail1;
97 	}
98 	if (!gdGetWord(sy, in)) {
99 		GD2_DBG(php_gd_error("Could not get y-size"));
100 		goto fail1;
101 	}
102 	GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy));
103 
104 	/* Chunk Size (pixels, not bytes!) */
105 	if (gdGetWord(cs, in) != 1) {
106 		goto fail1;
107 	}
108 	GD2_DBG(php_gd_error("ChunkSize: %d", *cs));
109 
110 	if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
111 		GD2_DBG(php_gd_error("Bad chunk size: %d", *cs));
112 		goto fail1;
113 	}
114 
115 	/* Data Format */
116 	if (gdGetWord(fmt, in) != 1) {
117 		goto fail1;
118 	}
119 	GD2_DBG(php_gd_error("Format: %d", *fmt));
120 
121 	if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
122 		GD2_DBG(php_gd_error("Bad data format: %d", *fmt));
123 		goto fail1;
124 	}
125 
126 	/* # of chunks wide */
127 	if (gdGetWord(ncx, in) != 1) {
128 		goto fail1;
129 	}
130 	GD2_DBG(php_gd_error("%d Chunks Wide", *ncx));
131 
132 	/* # of chunks high */
133 	if (gdGetWord(ncy, in) != 1) {
134 		goto fail1;
135 	}
136 	GD2_DBG(php_gd_error("%d Chunks vertically", *ncy));
137 
138 	if (gd2_compressed(*fmt)) {
139 		if (*ncx <= 0 || *ncy <= 0 || *ncx > INT_MAX / *ncy) {
140 			GD2_DBG(printf ("Illegal chunk counts: %d * %d\n", *ncx, *ncy));
141 			goto fail1;
142 		}
143 		nc = (*ncx) * (*ncy);
144 		GD2_DBG(php_gd_error("Reading %d chunk index entries", nc));
145 		if (overflow2(sizeof(t_chunk_info), nc)) {
146 			goto fail1;
147 		}
148 		sidx = sizeof(t_chunk_info) * nc;
149 		if (sidx <= 0) {
150 			goto fail1;
151 		}
152 		cidx = gdCalloc(sidx, 1);
153 		if (cidx == NULL) {
154 			goto fail1;
155 		}
156 
157 		for (i = 0; i < nc; i++) {
158 			if (gdGetInt(&cidx[i].offset, in) != 1) {
159 				gdFree(cidx);
160 				goto fail1;
161 			}
162 			if (gdGetInt(&cidx[i].size, in) != 1) {
163 				gdFree(cidx);
164 				goto fail1;
165 			}
166 			if (cidx[i].offset < 0 || cidx[i].size < 0) {
167 				gdFree(cidx);
168 				goto fail1;
169 			}
170 		}
171 		*chunkIdx = cidx;
172 	}
173 
174 	GD2_DBG(php_gd_error("gd2 header complete"));
175 
176 	return 1;
177 
178 fail1:
179 	return 0;
180 }
181 
_gd2CreateFromFile(gdIOCtxPtr in,int * sx,int * sy,int * cs,int * vers,int * fmt,int * ncx,int * ncy,t_chunk_info ** cidx)182 static gdImagePtr _gd2CreateFromFile (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** cidx)
183 {
184 	gdImagePtr im;
185 
186 	if (_gd2GetHeader (in, sx, sy, cs, vers, fmt, ncx, ncy, cidx) != 1) {
187 		GD2_DBG(php_gd_error("Bad GD2 header"));
188 		goto fail1;
189 	}
190 
191 	if (gd2_truecolor(*fmt)) {
192 		im = gdImageCreateTrueColor(*sx, *sy);
193 	} else {
194 		im = gdImageCreate(*sx, *sy);
195 	}
196 	if (im == NULL) {
197 		GD2_DBG(php_gd_error("Could not create gdImage"));
198 		goto fail2;
199 	}
200 
201 	if (!_gdGetColors(in, im, (*vers) == 2)) {
202 		GD2_DBG(php_gd_error("Could not read color palette"));
203 		goto fail3;
204 	}
205 	GD2_DBG(php_gd_error("Image palette completed: %d colours", im->colorsTotal));
206 
207 	return im;
208 
209 fail3:
210 	gdImageDestroy(im);
211 fail2:
212 	gdFree(*cidx);
213 fail1:
214 	return 0;
215 }
216 
_gd2ReadChunk(int offset,char * compBuf,int compSize,char * chunkBuf,uLongf * chunkLen,gdIOCtx * in)217 static int _gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf, uLongf * chunkLen, gdIOCtx * in)
218 {
219 	int zerr;
220 
221 	if (gdTell(in) != offset) {
222 		GD2_DBG(php_gd_error("Positioning in file to %d", offset));
223 		gdSeek(in, offset);
224 	} else {
225 		GD2_DBG(php_gd_error("Already Positioned in file to %d", offset));
226 	}
227 
228 	/* Read and uncompress an entire chunk. */
229 	GD2_DBG(php_gd_error("Reading file"));
230 	if (gdGetBuf(compBuf, compSize, in) != compSize) {
231 		return FALSE;
232 	}
233 	GD2_DBG(php_gd_error("Got %d bytes. Uncompressing into buffer of %d bytes", compSize, (int)*chunkLen));
234 	zerr = uncompress((unsigned char *) chunkBuf, chunkLen, (unsigned char *) compBuf, compSize);
235 	if (zerr != Z_OK) {
236 		GD2_DBG(php_gd_error("Error %d from uncompress", zerr));
237 		return FALSE;
238 	}
239 	GD2_DBG(php_gd_error("Got chunk"));
240 
241 	return TRUE;
242 }
243 
gdImageCreateFromGd2(FILE * inFile)244 gdImagePtr gdImageCreateFromGd2 (FILE * inFile)
245 {
246 	gdIOCtx *in = gdNewFileCtx(inFile);
247 	gdImagePtr im;
248 
249 	im = gdImageCreateFromGd2Ctx(in);
250 
251 	in->gd_free(in);
252 
253 	return im;
254 }
255 
gdImageCreateFromGd2Ptr(int size,void * data)256 gdImagePtr gdImageCreateFromGd2Ptr (int size, void *data)
257 {
258 	gdImagePtr im;
259 	gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
260 	im = gdImageCreateFromGd2Ctx(in);
261 	in->gd_free(in);
262 
263 	return im;
264 }
265 
gdImageCreateFromGd2Ctx(gdIOCtxPtr in)266 gdImagePtr gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
267 {
268 	int sx, sy;
269 	int i;
270 	int ncx, ncy, nc, cs, cx, cy;
271 	int x, y, ylo, yhi, xlo, xhi;
272 	int vers, fmt;
273 	t_chunk_info *chunkIdx = NULL;	/* So we can gdFree it with impunity. */
274 	unsigned char *chunkBuf = NULL;	/* So we can gdFree it with impunity. */
275 	int chunkNum = 0;
276 	int chunkMax = 0;
277 	uLongf chunkLen;
278 	int chunkPos = 0;
279 	int compMax = 0;
280 	int bytesPerPixel;
281 	char *compBuf = NULL;		/* So we can gdFree it with impunity. */
282 
283 	gdImagePtr im;
284 
285 	/* Get the header */
286 	if (!(im = _gd2CreateFromFile(in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx))) {
287 		 return 0;
288 	}
289 
290 	bytesPerPixel = im->trueColor ? 4 : 1;
291 	nc = ncx * ncy;
292 
293 	if (gd2_compressed(fmt)) {
294 		/* Find the maximum compressed chunk size. */
295 		compMax = 0;
296 		for (i = 0; (i < nc); i++) {
297 			if (chunkIdx[i].size > compMax) {
298 				compMax = chunkIdx[i].size;
299 			}
300 		}
301 		compMax++;
302 
303 		/* Allocate buffers */
304 		chunkMax = cs * bytesPerPixel * cs;
305 		if (chunkMax <= 0) {
306 			return 0;
307 		}
308 		chunkBuf = gdCalloc(chunkMax, 1);
309 		compBuf = gdCalloc(compMax, 1);
310 
311 		GD2_DBG(php_gd_error("Largest compressed chunk is %d bytes", compMax));
312 	}
313 
314 	/* Read the data... */
315 	for (cy = 0; (cy < ncy); cy++) {
316 		for (cx = 0; (cx < ncx); cx++) {
317 			ylo = cy * cs;
318 			yhi = ylo + cs;
319 			if (yhi > im->sy) {
320 				yhi = im->sy;
321 			}
322 
323 			GD2_DBG(php_gd_error("Processing Chunk %d (%d, %d), y from %d to %d", chunkNum, cx, cy, ylo, yhi));
324 
325 			if (gd2_compressed(fmt)) {
326 				chunkLen = chunkMax;
327 
328 				if (!_gd2ReadChunk(chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *) chunkBuf, &chunkLen, in)) {
329 					GD2_DBG(php_gd_error("Error reading comproessed chunk"));
330 					goto fail2;
331 				}
332 
333 				chunkPos = 0;
334 			}
335 
336 			for (y = ylo; (y < yhi); y++) {
337 				xlo = cx * cs;
338 				xhi = xlo + cs;
339 				if (xhi > im->sx) {
340 					xhi = im->sx;
341 				}
342 
343 				if (!gd2_compressed(fmt)) {
344 					for (x = xlo; x < xhi; x++) {
345 						if (im->trueColor) {
346 							if (!gdGetInt(&im->tpixels[y][x], in)) {
347 								php_gd_error("gd2: EOF while reading\n");
348 								gdImageDestroy(im);
349 								return NULL;
350 							}
351 						} else {
352 							int ch;
353 							if (!gdGetByte(&ch, in)) {
354 								php_gd_error("gd2: EOF while reading\n");
355 								gdImageDestroy(im);
356 								return NULL;
357 							}
358 							im->pixels[y][x] = ch;
359 						}
360 					}
361 				} else {
362 					for (x = xlo; x < xhi; x++) {
363 						if (im->trueColor) {
364 							/* 2.0.1: work around a gcc bug by being verbose. TBB */
365 							int a = chunkBuf[chunkPos++] << 24;
366 							int r = chunkBuf[chunkPos++] << 16;
367 							int g = chunkBuf[chunkPos++] << 8;
368 							int b = chunkBuf[chunkPos++];
369 							im->tpixels[y][x] = a + r + g + b;
370 						} else {
371 							im->pixels[y][x] = chunkBuf[chunkPos++];
372 						}
373 					}
374 				}
375 			}
376 			chunkNum++;
377 		}
378 	}
379 
380 	GD2_DBG(php_gd_error("Freeing memory"));
381 
382 	if (chunkBuf) {
383 		gdFree(chunkBuf);
384 	}
385 	if (compBuf) {
386 		gdFree(compBuf);
387 	}
388 	if (chunkIdx) {
389 		gdFree(chunkIdx);
390 	}
391 
392 	GD2_DBG(php_gd_error("Done"));
393 
394 	return im;
395 
396 fail2:
397 	gdImageDestroy(im);
398 	if (chunkBuf) {
399 		gdFree(chunkBuf);
400 	}
401 	if (compBuf) {
402 		gdFree(compBuf);
403 	}
404 	if (chunkIdx) {
405 		gdFree(chunkIdx);
406 	}
407 
408 	return 0;
409 }
410 
gdImageCreateFromGd2PartPtr(int size,void * data,int srcx,int srcy,int w,int h)411 gdImagePtr gdImageCreateFromGd2PartPtr (int size, void *data, int srcx, int srcy, int w, int h)
412 {
413 	gdImagePtr im;
414 	gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
415 	im = gdImageCreateFromGd2PartCtx(in, srcx, srcy, w, h);
416 	in->gd_free(in);
417 
418 	return im;
419 }
420 
gdImageCreateFromGd2Part(FILE * inFile,int srcx,int srcy,int w,int h)421 gdImagePtr gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
422 {
423 	gdImagePtr im;
424 	gdIOCtx *in = gdNewFileCtx(inFile);
425 
426 	im = gdImageCreateFromGd2PartCtx(in, srcx, srcy, w, h);
427 
428 	in->gd_free(in);
429 
430 	return im;
431 }
432 
gdImageCreateFromGd2PartCtx(gdIOCtx * in,int srcx,int srcy,int w,int h)433 gdImagePtr gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
434 {
435 	int scx, scy, ecx, ecy, fsx, fsy;
436 	int nc, ncx, ncy, cs, cx, cy;
437 	int x, y, ylo, yhi, xlo, xhi;
438 	int dstart, dpos;
439 	int i;
440 	/* 2.0.12: unsigned is correct; fixes problems with color munging. Thanks to Steven Brown. */
441 	unsigned int ch;
442 	int vers, fmt;
443 	t_chunk_info *chunkIdx = NULL;
444 	unsigned char *chunkBuf = NULL;
445 	int chunkNum;
446 	int chunkMax = 0;
447 	uLongf chunkLen;
448 	int chunkPos = 0;
449 	int compMax;
450 	char *compBuf = NULL;
451 
452 	gdImagePtr im;
453 
454 	if (w<1 || h <1) {
455 		return 0;
456 	}
457 
458 	/* The next few lines are basically copied from gd2CreateFromFile
459 	 * we change the file size, so don't want to use the code directly.
460 	 * but we do need to know the file size.
461 	 */
462 	if (_gd2GetHeader(in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx) != 1) {
463 		goto fail1;
464 	}
465 
466 	GD2_DBG(php_gd_error("File size is %dx%d", fsx, fsy));
467 
468 	/* This is the difference - make a file based on size of chunks. */
469 	if (gd2_truecolor(fmt)) {
470 		im = gdImageCreateTrueColor(w, h);
471 	} else {
472 		im = gdImageCreate(w, h);
473 	}
474 	if (im == NULL) {
475 		goto fail1;
476 	}
477 
478 	if (!_gdGetColors(in, im, vers == 2)) {
479 		goto fail2;
480 	}
481 	GD2_DBG(php_gd_error("Image palette completed: %d colours", im->colorsTotal));
482 
483 	/* Process the header info */
484 	nc = ncx * ncy;
485 
486 	if (gd2_compressed(fmt)) {
487 		/* Find the maximum compressed chunk size. */
488 		compMax = 0;
489 		for (i = 0; (i < nc); i++) {
490 			if (chunkIdx[i].size > compMax) {
491 				compMax = chunkIdx[i].size;
492 			}
493 		}
494 		compMax++;
495 
496 		if (im->trueColor) {
497 			chunkMax = cs * cs * 4;
498 		} else {
499 			chunkMax = cs * cs;
500 		}
501 		if (chunkMax <= 0) {
502 			goto fail2;
503 		}
504 
505 		chunkBuf = gdCalloc(chunkMax, 1);
506 		compBuf = gdCalloc(compMax, 1);
507 	}
508 
509 	/* Work out start/end chunks */
510 	scx = srcx / cs;
511 	scy = srcy / cs;
512 	if (scx < 0) {
513 		scx = 0;
514 	}
515 	if (scy < 0) {
516 		scy = 0;
517 	}
518 
519 	ecx = (srcx + w) / cs;
520 	ecy = (srcy + h) / cs;
521 	if (ecx >= ncx) {
522 		ecx = ncx - 1;
523 	}
524 	if (ecy >= ncy) {
525 		ecy = ncy - 1;
526 	}
527 
528 	/* Remember file position of image data. */
529 	dstart = gdTell(in);
530 	GD2_DBG(php_gd_error("Data starts at %d", dstart));
531 
532 	/* Loop through the chunks. */
533 	for (cy = scy; (cy <= ecy); cy++) {
534 		ylo = cy * cs;
535 		yhi = ylo + cs;
536 		if (yhi > fsy) {
537 			yhi = fsy;
538 		}
539 
540 		for (cx = scx; cx <= ecx; cx++) {
541 
542 			xlo = cx * cs;
543 			xhi = xlo + cs;
544 			if (xhi > fsx) {
545 				xhi = fsx;
546 			}
547 
548 			GD2_DBG(php_gd_error("Processing Chunk (%d, %d), from %d to %d", cx, cy, ylo, yhi));
549 
550 			if (!gd2_compressed(fmt)) {
551 				GD2_DBG(php_gd_error("Using raw format data"));
552 				if (im->trueColor) {
553 					dpos = (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) + dstart;
554 				} else {
555 					dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart;
556 				}
557 
558 				/* gd 2.0.11: gdSeek returns TRUE on success, not 0. Longstanding bug. 01/16/03 */
559 				if (!gdSeek(in, dpos)) {
560 					php_gd_error_ex(E_WARNING, "Error from seek: %d", errno);
561 					goto fail2;
562 				}
563 				GD2_DBG(php_gd_error("Reading (%d, %d) from position %d", cx, cy, dpos - dstart));
564 			} else {
565 				chunkNum = cx + cy * ncx;
566 
567 				chunkLen = chunkMax;
568 				if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *)chunkBuf, &chunkLen, in)) {
569 					php_gd_error("Error reading comproessed chunk");
570 					goto fail2;
571 				}
572 				chunkPos = 0;
573 				GD2_DBG(php_gd_error("Reading (%d, %d) from chunk %d", cx, cy, chunkNum));
574 			}
575 
576 			GD2_DBG(php_gd_error("   into (%d, %d) - (%d, %d)", xlo, ylo, xhi, yhi));
577 
578 			for (y = ylo; (y < yhi); y++) {
579 				for (x = xlo; x < xhi; x++) {
580 					if (!gd2_compressed(fmt)) {
581 						if (im->trueColor) {
582 							if (!gdGetInt((int *)&ch, in)) {
583 								ch = 0;
584 							}
585 						} else {
586 							ch = gdGetC(in);
587 							if ((int)ch == EOF) {
588 								ch = 0;
589 							}
590 						}
591 					} else {
592 						if (im->trueColor) {
593 							ch = chunkBuf[chunkPos++];
594 							ch = (ch << 8) + chunkBuf[chunkPos++];
595 							ch = (ch << 8) + chunkBuf[chunkPos++];
596 							ch = (ch << 8) + chunkBuf[chunkPos++];
597 						} else {
598 							ch = chunkBuf[chunkPos++];
599 						}
600 					}
601 
602 					/* Only use a point that is in the image. */
603 					if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0) && (y >= srcy) && (y < (srcy + h)) && (y < fsy) && (y >= 0)) {
604 						if (im->trueColor) {
605 							im->tpixels[y - srcy][x - srcx] = ch;
606 						} else {
607 							im->pixels[y - srcy][x - srcx] = ch;
608 						}
609 					}
610 				}
611 			}
612 		}
613 	}
614 
615 	if (chunkBuf) {
616 		gdFree(chunkBuf);
617 	}
618 	if (compBuf) {
619 		gdFree(compBuf);
620 	}
621 	if (chunkIdx) {
622 		gdFree(chunkIdx);
623 	}
624 
625 	return im;
626 
627 fail2:
628 	gdImageDestroy(im);
629 fail1:
630 	if (chunkBuf) {
631 		gdFree(chunkBuf);
632 	}
633 	if (compBuf) {
634 		gdFree(compBuf);
635 	}
636 	if (chunkIdx) {
637 		gdFree(chunkIdx);
638 	}
639 
640 	return 0;
641 }
642 
_gd2PutHeader(gdImagePtr im,gdIOCtx * out,int cs,int fmt,int cx,int cy)643 static void _gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy)
644 {
645 	int i;
646 
647 	/* Send the gd2 id, to verify file format. */
648 	for (i = 0; i < 4; i++) {
649 		gdPutC((unsigned char) (GD2_ID[i]), out);
650 	}
651 
652 	/* We put the version info first, so future versions can easily change header info. */
653 
654 	gdPutWord(GD2_VERS, out);
655 	gdPutWord(im->sx, out);
656 	gdPutWord(im->sy, out);
657 	gdPutWord(cs, out);
658 	gdPutWord(fmt, out);
659 	gdPutWord(cx, out);
660 	gdPutWord(cy, out);
661 }
662 
_gdImageGd2(gdImagePtr im,gdIOCtx * out,int cs,int fmt)663 static void _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
664 {
665 	int ncx, ncy, cx, cy;
666 	int x, y, ylo, yhi, xlo, xhi;
667 	int chunkLen;
668 	int chunkNum = 0;
669 	char *chunkData = NULL;	/* So we can gdFree it with impunity. */
670 	char *compData = NULL;	/* So we can gdFree it with impunity. */
671 	uLongf compLen;
672 	int idxPos = 0;
673 	int idxSize;
674 	t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
675 	int posSave;
676 	int bytesPerPixel = im->trueColor ? 4 : 1;
677 	int compMax = 0;
678 
679 	/* Force fmt to a valid value since we don't return anything. */
680 	if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED)) {
681 		fmt = GD2_FMT_COMPRESSED;
682 	}
683 	if (im->trueColor) {
684 		fmt += 2;
685 	}
686 	/* Make sure chunk size is valid. These are arbitrary values; 64 because it seems
687 	 * a little silly to expect performance improvements on a 64x64 bit scale, and
688 	 * 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be
689 	 * OK for one user, but for another to read it, they require the buffer.
690 	 */
691 	if (cs == 0) {
692 		cs = GD2_CHUNKSIZE;
693 	} else if (cs < GD2_CHUNKSIZE_MIN) {
694 		cs = GD2_CHUNKSIZE_MIN;
695 	} else if (cs > GD2_CHUNKSIZE_MAX) {
696 		cs = GD2_CHUNKSIZE_MAX;
697 	}
698 
699 	/* Work out number of chunks. */
700 	ncx = (im->sx + cs - 1) / cs;
701 	ncy = (im->sy + cs - 1) / cs;
702 
703 	/* Write the standard header. */
704 	_gd2PutHeader (im, out, cs, fmt, ncx, ncy);
705 
706 	if (gd2_compressed(fmt)) {
707 		/* Work out size of buffer for compressed data, If CHUNKSIZE is large,
708 	 	 * then these will be large!
709 	 	 */
710 
711 		/* The zlib notes say output buffer size should be (input size) * 1.01 * 12
712 		 * - we'll use 1.02 to be paranoid.
713 		 */
714 		compMax = (int)(cs * bytesPerPixel * cs * 1.02f) + 12;
715 
716 		/* Allocate the buffers.  */
717 		chunkData = safe_emalloc(cs * bytesPerPixel, cs, 0);
718 		memset(chunkData, 0, cs * bytesPerPixel * cs);
719 		if (compMax <= 0) {
720 			goto fail;
721 		}
722 		compData = gdCalloc(compMax, 1);
723 
724 		/* Save the file position of chunk index, and allocate enough space for
725 		 * each chunk_info block .
726 		 */
727 		idxPos = gdTell(out);
728 		idxSize = ncx * ncy * sizeof(t_chunk_info);
729 		GD2_DBG(php_gd_error("Index size is %d", idxSize));
730 		gdSeek(out, idxPos + idxSize);
731 
732 		chunkIdx = safe_emalloc(idxSize, sizeof(t_chunk_info), 0);
733 		memset(chunkIdx, 0, idxSize * sizeof(t_chunk_info));
734 	}
735 
736 	_gdPutColors (im, out);
737 
738 	GD2_DBG(php_gd_error("Size: %dx%d", im->sx, im->sy));
739 	GD2_DBG(php_gd_error("Chunks: %dx%d", ncx, ncy));
740 
741 	for (cy = 0; (cy < ncy); cy++) {
742 		for (cx = 0; (cx < ncx); cx++) {
743 			ylo = cy * cs;
744 			yhi = ylo + cs;
745 			if (yhi > im->sy) {
746 				yhi = im->sy;
747 			}
748 
749 			GD2_DBG(php_gd_error("Processing Chunk (%dx%d), y from %d to %d", cx, cy, ylo, yhi));
750 			chunkLen = 0;
751 			for (y = ylo; (y < yhi); y++) {
752 				GD2_DBG(php_gd_error("y=%d: ",y));
753 				xlo = cx * cs;
754 				xhi = xlo + cs;
755 				if (xhi > im->sx) {
756 					xhi = im->sx;
757 				}
758 
759 				if (gd2_compressed(fmt)) {
760 					for (x = xlo; x < xhi; x++) {
761 						GD2_DBG(php_gd_error("%d...",x));
762 						if (im->trueColor) {
763 							int p = im->tpixels[y][x];
764 							chunkData[chunkLen++] = gdTrueColorGetAlpha(p);
765 							chunkData[chunkLen++] = gdTrueColorGetRed(p);
766 							chunkData[chunkLen++] = gdTrueColorGetGreen(p);
767 							chunkData[chunkLen++] = gdTrueColorGetBlue(p);
768 						} else {
769 							chunkData[chunkLen++] = im->pixels[y][x];
770 						}
771 					}
772 				} else {
773 					for (x = xlo; x < xhi; x++) {
774 						GD2_DBG(php_gd_error("%d, ",x));
775 
776 						if (im->trueColor) {
777 							gdPutInt(im->tpixels[y][x], out);
778 						} else {
779 							gdPutC((unsigned char) im->pixels[y][x], out);
780 						}
781 					}
782 				}
783 				GD2_DBG(php_gd_error("y=%d done.",y));
784 			}
785 
786 			if (gd2_compressed(fmt)) {
787 				compLen = compMax;
788 				if (compress((unsigned char *) &compData[0], &compLen, (unsigned char *) &chunkData[0], chunkLen) != Z_OK) {
789 					php_gd_error("Error from compressing");
790 				} else {
791 					chunkIdx[chunkNum].offset = gdTell(out);
792 					chunkIdx[chunkNum++].size = compLen;
793 					GD2_DBG(php_gd_error("Chunk %d size %d offset %d", chunkNum, chunkIdx[chunkNum - 1].size, chunkIdx[chunkNum - 1].offset));
794 
795 					if (gdPutBuf (compData, compLen, out) <= 0) {
796 						/* Any alternate suggestions for handling this? */
797 						php_gd_error_ex(E_WARNING, "Error %d on write", errno);
798 					}
799 				}
800 			}
801 		}
802     	}
803 
804 	if (gd2_compressed(fmt)) {
805 		/* Save the position, write the index, restore position (paranoia). */
806 		GD2_DBG(php_gd_error("Seeking %d to write index", idxPos));
807 		posSave = gdTell(out);
808 		gdSeek(out, idxPos);
809 		GD2_DBG(php_gd_error("Writing index"));
810 		for (x = 0; x < chunkNum; x++) {
811 			GD2_DBG(php_gd_error("Chunk %d size %d offset %d", x, chunkIdx[x].size, chunkIdx[x].offset));
812 			gdPutInt(chunkIdx[x].offset, out);
813 			gdPutInt(chunkIdx[x].size, out);
814 		}
815 		gdSeek(out, posSave);
816 	}
817 fail:
818 	GD2_DBG(php_gd_error("Freeing memory"));
819 	if (chunkData) {
820 		gdFree(chunkData);
821 	}
822 	if (compData) {
823 		gdFree(compData);
824 	}
825 	if (chunkIdx) {
826 		gdFree(chunkIdx);
827 	}
828 	GD2_DBG(php_gd_error("Done"));
829 }
830 
gdImageGd2(gdImagePtr im,FILE * outFile,int cs,int fmt)831 void gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
832 {
833 	gdIOCtx *out = gdNewFileCtx(outFile);
834 
835 	_gdImageGd2(im, out, cs, fmt);
836 
837 	out->gd_free(out);
838 }
839 
gdImageGd2Ptr(gdImagePtr im,int cs,int fmt,int * size)840 void *gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
841 {
842 	void *rv;
843 	gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
844 
845 	_gdImageGd2(im, out, cs, fmt);
846 	rv = gdDPExtractData(out, size);
847 	out->gd_free(out);
848 
849 	return rv;
850 }
851