WSL: mmap's problem

WSL’s mmap behavior different from native Linux. Native Linux work, but WSL(14388) segmentation fault. Here is sample code:

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    char *path = "./test.db";

    unlink(path);

    int fd = open(path, O_RDWR|O_CREAT, 0644);
    void *m_ptr = mmap(NULL, 16 * 1024, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    lseek(fd, 8 * 1024 - 1, SEEK_SET);
    write(fd, "\0", 1);;

    memset(m_ptr, 0, 8 * 1024);

    printf("ok!!\n");

    return 0;
}

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 9
  • Comments: 17 (2 by maintainers)

Most upvoted comments

This has been fixed but is not in Creator’s update. Look for this to be fixed in the first post-Creator’s Update Insider build.

Remember that it’s a 2 part bug (possibly connected though)

1: the failure to map a nil sized file 2: the failure to do the mapping of a requested size where the pages becomes valid as the file becomes larger. Try creating a 4096 byte file, the accesses to the first page will succeed but because of the silent truncation the writes beyond 4096 bytes will fail, restarting the program after writing another 4kb will create a 8kb mapping but again the memory accesses will fail after the initial 8kb despite the file being 12kb at the time of access.

For correct behaviour the mapping should be of the requested size (16kb) directly and the memory pages should become available as the file is enlarged.

@yorickdowne The WSL maintainers may be particularly good and see updates on closed issues, but experience in various repos taught me that opening a new issue and referencing the closed one is more likely to get attention.

FWIW, Cygwin has the same behavior as WSL here, so there’s that defense.