1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * 07/2001 John George
5 */
6
7 /*\
8 * [Description]
9 *
10 * Verify that:
11 *
12 * - truncate(2) truncates a file to a specified length successfully.
13 * - If the file is larger than the specified length, the extra data is lost.
14 * - If the file is shorter than the specified length, the extra data is filled by '0'.
15 * - truncate(2) doesn't change offset.
16 */
17
18 #include <errno.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <string.h>
23
24 #include "tst_test.h"
25 #include "tst_safe_prw.h"
26
27 #define TESTFILE "testfile"
28 #define FILE_SIZE 1024
29 #define TRUNC_LEN1 256
30 #define TRUNC_LEN2 512
31
32 static int fd;
33
34 static struct tcase {
35 off_t trunc_len;
36 off_t read_off;
37 off_t read_count;
38 char exp_char;
39 } tcases[] = {
40 {TRUNC_LEN1, 0, TRUNC_LEN1, 'a'},
41 {TRUNC_LEN2, TRUNC_LEN1, TRUNC_LEN1, '\0'},
42 };
43
verify_truncate(unsigned int n)44 static void verify_truncate(unsigned int n)
45 {
46 struct tcase *tc = &tcases[n];
47 struct stat stat_buf;
48 char read_buf[tc->read_count];
49 int i;
50
51 memset(read_buf, 'b', tc->read_count);
52
53 TEST(truncate(TESTFILE, tc->trunc_len));
54 if (TST_RET == -1) {
55 tst_res(TFAIL | TTERRNO, "truncate(%s, %ld) failed",
56 TESTFILE, tc->trunc_len);
57 return;
58 }
59
60 if (TST_RET != 0) {
61 tst_res(TFAIL | TTERRNO,
62 "truncate(%s, %ld) returned invalid value %ld",
63 TESTFILE, tc->trunc_len, TST_RET);
64 return;
65 }
66
67 SAFE_STAT(TESTFILE, &stat_buf);
68 if (stat_buf.st_size != tc->trunc_len) {
69 tst_res(TFAIL, "%s: Incorrect file size %ld, expected %ld",
70 TESTFILE, stat_buf.st_size, tc->trunc_len);
71 return;
72 }
73
74 if (SAFE_LSEEK(fd, 0, SEEK_CUR)) {
75 tst_res(TFAIL, "truncate(%s, %ld) changes offset",
76 TESTFILE, tc->trunc_len);
77 return;
78 }
79
80 SAFE_PREAD(1, fd, read_buf, tc->read_count, tc->read_off);
81 for (i = 0; i < tc->read_count; i++) {
82 if (read_buf[i] != tc->exp_char) {
83 tst_res(TFAIL, "%s: wrong content %c, expected %c",
84 TESTFILE, read_buf[i], tc->exp_char);
85 return;
86 }
87 }
88
89 tst_res(TPASS, "truncate(%s, %ld) succeeded",
90 TESTFILE, tc->trunc_len);
91 }
92
setup(void)93 static void setup(void)
94 {
95 fd = SAFE_OPEN(TESTFILE, O_RDWR | O_CREAT, 0644);
96
97 tst_fill_fd(fd, 'a', FILE_SIZE, 1);
98
99 SAFE_LSEEK(fd, 0, SEEK_SET);
100 }
101
cleanup(void)102 static void cleanup(void)
103 {
104 if (fd > 0)
105 SAFE_CLOSE(fd);
106 }
107
108 static struct tst_test test = {
109 .needs_tmpdir = 1,
110 .setup = setup,
111 .cleanup = cleanup,
112 .tcnt = ARRAY_SIZE(tcases),
113 .test = verify_truncate,
114 };
115