xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/ftruncate/ftruncate03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
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  * Author: Jay Huie, Robbie Williamson
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Verify that ftruncate(2) system call returns appropriate error number:
12  *
13  * 1. EINVAL -- the file is a socket
14  * 2. EINVAL -- the file descriptor was opened with O_RDONLY
15  * 3. EINVAL -- the length is negative
16  * 4. EBADF -- the file descriptor is invalid
17  */
18 
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 
27 #include "tst_test.h"
28 
29 #define TESTFILE1	"testfile1"
30 #define TESTFILE2	"testfile2"
31 
32 static int sock_fd, read_fd, fd;
33 static int bad_fd = -1;
34 
35 static struct tcase {
36 	int *fd;
37 	off_t length;
38 	int exp_errno;
39 } tcases[] = {
40 	{&sock_fd, 4, EINVAL},
41 	{&read_fd, 4, EINVAL},
42 	{&fd, -1, EINVAL},
43 	{&bad_fd, 4, EBADF},
44 };
45 
verify_ftruncate(unsigned int n)46 static void verify_ftruncate(unsigned int n)
47 {
48 	struct tcase *tc = &tcases[n];
49 
50 	TEST(ftruncate(*tc->fd, tc->length));
51 	if (TST_RET != -1) {
52 		tst_res(TFAIL, "ftruncate() succeeded unexpectedly and got %ld",
53 			TST_RET);
54 		return;
55 	}
56 
57 	if (TST_ERR == tc->exp_errno) {
58 		tst_res(TPASS | TTERRNO, "ftruncate() failed expectedly");
59 	} else {
60 		tst_res(TFAIL | TTERRNO,
61 			"ftruncate() failed unexpectedly, got %s, expected",
62 			tst_strerrno(tc->exp_errno));
63 	}
64 }
65 
setup(void)66 static void setup(void)
67 {
68 	sock_fd = SAFE_SOCKET(PF_INET, SOCK_STREAM, 0);
69 
70 	read_fd = SAFE_OPEN(TESTFILE1, O_RDONLY | O_CREAT, 0644);
71 
72 	fd = SAFE_OPEN(TESTFILE2, O_RDWR | O_CREAT, 0644);
73 }
74 
cleanup(void)75 static void cleanup(void)
76 {
77 	if (sock_fd > 0)
78 		SAFE_CLOSE(sock_fd);
79 
80 	if (read_fd > 0)
81 		SAFE_CLOSE(read_fd);
82 
83 	if (fd > 0)
84 		SAFE_CLOSE(fd);
85 }
86 
87 static struct tst_test test = {
88 	.tcnt = ARRAY_SIZE(tcases),
89 	.test = verify_ftruncate,
90 	.setup = setup,
91 	.cleanup = cleanup,
92 	.needs_tmpdir = 1,
93 };
94