Skip to content

MUNMAP leaks the memory if file descriptor is closed #21360

Closed

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!

Activity

  1. added 2 commits that reference this issue on Feb 16, 2024
    1b8ca02
    ac5048b
  2. sbc100 commented on Feb 16, 2024

    @sbc100
    Collaborator

    Fix is in #21363

  3. nightelf3 commented on Feb 16, 2024

    @nightelf3
    Author

    Wow, thank you a lot!

  4. added a commit that references this issue on Feb 16, 2024
    71c3d00
  5. added a commit that references this issue on Feb 23, 2024
    4b3dd95
  6. added a commit that references this issue on Apr 12, 2024
    baa07c9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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