• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  * 07/2001 Ported by Wayne Boyer
5  * 08/2002 Make it use a socket so it works with 2.5 kernel
6  * Copyright (c) 2021 Xie Ziyao <xieziyao@huawei.com>
7  */
8 
9 /*\
10  * [Description]
11  *
12  * Test the basic functionality of the sendfile() system call:
13  *
14  * 1. Call sendfile() with offset = 0.
15  * 2. Call sendfile() with offset in the middle of the file.
16  */
17 
18 #include <stdio.h>
19 #include <inttypes.h>
20 #include <sys/sendfile.h>
21 
22 #include "tst_test.h"
23 
24 #define IN_FILE "in_file"
25 #define OUT_FILE "out_file"
26 
27 #define OFFSET_DESC(x) .desc = "with offset = "#x, .offset = x
28 
29 struct test_case_t {
30 	char *desc;
31 	off_t offset;
32 	int64_t count;
33 	int64_t exp_retval;
34 	int64_t exp_updated_offset;
35 } tc[] = {
36 	{ OFFSET_DESC(0), 26, 26, 26 },
37 	{ OFFSET_DESC(2), 24, 24, 26 },
38 };
39 
setup(void)40 static void setup(void)
41 {
42 	int fd;
43 	char buf[27];
44 
45 	fd = SAFE_CREAT(IN_FILE, 00700);
46 	sprintf(buf, "abcdefghijklmnopqrstuvwxyz");
47 	SAFE_WRITE(SAFE_WRITE_ALL, fd, buf, strlen(buf));
48 	SAFE_CLOSE(fd);
49 
50 	fd = SAFE_CREAT(OUT_FILE, 00700);
51 	SAFE_CLOSE(fd);
52 }
53 
run(unsigned int i)54 static void run(unsigned int i)
55 {
56 	int in_fd = SAFE_OPEN(IN_FILE, O_RDONLY);
57 	int out_fd = SAFE_OPEN(OUT_FILE, O_WRONLY);
58 	off_t offset = tc[i].offset;
59 	off_t before_pos, after_pos;
60 
61 	before_pos = SAFE_LSEEK(in_fd, 0, SEEK_CUR);
62 
63 	TEST(sendfile(out_fd, in_fd, &offset, tc[i].count));
64 	after_pos = SAFE_LSEEK(in_fd, 0, SEEK_CUR);
65 
66 	if (tc[i].exp_retval != TST_RET)
67 		tst_res(TFAIL, "sendfile() failed to return expected value, "
68 			       "expected: %" PRId64 ", got: %ld",
69 			tc[i].exp_retval, TST_RET);
70 	else if (offset != tc[i].exp_updated_offset)
71 		tst_res(TFAIL, "sendfile() failed to update OFFSET parameter to "
72 			       "expected value, expected: %" PRId64 ", got: %" PRId64,
73 			tc[i].exp_updated_offset, (int64_t)(offset));
74 	else if (before_pos != after_pos)
75 		tst_res(TFAIL, "sendfile() updated the file position of in_fd "
76 			       "unexpectedly, expected file position: %" PRId64
77 			       ", actual file position %" PRId64,
78 			(int64_t)(before_pos), (int64_t)(after_pos));
79 	else
80 		tst_res(TPASS, "sendfile() with %s", tc[i].desc);
81 
82 	SAFE_CLOSE(in_fd);
83 	SAFE_CLOSE(out_fd);
84 }
85 
86 static struct tst_test test = {
87 		.needs_tmpdir = 1,
88 		.setup = setup,
89 		.test = run,
90 		.tcnt = ARRAY_SIZE(tc),
91 };
92