Skip to content

Commit

Permalink
Merge pull request #449 from s-hadinger/filelib_improve_protection
Browse files Browse the repository at this point in the history
Improve protection of filelib when reading files too large
  • Loading branch information
skiars authored Nov 15, 2024
2 parents b4b87d8 + 5783eb2 commit 828cf43
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/be_filelib.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "be_sys.h"
#include "be_gc.h"
#include "be_bytecode.h"
#include "be_vm.h"
#include <string.h>

#define READLINE_STEP 100
Expand Down Expand Up @@ -71,12 +72,23 @@ static int i_readbytes(bvm *vm)
void *fh = be_tocomptr(vm, -1);
size_t size = readsize(vm, argc, fh);
if (size) {
if (size > vm->bytesmaxsize) {
be_raise(vm, "memory_error", "size exceeds maximum allowed for bytes");
}
/* avoid double allocation, using directly the internal buffer of bytes() */
be_getbuiltin(vm, "bytes");
be_pushint(vm, size);
be_call(vm, 1); /* call bytes() constructor with pre-sized buffer */
be_pop(vm, 1); /* bytes() instance is at top */

/* read back the actual buffer size */
be_getmember(vm, -1, ".size");
int32_t bytes_size = be_toint(vm, -1);
be_pop(vm, 1);
if (bytes_size < (int32_t)size) {
be_raise(vm, "memory_error", "could not allocated buffer");
}

be_getmember(vm, -1, "resize");
be_pushvalue(vm, -2);
be_pushint(vm, size);
Expand Down

0 comments on commit 828cf43

Please sign in to comment.