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/stat.h> 21#include <unistd.h> 22#include <errno.h> 23#include <string.h> 24#include <stdlib.h> 25#include "lapi/mmap.h" 26#include "tst_test.h" 27 28static int fd_file1; 29static int fd_file2; 30static void *mapped_address; 31static const char str[] = "Writing to mapped file"; 32 33#define FNAME1 "file1_to_mmap" 34#define FNAME2 "file2_to_mmap" 35 36static void setup(void) 37{ 38 fd_file1 = SAFE_OPEN(FNAME1, O_CREAT | O_RDWR, 0600); 39 fd_file2 = SAFE_OPEN(FNAME2, O_CREAT | O_RDWR, 0600); 40} 41 42static void cleanup(void) 43{ 44 int str_len; 45 46 str_len = strlen(str); 47 48 if (fd_file2 > 0) 49 SAFE_CLOSE(fd_file2); 50 if (fd_file1 > 0) 51 SAFE_CLOSE(fd_file1); 52 if (mapped_address) 53 SAFE_MUNMAP(mapped_address, str_len); 54} 55 56static void test_mmap(void) 57{ 58 int str_len; 59 void *address; 60 61 str_len = strlen(str); 62 63 SAFE_WRITE(SAFE_WRITE_ALL, fd_file1, str, str_len); 64 mapped_address = SAFE_MMAP(NULL, str_len, PROT_WRITE, 65 MAP_PRIVATE, fd_file1, 0); 66 67 SAFE_WRITE(SAFE_WRITE_ALL, fd_file2, str, str_len); 68 69 address = mmap(mapped_address, str_len, PROT_WRITE, 70 MAP_PRIVATE | MAP_FIXED_NOREPLACE, fd_file2, 0); 71 if (address == MAP_FAILED && errno == EEXIST) 72 tst_res(TPASS, "mmap set errno to EEXIST as expected"); 73 else 74 tst_res(TFAIL | TERRNO, "mmap failed, with unexpected error " 75 "code, expected EEXIST"); 76} 77 78static struct tst_test test = { 79 .setup = setup, 80 .cleanup = cleanup, 81 .test_all = test_mmap, 82 .min_kver = "4.17", 83 .needs_tmpdir = 1 84}; 85