Skip to content

[Bug] Check mremap return value to prevent potential crash in MMapIO #1724

@LHT129

Description

@LHT129

Description

Add return value check for mremap calls in MMapIO on Linux platform to prevent potential segmentation faults when memory remapping fails.

Background

In src/io/mmap_io.cpp, the Linux code path (non-Apple) has three mremap calls that do not check the return value:

  1. WriteImpl - when extending memory mapping
  2. ResizeImpl - when expanding memory mapping
  3. ResizeImpl - when shrinking memory mapping

When mremap fails, it returns MAP_FAILED (i.e., (void*)-1). Directly assigning this to this->start_ causes:

  • Subsequent memcpy(this->start_ + offset, data, size) writes to address -1 + offset, causing segfault
  • All subsequent read/write operations on invalid memory addresses

The macOS branch (#ifdef __APPLE__) correctly checks for MAP_FAILED and throws an exception, but the Linux branch does not.

Requirements

  • Add return value check for all three mremap calls
  • Throw VsagException with meaningful error message on failure
  • Align Linux error handling with macOS implementation

Technical Details

The fix follows the same pattern as the macOS branch:

void* new_addr = mremap(this->start_, old_size, new_size, MREMAP_MAYMOVE);
if (new_addr == MAP_FAILED) {
    throw VsagException(ErrorType::INTERNAL_ERROR,
                        fmt::format("mremap failed: {}", strerror(errno)));
}
this->start_ = static_cast<uint8_t*>(new_addr);

Acceptance Criteria

  • All three mremap calls have return value checks
  • Error handling matches macOS branch behavior
  • Code compiles successfully
  • Unit tests pass

Related

  • Files modified: src/io/mmap_io.cpp
  • Reference: mremap(2) man page - returns MAP_FAILED on failure

Notes

This is a defensive fix that prevents crashes in low-memory situations or when system limits are hit. The error message includes strerror(errno) for debugging.

Metadata

Metadata

Assignees

Labels

kind/bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions