Skip to content

Commit

Permalink
Fix image decode (#3148)
Browse files Browse the repository at this point in the history
* call jpeg_destroy_decompress explicitly on setjmp
* use right bmp length to guard against pointer overflow

Signed-off-by: cyy <cyyever@outlook.com>
  • Loading branch information
cyyever committed Jul 16, 2021
1 parent a0058f3 commit 5f7bfda
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
5 changes: 3 additions & 2 deletions dali/image/bmp.cc
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,15 @@ BmpImage::BmpImage(const uint8_t *encoded_buffer, size_t length, DALIImageType i

Image::Shape BmpImage::PeekShapeImpl(const uint8_t *bmp, size_t length) const {
DALI_ENFORCE(bmp != nullptr);
DALI_ENFORCE(length >= 18);
auto ptr = bmp + 14;
uint32_t header_size = ConsumeValue<uint32_t>(ptr);
int64_t h = 0, w = 0, c = 0;
int bpp = 0, compression_type = BMP_COMPRESSION_RGB;
const uint8_t* palette_start = nullptr;
size_t ncolors = 0;
size_t palette_entry_size = 0;
if (length >= 22 && header_size == 12) {
if (length >= 26 && header_size == 12) {
// BITMAPCOREHEADER:
// | 32u header | 16u width | 16u height | 16u number of color planes | 16u bits per pixel
w = ConsumeValue<uint16_t>(ptr);
Expand All @@ -97,7 +98,7 @@ Image::Shape BmpImage::PeekShapeImpl(const uint8_t *bmp, size_t length) const {
palette_entry_size = 3;
ncolors = (1_uz << bpp);
}
} else if (length >= 26 && header_size >= 40) {
} else if (length >= 50 && header_size >= 40) {
// BITMAPINFOHEADER and later:
// | 32u header | 32s width | 32s height | 16u number of color planes | 16u bits per pixel
// | 32u compression type
Expand Down
16 changes: 10 additions & 6 deletions dali/image/jpeg_mem.cc
Original file line number Diff line number Diff line change
Expand Up @@ -578,27 +578,31 @@ bool GetImageInfo(const void* srcdata, int datasize, int* width, int* height,

// Initialize libjpeg structures to have a memory source
// Modify the usual jpeg error manager to catch fatal errors.
struct jpeg_decompress_struct cinfo;
struct jpeg_decompress_struct cinfo{};
struct jpeg_error_mgr jerr;
jmp_buf jpeg_jmpbuf;
cinfo.err = jpeg_std_error(&jerr);
cinfo.client_data = &jpeg_jmpbuf;
jerr.error_exit = CatchError;
if (setjmp(jpeg_jmpbuf)) {
return false;
}

// set up, read header, set image parameters, save size
jpeg_create_decompress(&cinfo);

if (setjmp(jpeg_jmpbuf)) {
jpeg_destroy_decompress(&cinfo);
return false;
}
SetSrc(&cinfo, srcdata, datasize, false);

DALI_ENFORCE(jpeg_read_header(&cinfo, TRUE) == JPEG_HEADER_OK);
if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
jpeg_destroy_decompress(&cinfo);
return false;
}
if (width) *width = cinfo.image_width;
if (height) *height = cinfo.image_height;
if (components) *components = cinfo.num_components;

jpeg_destroy_decompress(&cinfo);

return true;
}

Expand Down

0 comments on commit 5f7bfda

Please sign in to comment.