Skip to content

Fix data loss when Realloc moves a block into the free block below - #30

Open
dallison wants to merge 2 commits into
mainfrom
fix-realloc-merge-below
Open

dallison wants to merge 2 commits into
mainfrom
fix-realloc-merge-below

Conversation

@dallison

Copy link
Copy Markdown
Owner

Summary

  • Fix PayloadBuffer::Realloc when growing into the free block below: defer writing the free-block header until after the block move so payload bytes are not overwritten before memmove.
  • Omit the trailing free header when no room remains, and remove the zero-length free block from the list instead of corrupting the next block header.
  • Add a regression test covering the merge-below realloc path.

Test plan

  • Run toolbelt/payload_buffer_test (or full Bazel/CMake test suite as used in CI)
  • Confirm vector growth no longer drops elements when realloc merges with the block below

When Realloc grows a block into the free block below it, the block
moves down and what is left of the two follows it.  The header of that
free block was written before the move, and starts inside the block's
old place when the new size is at least that of the free block below,
so it overwrote 8 bytes of the block before they were copied.  When
nothing was left, the header was written over the size of the next
block, and a free block of length 0 was put on the free list.  The
header is now written after the move, and only when there is room for
one; otherwise the free block is taken off the list.

Growing a vector could lose two 4-byte elements this way.
SetString() read freed memory when its source was a string in the same
buffer and making room for the copy moved the buffer.  Assigning a
string a part of itself could also lose its end, as shrinking the old
string in place writes a free block header over it.

SetString() now finds a source in the buffer again by its offset after
allocating, and copies out a source inside the string it replaces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant