Error out creating too large bitmaps / tilemaps instead of corrupting memory

This commit is contained in:
Ilari Liusvaara 2014-03-31 14:15:24 +03:00
parent 7ba7fc24f6
commit 5d0fb0f39a
3 changed files with 8 additions and 5 deletions

View file

@ -41,7 +41,7 @@ struct lua_bitmap
{
lua_bitmap(lua::state& L, uint32_t w, uint32_t h);
static size_t overcommit(uint32_t w, uint32_t h) {
return lua::overcommit_std_align + sizeof(uint16_t) * w * h;
return lua::overcommit_std_align + sizeof(uint16_t) * (size_t)w * h;
}
~lua_bitmap();
size_t width;
@ -65,7 +65,7 @@ struct lua_dbitmap
{
lua_dbitmap(lua::state& L, uint32_t w, uint32_t h);
static size_t overcommit(uint32_t w, uint32_t h) {
return lua::overcommit_std_align + sizeof(framebuffer::color) * w * h;
return lua::overcommit_std_align + sizeof(framebuffer::color) * (size_t)w * h;
}
~lua_dbitmap();
size_t width;

View file

@ -887,6 +887,7 @@ void lua_palette::push_back(const framebuffer::color& cx)
/** BITMAP **/
lua_bitmap::lua_bitmap(lua::state& L, uint32_t w, uint32_t h)
{
if(overcommit(w, h) / h / sizeof(uint16_t) < w) throw std::bad_alloc();
width = w;
height = h;
pixels = lua::align_overcommit<lua_bitmap, uint16_t>(this);
@ -1051,12 +1052,13 @@ int lua_bitmap::save_png(lua::state& L, lua::parameters& P)
/** DBITMAP **/
lua_dbitmap::lua_dbitmap(lua::state& L, uint32_t w, uint32_t h)
{
if(overcommit(w, h) / h / sizeof(framebuffer::color) < w) throw std::bad_alloc();
width = w;
height = h;
pixels = lua::align_overcommit<lua_dbitmap, framebuffer::color>(this);
//Initialize the bitmap data.
framebuffer::color transparent(-1);
for(size_t i = 0; i < width * height; i++)
for(size_t i = 0; i < (size_t)width * height; i++)
new(pixels + i) framebuffer::color(transparent);
}

View file

@ -32,7 +32,7 @@ namespace
{
tilemap(lua::state& L, size_t _width, size_t _height, size_t _cwidth, size_t _cheight);
static size_t overcommit(size_t _width, size_t _height, size_t _cwidth, size_t _cheight) {
return lua::overcommit_std_align + 2 * sizeof(tilemap_entry) * _width * _height;
return lua::overcommit_std_align + 2 * sizeof(tilemap_entry) * (size_t)_width * _height;
}
~tilemap()
{
@ -317,8 +317,9 @@ namespace
tilemap::tilemap(lua::state& L, size_t _width, size_t _height, size_t _cwidth, size_t _cheight)
: width(_width), height(_height), cwidth(_cwidth), cheight(_cheight)
{
if(width * height / height != width)
if(overcommit(width, height, cwidth, cheight) / height / sizeof(tilemap_entry) < width)
throw std::bad_alloc();
map = lua::align_overcommit<tilemap, tilemap_entry>(this);
tmpmap = &map[width * height];
//Initialize the map!