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, %lld, SEEK_SET) failed",
47 tc->fname, (long long int)tc->off);
48 return;
49 }
50
51 if (TST_RET != tc->exp_off) {
52 tst_res(TFAIL, "lseek(%s, %lld, SEEK_SET) returned %ld, expected %lld",
53 tc->fname, (long long int)tc->off, TST_RET,
54 (long long int)tc->exp_off);
55 return;
56 }
57
58 SAFE_WRITE(SAFE_WRITE_ALL, *tc->fd, WR_STR2, sizeof(WR_STR2) - 1);
59
60 SAFE_CLOSE(*tc->fd);
61
62 *tc->fd = SAFE_OPEN(tc->fname, O_RDWR);
63
64 SAFE_READ(1, *tc->fd, read_buf, tc->exp_size);
65
66 if (strcmp(read_buf, tc->exp_data)) {
67 tst_res(TFAIL, "lseek(%s, %lld, SEEK_SET) wrote incorrect data %s",
68 tc->fname, (long long int)tc->off, read_buf);
69 } else {
70 tst_res(TPASS, "lseek(%s, %lld, SEEK_SET) wrote correct data %s",
71 tc->fname, (long long int)tc->off, read_buf);
72 }
73 }
74
setup(void)75 static void setup(void)
76 {
77 fd1 = SAFE_OPEN(TFILE1, O_RDWR | O_CREAT, 0644);
78 fd2 = SAFE_OPEN(TFILE2, O_RDWR | O_CREAT, 0644);
79
80 SAFE_WRITE(SAFE_WRITE_ALL, fd1, WR_STR1, sizeof(WR_STR1) - 1);
81 SAFE_WRITE(SAFE_WRITE_ALL, fd2, WR_STR1, sizeof(WR_STR1) - 1);
82 }
83
cleanup(void)84 static void cleanup(void)
85 {
86 if (fd1 > 0)
87 SAFE_CLOSE(fd1);
88
89 if (fd2 > 0)
90 SAFE_CLOSE(fd2);
91 }
92
93 static struct tst_test test = {
94 .setup = setup,
95 .cleanup = cleanup,
96 .tcnt = ARRAY_SIZE(tcases),
97 .test = verify_lseek,
98 .needs_tmpdir = 1,
99 };
100