serenity icon indicating copy to clipboard operation
serenity copied to clipboard

Kernel/Memory: Shared anonymous mmaps not working correctly

Open brody-qq opened this issue 1 year ago • 0 comments

If an mmap is created with flags MAP_SHARED | MAP_ANONYMOUS, that mmap will be inherited by child processes, and any writes to the mmap in the child process should be visible in the parent process (and vice-versa).

This is currently not working, writes to shared anonymous mmaps are not visible in other processes sharing the mmap.

How to reproduce: apply the following diff, then run test-shared-anon-mmap in the shell

This program is a minimal testcase that:

  • creates a MAP_SHARED | MAP_ANONYMOUS mmap
  • forks
  • the child process makes a write to the mmap, then exits
  • the parent process waits for the child to exit, then checks if the write the child made is visible in the parent process
diff --git a/Userland/Utilities/test-shared-anon-mmap.cpp b/Userland/Utilities/test-shared-anon-mmap.cpp
new file mode 100644
index 0000000000..48dfd0659e
--- /dev/null
+++ b/Userland/Utilities/test-shared-anon-mmap.cpp
@@ -0,0 +1,42 @@
+#include <AK/Assertions.h>
+#include <LibMain/Main.h>
+#include <LibThreading/Thread.h>
+#include <errno.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+
+ErrorOr<int> serenity_main(Main::Arguments)
+{
+    size_t pages = 100;
+    size_t size = pages * 4096;
+
+    char *ptr = (char *)mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+    if (ptr == MAP_FAILED) {
+        perror(nullptr);
+        return 1;
+    }
+
+    pid_t pid = fork();
+    switch (pid) {
+    case -1:
+        perror(nullptr);
+        exit(1);
+        break;
+    case 0:
+        ptr[0] = '$';
+        exit(EXIT_SUCCESS);
+        break;
+    default:
+        wait(nullptr);
+        if (ptr[0] == '$')
+            printf("SUCCESS\n");
+        else
+            printf("ERROR\n");
+        break;
+    }
+
+    return 0;
+}

brody-qq avatar Jul 01 '24 01:07 brody-qq