Skip to content

MUNMAP leaks the memory if file descriptor is closed #21360

Closed
@nightelf3

Description

@nightelf3

I noticed a memory leak using Skia's SkStream::MakeFromFile with EMSDK caused by the inability to release the allocated memory when a file descriptor is not valid (even for MAP_PRIVATE mode).

Here are Skia sources as an example.

[SkStream::MakeFromFile]

static sk_sp<SkData> mmap_filename(const char path[]) {
    FILE* file = sk_fopen(path, kRead_SkFILE_Flag);
    if (nullptr == file) {
        return nullptr;
    }

    auto data = SkData::MakeFromFILE(file);  // <--- this calls sk_fmmap and remembers the memory
    sk_fclose(file);  // <--- this releases the file handle, mmaped buffer in `data` won't be released
    return data;
}

[sk_fdmmap]

void* addr = mmap(nullptr, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);

munmap() documentation specifies the following:

The munmap() function shall remove any mappings for those entire pages containing any part of the address space of the process starting at addr and continuing for len bytes.

So we should be safe to release the addr pointer when stream is closed in munmap_js, something like:

var stream = FS.getStream(fd);
if (!stream) {
  _free(addr);
 } else {
   ...
 }

What do you think about it?
Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions