Skip to content

Commit 67cccf0

Browse files
committed
Don't fail when yr_notebook_alloc is called with a large size.
Until now yr_notebook_alloc was assuming that the size of allocated buffer was always less than page size. In the best case, it produced an assertion, but when assertions are turned off with `NDEBUG` this leads to memory corruption. With this change yr_notebook_alloc always fulfil the allocation, creating a larger than normal page if necessary.
1 parent 67e072a commit 67cccf0

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

libyara/notebook.c

+10-5
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ typedef struct YR_NOTEBOOK_PAGE YR_NOTEBOOK_PAGE;
4848
// all the buffers allocated via yr_notebook_alloc().
4949
struct YR_NOTEBOOK
5050
{
51-
// Size of each page in the notebook.
51+
// Size of pages in the notebook. Most pages are this size, but some
52+
// of them can be 2x, 3x, or in general Nx this size. This happens when
53+
// yr_notebook_alloc is called with a size that is larger than page_size,
54+
// which means that the notebook needs to allocate a page that is larger
55+
// than the rest for accomodating the requested buffer.
5256
size_t page_size;
5357
// Pointer to the first page in the book, this is also the most recently
5458
// created page, the one that is being filled.
@@ -147,15 +151,16 @@ void* yr_notebook_alloc(YR_NOTEBOOK* notebook, size_t size)
147151
// deferrencing pointers to types larger than a byte.
148152
size = (size + 7) & ~0x7;
149153

150-
// The requested memory size can't be larger than a notebook's page.
151-
assert(size <= notebook->page_size);
152-
153154
// If the requested size doesn't fit in current page's free space, allocate
154155
// a new page.
155156
if (notebook->page_size - notebook->page_list_head->used < size)
156157
{
158+
// The new page must be able to fit the requested buffer, so find the
159+
// multiple of notebook->page_size that is larger than size.
160+
size_t page_size = (size / notebook->page_size + 1) * notebook->page_size;
161+
157162
YR_NOTEBOOK_PAGE* new_page = yr_malloc(
158-
sizeof(YR_NOTEBOOK_PAGE) + notebook->page_size);
163+
sizeof(YR_NOTEBOOK_PAGE) + page_size);
159164

160165
if (new_page == NULL)
161166
return NULL;

0 commit comments

Comments
 (0)