File gd-CVE-2016-6906.patch of Package gd.4119

Index: libgd-2.1.0/src/gd_tga.c
===================================================================
--- libgd-2.1.0.orig/src/gd_tga.c	2017-02-01 12:55:02.709903265 +0100
+++ libgd-2.1.0/src/gd_tga.c	2017-02-01 13:12:35.484447642 +0100
@@ -197,6 +197,7 @@ int read_image_tga( gdIOCtx *ctx, oTga *
 	int bitmap_caret = 0;
 	int i = 0;
 	uint8_t encoded_pixels;
+        int rle_size;
 
 	if(overflow2(tga->width, tga->height)) {
 		return -1;
@@ -271,7 +272,7 @@ int read_image_tga( gdIOCtx *ctx, oTga *
 			return -1;
 		}
 
-		if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
+		if ((rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx)) != image_block_size) {
 			gdFree(conversion_buffer);
 			gdFree(decompression_buffer);
 			return -1;
@@ -287,12 +288,19 @@ int read_image_tga( gdIOCtx *ctx, oTga *
 		buffer_caret = 0;
 
 		while( bitmap_caret < image_block_size ) {
+
+			if (buffer_caret + pixel_block_size > rle_size) {
+				gdFree( decompression_buffer );
+				gdFree( conversion_buffer );
+				return -1;
+			}
 			
 			if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
 				encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & !TGA_RLE_FLAG ) + 1 );
 				buffer_caret++;
 
-				if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
+				if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size
+					|| buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) {
 					gdFree( decompression_buffer );
 					gdFree( conversion_buffer );
 					return -1;
@@ -308,7 +316,8 @@ int read_image_tga( gdIOCtx *ctx, oTga *
 				encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
 				buffer_caret++;
 
-				if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
+				if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size
+					|| buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) {
 					gdFree( decompression_buffer );
 					gdFree( conversion_buffer );
 					return -1;