aboutsummaryrefslogtreecommitdiff
path: root/testcases/kernel/syscalls/preadv/preadv01.c
blob: 871b3ab42be2bd82efe06209a7bc8821d7f8feb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (c) 2015 Fujitsu Ltd.
 * Author: Xiao Yang <yangx.jy@cn.fujitsu.com>
 * Copyright (c) Linux Test Project, 2016-2023
 */

/*\
 * [Description]
 *
 * Testcase to check the basic functionality of the preadv(2).
 *
 * Preadv(2) should succeed to read the expected content of data
 * and after reading the file, the file offset is not changed.
 */

#define _GNU_SOURCE

#include <string.h>
#include <sys/uio.h>

#include "tst_test.h"
#include "preadv.h"

#define CHUNK           64

static int fd;

static struct iovec *rd_iovec;

static struct tcase {
	int count;
	off_t offset;
	ssize_t size;
	char content;
} tcases[] = {
	{1, 0, CHUNK, 'a'},
	{2, 0, CHUNK, 'a'},
	{1, CHUNK*3/2, CHUNK/2, 'b'}
};

static void verify_preadv(unsigned int n)
{
	int i;
	char *vec;
	struct tcase *tc = &tcases[n];

	vec = rd_iovec[0].iov_base;
	memset(vec, 0x00, CHUNK);

	SAFE_LSEEK(fd, 0, SEEK_SET);

	TEST(preadv(fd, rd_iovec, tc->count, tc->offset));
	if (TST_RET < 0) {
		tst_res(TFAIL | TTERRNO, "Preadv(2) failed");
		return;
	}

	if (TST_RET != tc->size) {
		tst_res(TFAIL, "Preadv(2) read %li bytes, expected %zi",
			 TST_RET, tc->size);
		return;
	}

	for (i = 0; i < tc->size; i++) {
		if (vec[i] != tc->content)
			break;
	}

	if (i < tc->size) {
		tst_res(TFAIL, "Buffer wrong at %i have %02x expected %02x",
			 i, vec[i], tc->content);
		return;
	}

	if (SAFE_LSEEK(fd, 0, SEEK_CUR) != 0) {
		tst_res(TFAIL, "Preadv(2) has changed file offset");
		return;
	}

	tst_res(TPASS, "Preadv(2) read %zi bytes successfully "
		 "with content '%c' expectedly", tc->size, tc->content);
}

static void setup(void)
{
	char buf[CHUNK];

	fd = SAFE_OPEN("file", O_RDWR | O_CREAT, 0644);

	memset(buf, 'a', sizeof(buf));
	SAFE_WRITE(SAFE_WRITE_ALL, fd, buf, sizeof(buf));

	memset(buf, 'b', sizeof(buf));
	SAFE_WRITE(SAFE_WRITE_ALL, fd, buf, sizeof(buf));
}

static void cleanup(void)
{
	if (fd > 0)
		SAFE_CLOSE(fd);
}

static struct tst_test test = {
	.tcnt = ARRAY_SIZE(tcases),
	.setup = setup,
	.cleanup = cleanup,
	.test = verify_preadv,
	.needs_tmpdir = 1,
	.bufs = (struct tst_buffers []) {
		{&rd_iovec, .iov_sizes = (int[]){CHUNK, 0, -1}},
		{},
	}
};