1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * 06/2017 modified by Xiao Yang <[email protected]>
5 */
6
7 /*
8 * Description:
9 * lseek() succeeds to set the specified offset according to whence
10 * and read valid data from this location.
11 */
12
13 #include <errno.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17 #include "tst_test.h"
18
19 #define WRITE_STR "abcdefg"
20 #define TFILE "tfile"
21
22 static int fd;
23 static struct tcase {
24 off_t off;
25 int whence;
26 char *wname;
27 off_t exp_off;
28 ssize_t exp_size;
29 char *exp_data;
30 } tcases[] = {
31 {4, SEEK_SET, "SEEK_SET", 4, 3, "efg"},
32 {-2, SEEK_CUR, "SEEK_CUR", 5, 2, "fg"},
33 {-4, SEEK_END, "SEEK_END", 3, 4, "defg"},
34 {0, SEEK_END, "SEEK_END", 7, 0, NULL},
35 };
36
verify_lseek(unsigned int n)37 static void verify_lseek(unsigned int n)
38 {
39 char read_buf[64];
40 struct tcase *tc = &tcases[n];
41
42 // reset the offset to end of file
43 SAFE_READ(0, fd, read_buf, sizeof(read_buf));
44
45 memset(read_buf, 0, sizeof(read_buf));
46
47 TEST(lseek(fd, tc->off, tc->whence));
48 if (TST_RET == (off_t) -1) {
49 tst_res(TFAIL | TTERRNO, "lseek(%s, %lld, %s) failed", TFILE,
50 (long long int)tc->off, tc->wname);
51 return;
52 }
53
54 if (TST_RET != tc->exp_off) {
55 tst_res(TFAIL, "lseek(%s, %lld, %s) returned %ld, expected %lld",
56 TFILE, (long long int)tc->off, tc->wname, TST_RET,
57 (long long int)tc->exp_off);
58 return;
59 }
60
61 SAFE_READ(1, fd, read_buf, tc->exp_size);
62
63 if (tc->exp_data && strcmp(read_buf, tc->exp_data)) {
64 tst_res(TFAIL, "lseek(%s, %lld, %s) read incorrect data",
65 TFILE, (long long int)tc->off, tc->wname);
66 } else {
67 tst_res(TPASS, "lseek(%s, %lld, %s) read correct data",
68 TFILE, (long long int)tc->off, tc->wname);
69 }
70 }
71
setup(void)72 static void setup(void)
73 {
74 fd = SAFE_OPEN(TFILE, O_RDWR | O_CREAT, 0644);
75
76 SAFE_WRITE(SAFE_WRITE_ALL, fd, WRITE_STR, sizeof(WRITE_STR) - 1);
77 }
78
cleanup(void)79 static void cleanup(void)
80 {
81 if (fd > 0)
82 SAFE_CLOSE(fd);
83 }
84
85 static struct tst_test test = {
86 .setup = setup,
87 .cleanup = cleanup,
88 .tcnt = ARRAY_SIZE(tcases),
89 .test = verify_lseek,
90 .needs_tmpdir = 1,
91 };
92