Skip to content

Commit 2cd30c2

Browse files
committed
tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)
1 parent 09e8340 commit 2cd30c2

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

Diff for: src/bin/jp2/convert.c

+27-12
Original file line numberDiff line numberDiff line change
@@ -580,13 +580,10 @@ struct tga_header {
580580
};
581581
#endif /* INFORMATION_ONLY */
582582

583-
static unsigned short get_ushort(const unsigned char *data)
583+
/* Returns a ushort from a little-endian serialized value */
584+
static unsigned short get_tga_ushort(const unsigned char *data)
584585
{
585-
unsigned short val = *(const unsigned short *)data;
586-
#ifdef OPJ_BIG_ENDIAN
587-
val = ((val & 0xffU) << 8) | (val >> 8);
588-
#endif
589-
return val;
586+
return data[0] | (data[1] << 8);
590587
}
591588

592589
#define TGA_HEADER_SIZE 18
@@ -613,17 +610,17 @@ static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
613610
id_len = tga[0];
614611
/*cmap_type = tga[1];*/
615612
image_type = tga[2];
616-
/*cmap_index = get_ushort(&tga[3]);*/
617-
cmap_len = get_ushort(&tga[5]);
613+
/*cmap_index = get_tga_ushort(&tga[3]);*/
614+
cmap_len = get_tga_ushort(&tga[5]);
618615
cmap_entry_size = tga[7];
619616

620617

621618
#if 0
622-
x_origin = get_ushort(&tga[8]);
623-
y_origin = get_ushort(&tga[10]);
619+
x_origin = get_tga_ushort(&tga[8]);
620+
y_origin = get_tga_ushort(&tga[10]);
624621
#endif
625-
image_w = get_ushort(&tga[12]);
626-
image_h = get_ushort(&tga[14]);
622+
image_w = get_tga_ushort(&tga[12]);
623+
image_h = get_tga_ushort(&tga[14]);
627624
pixel_depth = tga[16];
628625
image_desc = tga[17];
629626

@@ -817,6 +814,24 @@ opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
817814
color_space = OPJ_CLRSPC_SRGB;
818815
}
819816

817+
/* If the declared file size is > 10 MB, check that the file is big */
818+
/* enough to avoid excessive memory allocations */
819+
if (image_height != 0 && image_width > 10000000 / image_height / numcomps) {
820+
char ch;
821+
OPJ_UINT64 expected_file_size =
822+
(OPJ_UINT64)image_width * image_height * numcomps;
823+
long curpos = ftell(f);
824+
if (expected_file_size > (OPJ_UINT64)INT_MAX) {
825+
expected_file_size = (OPJ_UINT64)INT_MAX;
826+
}
827+
fseek(f, (long)expected_file_size - 1, SEEK_SET);
828+
if (fread(&ch, 1, 1, f) != 1) {
829+
fclose(f);
830+
return NULL;
831+
}
832+
fseek(f, curpos, SEEK_SET);
833+
}
834+
820835
subsampling_dx = parameters->subsampling_dx;
821836
subsampling_dy = parameters->subsampling_dy;
822837

0 commit comments

Comments
 (0)