• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  *  07/2001 Ported by Wayne Boyer
5  *  05/2019 Ported to new library: Christian Amann <camann@suse.com>
6  */
7 /*
8  * Tests different error scenarios:
9  *
10  * 1) Calls fstat() with closed file descriptor
11  *    -> EBADF
12  * 2) Calls fstat() with an invalid address for stat structure
13  *    -> EFAULT (or receive signal SIGSEGV)
14  */
15 
16 #include <errno.h>
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <wait.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include "tst_test.h"
23 #include "tst_safe_macros.h"
24 
25 #define TESTFILE	"test_file"
26 
27 static int fd_ok;
28 static int fd_ebadf = -1;
29 static struct stat stat_buf;
30 
31 static struct tcase {
32 	int *fd;
33 	struct stat *stat_buf;
34 	int exp_err;
35 } tcases[] = {
36 	{&fd_ebadf, &stat_buf, EBADF},
37 	{&fd_ok, NULL, EFAULT},
38 };
39 
check_fstat(unsigned int tc_num)40 static void check_fstat(unsigned int tc_num)
41 {
42 	struct tcase *tc = &tcases[tc_num];
43 
44 	TEST(fstat(*tc->fd, tc->stat_buf));
45 	if (TST_RET == -1) {
46 		if (tc->exp_err == TST_ERR) {
47 			tst_res(TPASS,
48 				 "fstat() fails with expected error %s",
49 				 tst_strerrno(tc->exp_err));
50 		} else {
51 			tst_res(TFAIL | TTERRNO,
52 				 "fstat() did not fail with %s, but with",
53 				 tst_strerrno(tc->exp_err));
54 		}
55 	} else {
56 		tst_res(TFAIL, "fstat() returned %ld, expected -1",
57 			 TST_RET);
58 	}
59 }
60 
run(unsigned int tc_num)61 static void run(unsigned int tc_num)
62 {
63 	pid_t pid;
64 	int status;
65 
66 	pid = SAFE_FORK();
67 	if (pid == 0) {
68 		check_fstat(tc_num);
69 		return;
70 	}
71 	SAFE_WAITPID(pid, &status, 0);
72 
73 	if (tcases[tc_num].exp_err == EFAULT && WTERMSIG(status) == SIGSEGV) {
74 		tst_res(TPASS, "fstat() failed as expected with SIGSEGV");
75 		return;
76 	}
77 
78 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
79 		return;
80 
81 	tst_res(TFAIL, "child %s", tst_strstatus(status));
82 }
83 
setup(void)84 static void setup(void)
85 {
86 	fd_ok = SAFE_OPEN(TESTFILE, O_RDWR | O_CREAT, 0644);
87 }
88 
cleanup(void)89 static void cleanup(void)
90 {
91 	if (fd_ok > 0)
92 		SAFE_CLOSE(fd_ok);
93 }
94 
95 static struct tst_test test = {
96 	.test = run,
97 	.tcnt = ARRAY_SIZE(tcases),
98 	.setup = setup,
99 	.cleanup = cleanup,
100 	.needs_tmpdir = 1,
101 	.forks_child = 1,
102 };
103