• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2002
4  * Copyright (c) 2019 FUJITSU LIMITED. All rights reserved.
5  *
6  * Jay Huie
7  * Robbie Williamson
8  */
9 /*
10  * Test Description:
11  *  Verify that,
12  *  1)ftruncate() fails with EINVAL if the file is a socket.
13  *  2)ftruncate() fails with EINVAL if the file descriptor opens with O_RDONLY.
14  *  3)ftruncate() fails with EINVAL if the length is negative.
15  *  4)ftruncate() fails with EBADF if the file descriptor is invalid.
16  */
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <sys/socket.h>
25 
26 #include "tst_test.h"
27 
28 #define TESTFILE1	"testfile1"
29 #define TESTFILE2	"testfile2"
30 
31 static int sock_fd, read_fd, fd;
32 static int bad_fd = -1;
33 
34 static struct tcase {
35 	int *fd;
36 	off_t length;
37 	int exp_errno;
38 } tcases[] = {
39 	{&sock_fd, 4, EINVAL},
40 	{&read_fd, 4, EINVAL},
41 	{&fd, -1, EINVAL},
42 	{&bad_fd, 4, EBADF},
43 };
44 
verify_ftruncate(unsigned int n)45 static void verify_ftruncate(unsigned int n)
46 {
47 	struct tcase *tc = &tcases[n];
48 
49 	TEST(ftruncate(*tc->fd, tc->length));
50 	if (TST_RET != -1) {
51 		tst_res(TFAIL, "ftruncate() succeeded unexpectedly and got %ld",
52 			TST_RET);
53 		return;
54 	}
55 
56 	if (TST_ERR == tc->exp_errno) {
57 		tst_res(TPASS | TTERRNO, "ftruncate() failed expectedly");
58 	} else {
59 		tst_res(TFAIL | TTERRNO,
60 			"ftruncate() failed unexpectedly, got %s, expected",
61 			tst_strerrno(tc->exp_errno));
62 	}
63 }
64 
setup(void)65 static void setup(void)
66 {
67 	sock_fd = SAFE_SOCKET(PF_INET, SOCK_STREAM, 0);
68 
69 	read_fd = SAFE_OPEN(TESTFILE1, O_RDONLY | O_CREAT, 0644);
70 
71 	fd = SAFE_OPEN(TESTFILE2, O_RDWR | O_CREAT, 0644);
72 }
73 
cleanup(void)74 static void cleanup(void)
75 {
76 	if (sock_fd > 0)
77 		SAFE_CLOSE(sock_fd);
78 
79 	if (read_fd > 0)
80 		SAFE_CLOSE(read_fd);
81 
82 	if (fd > 0)
83 		SAFE_CLOSE(fd);
84 }
85 
86 static struct tst_test test = {
87 	.tcnt = ARRAY_SIZE(tcases),
88 	.test = verify_ftruncate,
89 	.setup = setup,
90 	.cleanup = cleanup,
91 	.needs_tmpdir = 1,
92 };
93