1 /* 2 * Copyright (c) International Business Machines Corp., 2001 3 * 07/2001 Ported by John George 4 * Copyright (c) 2017 Fujitsu Ltd. 5 * 04/2017 Modified by Jinhui Huang 6 * 7 * This program is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2 of the License, or 10 * (at your option) any later version. 11 * 12 * This program is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 15 * the GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with this program; if not, write to the Free Software 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 20 */ 21 22 /* 23 * DESCRIPTION 24 * Testcase to check that write(2) doesn't corrupt a file when it fails 25 * 26 * ALGORITHM 27 * Create a file for writing, write 100 bytes to it. Then make write(2) 28 * fail with some erroneous parameter, close the fd. Then reopen the 29 * file in RDONLY mode, and read the contents of the file. Compare the 30 * buffers, to see whether they are same. 31 */ 32 33 #include <stdio.h> 34 #include <errno.h> 35 #include "tst_test.h" 36 37 static char *bad_addr; 38 static char wbuf[BUFSIZ], rbuf[BUFSIZ]; 39 static int fd; 40 41 static void verify_write(void) 42 { 43 fd = SAFE_CREAT("testfile", 0644); 44 45 SAFE_WRITE(1, fd, wbuf, 100); 46 47 if (write(fd, bad_addr, 100) != -1) { 48 tst_res(TFAIL, "write() failed to fail"); 49 SAFE_CLOSE(fd); 50 return; 51 } 52 53 SAFE_CLOSE(fd); 54 55 fd = SAFE_OPEN("testfile", O_RDONLY); 56 57 memset(rbuf, 0, BUFSIZ); 58 59 SAFE_READ(0, fd, rbuf, 100); 60 61 if (memcmp(wbuf, rbuf, 100) == 0) 62 tst_res(TPASS, "failure of write() did not corrupt the file"); 63 else 64 tst_res(TFAIL, "failure of write() corrupted the file"); 65 66 SAFE_CLOSE(fd); 67 } 68 69 static void setup(void) 70 { 71 bad_addr = SAFE_MMAP(0, 1, PROT_NONE, 72 MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); 73 74 memset(wbuf, '0', 100); 75 } 76 77 static void cleanup(void) 78 { 79 if (fd > 0) 80 SAFE_CLOSE(fd); 81 } 82 83 static struct tst_test test = { 84 .test_all = verify_write, 85 .setup = setup, 86 .cleanup = cleanup, 87 .needs_tmpdir = 1, 88 }; 89