1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * Copyright (c) Red Hat Inc., 2007
5 * 11/2007 Copied from sendfile02.c by Masatake YAMATO
6 */
7
8 /*\
9 * [Description]
10 *
11 * Testcase to test that sendfile(2) system call returns EFAULT when passing
12 * wrong offset pointer.
13 *
14 * [Algorithm]
15 *
16 * Given wrong address or protected buffer as OFFSET argument to sendfile:
17 * - a wrong address is created by munmap a buffer allocated by mmap
18 * - a protected buffer is created by mmap with specifying protection
19 */
20
21 #include <sys/sendfile.h>
22 #include "tst_test.h"
23
24 static int in_fd;
25 static int out_fd;
26
27 struct test_case_t {
28 int protection;
29 int pass_unmapped_buffer;
30 const char *desc;
31 } tc[] = {
32 {PROT_NONE, 0, "pass_mapped_buffer"},
33 {PROT_READ, 0, "pass_mapped_buffer"},
34 {PROT_EXEC, 0, "pass_mapped_buffer"},
35 {PROT_EXEC | PROT_READ, 0, "pass_mapped_buffer"},
36 {PROT_READ | PROT_WRITE, 1, "pass_unmapped_buffer"}
37 };
38
setup(void)39 static void setup(void)
40 {
41 in_fd = SAFE_OPEN("in_file", O_CREAT | O_RDWR, 0600);
42 out_fd = SAFE_CREAT("out_file", 0600);
43 }
44
cleanup(void)45 static void cleanup(void)
46 {
47 SAFE_CLOSE(in_fd);
48 SAFE_CLOSE(out_fd);
49 }
50
run(unsigned int i)51 static void run(unsigned int i)
52 {
53 off_t *protected_buffer;
54 protected_buffer = SAFE_MMAP(NULL, sizeof(*protected_buffer),
55 tc[i].protection,
56 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
57
58 if (tc[i].pass_unmapped_buffer)
59 SAFE_MUNMAP(protected_buffer, sizeof(*protected_buffer));
60
61 TST_EXP_FAIL2(sendfile(out_fd, in_fd, protected_buffer, 1),
62 EFAULT, "sendfile(..) with %s, protection=%d",
63 tc[i].desc, tc[i].protection);
64
65 if (!tc[i].pass_unmapped_buffer)
66 SAFE_MUNMAP(protected_buffer, sizeof(*protected_buffer));
67 }
68
69 static struct tst_test test = {
70 .tcnt = ARRAY_SIZE(tc),
71 .needs_tmpdir = 1,
72 .cleanup = cleanup,
73 .setup = setup,
74 .test = run,
75 };
76