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 *
18 * - a wrong address is created by munmap a buffer allocated by mmap
19 * - a protected buffer is created by mmap with specifying protection
20 */
21
22 #include <sys/sendfile.h>
23 #include "tst_test.h"
24
25 static int in_fd;
26 static int out_fd;
27
28 struct test_case_t {
29 int protection;
30 int pass_unmapped_buffer;
31 const char *desc;
32 } tc[] = {
33 {PROT_NONE, 0, "pass_mapped_buffer"},
34 {PROT_READ, 0, "pass_mapped_buffer"},
35 {PROT_EXEC, 0, "pass_mapped_buffer"},
36 {PROT_EXEC | PROT_READ, 0, "pass_mapped_buffer"},
37 {PROT_READ | PROT_WRITE, 1, "pass_unmapped_buffer"}
38 };
39
setup(void)40 static void setup(void)
41 {
42 in_fd = SAFE_OPEN("in_file", O_CREAT | O_RDWR, 0600);
43 out_fd = SAFE_CREAT("out_file", 0600);
44 }
45
cleanup(void)46 static void cleanup(void)
47 {
48 SAFE_CLOSE(in_fd);
49 SAFE_CLOSE(out_fd);
50 }
51
run(unsigned int i)52 static void run(unsigned int i)
53 {
54 off_t *protected_buffer;
55 protected_buffer = SAFE_MMAP(NULL, sizeof(*protected_buffer),
56 tc[i].protection,
57 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
58
59 if (tc[i].pass_unmapped_buffer)
60 SAFE_MUNMAP(protected_buffer, sizeof(*protected_buffer));
61
62 TST_EXP_FAIL2(sendfile(out_fd, in_fd, protected_buffer, 1),
63 EFAULT, "sendfile(..) with %s, protection=%d",
64 tc[i].desc, tc[i].protection);
65
66 if (!tc[i].pass_unmapped_buffer)
67 SAFE_MUNMAP(protected_buffer, sizeof(*protected_buffer));
68 }
69
70 static struct tst_test test = {
71 .tcnt = ARRAY_SIZE(tc),
72 .needs_tmpdir = 1,
73 .cleanup = cleanup,
74 .setup = setup,
75 .test = run,
76 };
77