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 <yangx.jy@cn.fujitsu.com>
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, %ld, %s) failed", TFILE,
50 tc->off, tc->wname);
51 return;
52 }
53
54 if (TST_RET != tc->exp_off) {
55 tst_res(TFAIL, "lseek(%s, %ld, %s) returned %ld, expected %ld",
56 TFILE, tc->off, tc->wname, TST_RET, tc->exp_off);
57 return;
58 }
59
60 SAFE_READ(1, fd, read_buf, tc->exp_size);
61
62 if (tc->exp_data && strcmp(read_buf, tc->exp_data)) {
63 tst_res(TFAIL, "lseek(%s, %ld, %s) read incorrect data",
64 TFILE, tc->off, tc->wname);
65 } else {
66 tst_res(TPASS, "lseek(%s, %ld, %s) read correct data",
67 TFILE, tc->off, tc->wname);
68 }
69 }
70
setup(void)71 static void setup(void)
72 {
73 fd = SAFE_OPEN(TFILE, O_RDWR | O_CREAT, 0644);
74
75 SAFE_WRITE(1, fd, WRITE_STR, sizeof(WRITE_STR) - 1);
76 }
77
cleanup(void)78 static void cleanup(void)
79 {
80 if (fd > 0)
81 SAFE_CLOSE(fd);
82 }
83
84 static struct tst_test test = {
85 .setup = setup,
86 .cleanup = cleanup,
87 .tcnt = ARRAY_SIZE(tcases),
88 .test = verify_lseek,
89 .needs_tmpdir = 1,
90 };
91