• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *   Copyright (c) International Business Machines Corp., 2001
5  *	07/2001 Ported by John George
6  *      04/2002 wjhuie sigset cleanups
7  *      08/2007 Ricardo Salveti de Araujo <rsalveti@linux.vnet.ibm.com>
8  */
9 
10 /*
11  * DESCRIPTION
12  *	Check the return value, and errnos of write(2)
13  *	- when the file descriptor is invalid - EBADF
14  *	- when the buf parameter is invalid - EFAULT
15  *	- on an attempt to write to a pipe that is not open for reading - EPIPE
16  */
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <sys/wait.h>
24 #include <sys/mman.h>
25 #include "tst_test.h"
26 
27 static int fd;
28 static int inv_fd = -1;
29 static char b[32];
30 static char *buf = b;
31 static char *bad_addr;
32 static int pipefd[2];
33 
34 static struct tcase {
35 	int *fd;
36 	char **buf;
37 	size_t size;
38 	int exp_errno;
39 } tcases[] = {
40 	{&inv_fd, &buf, sizeof(buf), EBADF},
41 	{&fd, &bad_addr, sizeof(buf), EFAULT},
42 	{&pipefd[1], &buf, sizeof(buf), EPIPE},
43 };
44 
45 static int sigpipe_cnt;
46 
sighandler(int sig)47 static void sighandler(int sig)
48 {
49 	if (sig == SIGPIPE)
50 		sigpipe_cnt++;
51 }
52 
verify_write(unsigned int i)53 static void verify_write(unsigned int i)
54 {
55 	struct tcase *tc = &tcases[i];
56 
57 	sigpipe_cnt = 0;
58 
59 	TEST(write(*tc->fd, *tc->buf, tc->size));
60 
61 	if (TST_RET != -1) {
62 		tst_res(TFAIL, "write() succeeded unexpectedly");
63 		return;
64 	}
65 
66 	if (TST_ERR != tc->exp_errno) {
67 		tst_res(TFAIL | TTERRNO,
68 			"write() failed unexpectedly, expected %s",
69 			tst_strerrno(tc->exp_errno));
70 		return;
71 	}
72 
73 	if (tc->exp_errno == EPIPE && sigpipe_cnt != 1) {
74 		tst_res(TFAIL, "sigpipe_cnt = %i", sigpipe_cnt);
75 		return;
76 	}
77 
78 	tst_res(TPASS | TTERRNO, "write() failed expectedly");
79 }
80 
setup(void)81 static void setup(void)
82 {
83 	fd = SAFE_OPEN("write_test", O_RDWR | O_CREAT, 0644);
84 
85 	bad_addr = SAFE_MMAP(0, 1, PROT_NONE,
86 			MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
87 
88 	SAFE_PIPE(pipefd);
89 	SAFE_CLOSE(pipefd[0]);
90 
91 	SAFE_SIGNAL(SIGPIPE, sighandler);
92 }
93 
cleanup(void)94 static void cleanup(void)
95 {
96 	if (fd > 0)
97 		SAFE_CLOSE(fd);
98 
99 	SAFE_MUNMAP(bad_addr, 1);
100 }
101 
102 static struct tst_test test = {
103 	.needs_tmpdir = 1,
104 	.setup = setup,
105 	.cleanup = cleanup,
106 	.test = verify_write,
107 	.tcnt = ARRAY_SIZE(tcases),
108 };
109