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 write 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 TFILE1 "tfile1"
20 #define TFILE2 "tfile2"
21 #define WR_STR1 "abcdefg"
22 #define WR_STR2 "ijk"
23
24 static int fd1, fd2;
25 static struct tcase {
26 int *fd;
27 char *fname;
28 off_t off;
29 off_t exp_off;
30 int exp_size;
31 char *exp_data;
32 } tcases[] = {
33 {&fd1, TFILE1, 7, 7, 10, "abcdefgijk"},
34 {&fd2, TFILE2, 2, 2, 7, "abijkfg"},
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 memset(read_buf, 0, sizeof(read_buf));
43
44 TEST(lseek(*tc->fd, tc->off, SEEK_SET));
45 if (TST_RET == (off_t) -1) {
46 tst_res(TFAIL | TTERRNO, "lseek(%s, %ld, SEEK_SET) failed",
47 tc->fname, tc->off);
48 return;
49 }
50
51 if (TST_RET != tc->exp_off) {
52 tst_res(TFAIL, "lseek(%s, %ld, SEEK_SET) returned %ld, expected %ld",
53 tc->fname, tc->off, TST_RET, tc->exp_off);
54 return;
55 }
56
57 SAFE_WRITE(1, *tc->fd, WR_STR2, sizeof(WR_STR2) - 1);
58
59 SAFE_CLOSE(*tc->fd);
60
61 *tc->fd = SAFE_OPEN(tc->fname, O_RDWR);
62
63 SAFE_READ(1, *tc->fd, read_buf, tc->exp_size);
64
65 if (strcmp(read_buf, tc->exp_data)) {
66 tst_res(TFAIL, "lseek(%s, %ld, SEEK_SET) wrote incorrect data %s",
67 tc->fname, tc->off, read_buf);
68 } else {
69 tst_res(TPASS, "lseek(%s, %ld, SEEK_SET) wrote correct data %s",
70 tc->fname, tc->off, read_buf);
71 }
72 }
73
setup(void)74 static void setup(void)
75 {
76 fd1 = SAFE_OPEN(TFILE1, O_RDWR | O_CREAT, 0644);
77 fd2 = SAFE_OPEN(TFILE2, O_RDWR | O_CREAT, 0644);
78
79 SAFE_WRITE(1, fd1, WR_STR1, sizeof(WR_STR1) - 1);
80 SAFE_WRITE(1, fd2, WR_STR1, sizeof(WR_STR1) - 1);
81 }
82
cleanup(void)83 static void cleanup(void)
84 {
85 if (fd1 > 0)
86 SAFE_CLOSE(fd1);
87
88 if (fd2 > 0)
89 SAFE_CLOSE(fd2);
90 }
91
92 static struct tst_test test = {
93 .setup = setup,
94 .cleanup = cleanup,
95 .tcnt = ARRAY_SIZE(tcases),
96 .test = verify_lseek,
97 .needs_tmpdir = 1,
98 };
99