Skip to content

Commit

Permalink
Correctly release the underlying file mapping.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Dec 24, 2023
1 parent 37753f1 commit c5163e6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 20 deletions.
3 changes: 3 additions & 0 deletions include/ruby/io/buffer.h
Expand Up @@ -58,6 +58,9 @@ enum rb_io_buffer_flags {

// The buffer is read-only and cannot be modified.
RB_IO_BUFFER_READONLY = 128,

// The buffer is backed by a file.
RB_IO_BUFFER_FILE = 256,
};

// Represents the endian of the data types.
Expand Down
40 changes: 22 additions & 18 deletions io_buffer.c
Expand Up @@ -155,17 +155,7 @@ io_buffer_map_file(struct rb_io_buffer *buffer, int descriptor, size_t size, rb_
buffer->size = size;

buffer->flags |= RB_IO_BUFFER_MAPPED;
}

// Release the memory associated with a mapped buffer.
static inline void
io_buffer_unmap(void* base, size_t size)
{
#ifdef _WIN32
VirtualFree(base, 0, MEM_RELEASE);
#else
munmap(base, size);
#endif
buffer->flags |= RB_IO_BUFFER_FILE;
}

static void
Expand Down Expand Up @@ -234,7 +224,16 @@ io_buffer_free(struct rb_io_buffer *buffer)
}

if (buffer->flags & RB_IO_BUFFER_MAPPED) {
io_buffer_unmap(buffer->base, buffer->size);
#ifdef _WIN32
if (buffer->flags & RB_IO_BUFFER_FILE) {
UnmapViewOfFile(buffer->base);
}
else {
VirtualFree(buffer->base, 0, MEM_RELEASE);
}
#else
munmap(buffet->base, buffer->size);
#endif
}

// Previously we had this, but we found out due to the way GC works, we
Expand All @@ -245,19 +244,20 @@ io_buffer_free(struct rb_io_buffer *buffer)

buffer->base = NULL;

#if defined(_WIN32)
if (buffer->mapping) {
CloseHandle(buffer->mapping);
buffer->mapping = NULL;
}
#endif
buffer->size = 0;
buffer->flags = 0;
buffer->source = Qnil;

return 1;
}

#if defined(_WIN32)
if (buffer->mapping) {
CloseHandle(buffer->mapping);
buffer->mapping = NULL;
}
#endif

return 0;
}

Expand Down Expand Up @@ -926,6 +926,10 @@ rb_io_buffer_to_s(VALUE self)
rb_str_cat2(result, " MAPPED");
}

if (buffer->flags & RB_IO_BUFFER_FILE) {
rb_str_cat2(result, " FILE");
}

if (buffer->flags & RB_IO_BUFFER_SHARED) {
rb_str_cat2(result, " SHARED");
}
Expand Down
2 changes: 0 additions & 2 deletions test/ruby/test_io_buffer.rb
Expand Up @@ -519,8 +519,6 @@ def test_shared
end

def test_private
omit if RUBY_PLATFORM =~ /mswin|mingw/

Tempfile.create("buffer.txt") do |io|
io.write("Hello World")

Expand Down

0 comments on commit c5163e6

Please sign in to comment.