1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Zilogic Systems Pvt. Ltd., 2020
4 * Email: code@zilogic.com
5 */
6
7 /*
8 * Test mmap with MAP_FIXED_NOREPLACE flag
9 *
10 * We are testing the MAP_FIXED_NOREPLACE flag of mmap() syscall. To check
11 * if an attempt to mmap at an exisiting mapping fails with EEXIST.
12 * The code allocates a free address by passing NULL to first mmap call
13 * Then tries to mmap with the same address using MAP_FIXED_NOREPLACE flag
14 * and the mapping fails as expected.
15 */
16
17 #include <stdio.h>
18 #include <fcntl.h>
19 #include <sys/types.h>
20 #include <sys/mman.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include "lapi/mmap.h"
27 #include "tst_test.h"
28
29 static int fd_file1;
30 static int fd_file2;
31 static void *mapped_address;
32 static const char str[] = "Writing to mapped file";
33
34 #define FNAME1 "file1_to_mmap"
35 #define FNAME2 "file2_to_mmap"
36
setup(void)37 static void setup(void)
38 {
39 fd_file1 = SAFE_OPEN(FNAME1, O_CREAT | O_RDWR, 0600);
40 fd_file2 = SAFE_OPEN(FNAME2, O_CREAT | O_RDWR, 0600);
41 }
42
cleanup(void)43 static void cleanup(void)
44 {
45 int str_len;
46
47 str_len = strlen(str);
48
49 if (fd_file2 > 0)
50 SAFE_CLOSE(fd_file2);
51 if (fd_file1 > 0)
52 SAFE_CLOSE(fd_file1);
53 if (mapped_address)
54 SAFE_MUNMAP(mapped_address, str_len);
55 }
56
test_mmap(void)57 static void test_mmap(void)
58 {
59 int str_len;
60 void *address;
61
62 str_len = strlen(str);
63
64 SAFE_WRITE(1, fd_file1, str, str_len);
65 mapped_address = SAFE_MMAP(NULL, str_len, PROT_WRITE,
66 MAP_PRIVATE, fd_file1, 0);
67
68 SAFE_WRITE(1, fd_file2, str, str_len);
69
70 address = mmap(mapped_address, str_len, PROT_WRITE,
71 MAP_PRIVATE | MAP_FIXED_NOREPLACE, fd_file2, 0);
72 if (address == MAP_FAILED && errno == EEXIST)
73 tst_res(TPASS, "mmap set errno to EEXIST as expected");
74 else
75 tst_res(TFAIL | TERRNO, "mmap failed, with unexpected error "
76 "code, expected EEXIST");
77 }
78
79 static struct tst_test test = {
80 .setup = setup,
81 .cleanup = cleanup,
82 .test_all = test_mmap,
83 .min_kver = "4.17",
84 .needs_tmpdir = 1
85 };
86