Skip to content

Commit

Permalink
BMPUtils: get rid of extra allocation on loading file, discard BMPs t…
Browse files Browse the repository at this point in the history
…hat's smaller than data size values
  • Loading branch information
a1batross committed Dec 1, 2022
1 parent 2716551 commit fbfe112
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
23 changes: 19 additions & 4 deletions BMPUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class CBMP
{
public:
static CBMP* LoadFile( const char *filename ); // implemented in library!

CBMP( uint w, uint h )
{
bmp_t bhdr;
Expand All @@ -81,12 +81,22 @@ class CBMP
bhdr.colors = ( pixel_size == 1 ) ? 256 : 0;
bhdr.importantColors = 0;

fileAllocated = false;
data = new byte[bhdr.fileSize];
memcpy( data, &bhdr, sizeof( bhdr ));
memset( data + bhdr.bitmapDataOffset, 0, bhdr.bitmapDataSize );
}

~CBMP() { if( data ) delete []data; }
~CBMP()
{
if( data )
{
if( fileAllocated )
EngFuncs::COM_FreeFile( data );
else
delete []data;
}
}

void Increase(uint w, uint h)
{
Expand Down Expand Up @@ -172,7 +182,12 @@ class CBMP
return (rgbquad_t*)(data + sizeof( bmp_t ));
}


private:
byte *data;
CBMP( bmp_t *data ) :
fileAllocated( true ), data( (byte*)data )
{
}

bool fileAllocated;
byte *data;
};
13 changes: 10 additions & 3 deletions Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -413,10 +413,17 @@ CBMP* CBMP::LoadFile( const char *filename )
if( !bmp->width || !bmp->height )
return NULL;

CBMP *ret = new CBMP( bmp->width, bmp->height );
memcpy( ret->GetBitmap(), bmp, length );
// validate all nasty data size fields
if( length < bmp->fileSize ||
length < bmp->bitmapDataSize ||
length < bmp->bitmapDataOffset ||
length < bmp->bitmapHeaderSize ||
length < bmp->bitmapDataOffset + bmp->bitmapDataSize ||
length < bmp->bitmapHeaderSize + bmp->bitmapDataSize )
return NULL;

EngFuncs::COM_FreeFile( bmp );
// will be freed in destructor
CBMP *ret = new CBMP( bmp );

return ret;
}
Expand Down

0 comments on commit fbfe112

Please sign in to comment.