• 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  * Copyright (c) 2019 FUJITSU LIMITED. All rights reserved.
5  * Author: Wayne Boyer
6  */
7 /*
8  * Test Description:
9  *  Verify that, ftruncate() succeeds to truncate a file to a certain length,
10  *  if the file previously is smaller than the truncated size, ftruncate()
11  *  shall increase the size of the file.
12  */
13 
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <string.h>
20 
21 #include "tst_test.h"
22 
23 #define TESTFILE	"testfile"
24 
25 #define TRUNC_LEN1	256
26 #define TRUNC_LEN2	512
27 #define FILE_SIZE	1024
28 
29 static int fd;
30 
check_and_report(off_t offset,char data,off_t trunc_len)31 static void check_and_report(off_t offset, char data, off_t trunc_len)
32 {
33 	int i, file_length;
34 	char buf[FILE_SIZE];
35 	struct stat stat_buf;
36 
37 	memset(buf, '*', sizeof(buf));
38 
39 	SAFE_FSTAT(fd, &stat_buf);
40 	file_length = stat_buf.st_size;
41 
42 	if (file_length != trunc_len) {
43 		tst_res(TFAIL, "ftruncate() got incorrected size: %d",
44 			file_length);
45 		return;
46 	}
47 
48 	SAFE_LSEEK(fd, offset, SEEK_SET);
49 	SAFE_READ(0, fd, buf, sizeof(buf));
50 
51 	for (i = 0; i < TRUNC_LEN1; i++) {
52 		if (buf[i] != data) {
53 			tst_res(TFAIL,
54 				"ftruncate() got incorrect data %i, expected %i",
55 				buf[i], data);
56 			return;
57 		}
58 	}
59 
60 	tst_res(TPASS, "ftruncate() succeeded");
61 }
62 
verify_ftruncate(void)63 static void verify_ftruncate(void)
64 {
65 	tst_res(TINFO, "Truncated length smaller than file size");
66 	TEST(ftruncate(fd, TRUNC_LEN1));
67 	if (TST_RET == -1) {
68 		tst_res(TFAIL | TTERRNO, "ftruncate() failed");
69 		return;
70 	}
71 
72 	check_and_report(0, 'a', TRUNC_LEN1);
73 
74 	tst_res(TINFO, "Truncated length exceeds file size");
75 	TEST(ftruncate(fd, TRUNC_LEN2));
76 	if (TST_RET == -1) {
77 		tst_res(TFAIL | TTERRNO, "ftruncate() failed");
78 		return;
79 	}
80 
81 	check_and_report(TRUNC_LEN1, 0, TRUNC_LEN2);
82 }
83 
setup(void)84 static void setup(void)
85 {
86 	if (tst_fill_file(TESTFILE, 'a', FILE_SIZE, 1))
87 		tst_brk(TBROK, "Failed to create test file");
88 
89 	fd = SAFE_OPEN(TESTFILE, O_RDWR);
90 }
91 
cleanup(void)92 static void cleanup(void)
93 {
94 	if (fd > 0)
95 		SAFE_CLOSE(fd);
96 }
97 
98 static struct tst_test test = {
99 	.test_all = verify_ftruncate,
100 	.setup = setup,
101 	.cleanup = cleanup,
102 	.needs_tmpdir = 1,
103 };
104