Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 //
0003 // Copyright 2019, Michael Ellerman, IBM Corp.
0004 //
0005 // Test that allocating memory beyond the memory limit and then forking is
0006 // handled correctly, ie. the child is able to access the mappings beyond the
0007 // memory limit and the child's writes are not visible to the parent.
0008 
0009 #include <stdio.h>
0010 #include <stdlib.h>
0011 #include <sys/mman.h>
0012 #include <sys/types.h>
0013 #include <sys/wait.h>
0014 #include <unistd.h>
0015 
0016 #include "utils.h"
0017 
0018 
0019 #ifndef MAP_FIXED_NOREPLACE
0020 #define MAP_FIXED_NOREPLACE MAP_FIXED   // "Should be safe" above 512TB
0021 #endif
0022 
0023 
0024 static int test(void)
0025 {
0026     int p2c[2], c2p[2], rc, status, c, *p;
0027     unsigned long page_size;
0028     pid_t pid;
0029 
0030     page_size = sysconf(_SC_PAGESIZE);
0031     SKIP_IF(page_size != 65536);
0032 
0033     // Create a mapping at 512TB to allocate an extended_id
0034     p = mmap((void *)(512ul << 40), page_size, PROT_READ | PROT_WRITE,
0035         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
0036     if (p == MAP_FAILED) {
0037         perror("mmap");
0038         printf("Error: couldn't mmap(), confirm kernel has 4TB support?\n");
0039         return 1;
0040     }
0041 
0042     printf("parent writing %p = 1\n", p);
0043     *p = 1;
0044 
0045     FAIL_IF(pipe(p2c) == -1 || pipe(c2p) == -1);
0046 
0047     pid = fork();
0048     if (pid == 0) {
0049         FAIL_IF(read(p2c[0], &c, 1) != 1);
0050 
0051         pid = getpid();
0052         printf("child writing  %p = %d\n", p, pid);
0053         *p = pid;
0054 
0055         FAIL_IF(write(c2p[1], &c, 1) != 1);
0056         FAIL_IF(read(p2c[0], &c, 1) != 1);
0057         exit(0);
0058     }
0059 
0060     c = 0;
0061     FAIL_IF(write(p2c[1], &c, 1) != 1);
0062     FAIL_IF(read(c2p[0], &c, 1) != 1);
0063 
0064     // Prevent compiler optimisation
0065     barrier();
0066 
0067     rc = 0;
0068     printf("parent reading %p = %d\n", p, *p);
0069     if (*p != 1) {
0070         printf("Error: BUG! parent saw child's write! *p = %d\n", *p);
0071         rc = 1;
0072     }
0073 
0074     FAIL_IF(write(p2c[1], &c, 1) != 1);
0075     FAIL_IF(waitpid(pid, &status, 0) == -1);
0076     FAIL_IF(!WIFEXITED(status) || WEXITSTATUS(status));
0077 
0078     if (rc == 0)
0079         printf("success: test completed OK\n");
0080 
0081     return rc;
0082 }
0083 
0084 int main(void)
0085 {
0086     return test_harness(test, "large_vm_fork_separation");
0087 }