1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Linux Test Project, 2009-2021
4 * Copyright (c) 2016 Oracle and/or its affiliates. All Rights Reserved.
5 * Copyright (c) International Business Machines Corp., 2006
6 * Author: Yi Yang <yyangcdl@cn.ibm.com>
7 */
8
9 /*\
10 * [Description]
11 * Basic unlinkat() test.
12 */
13
14 #include "tst_test.h"
15 #include "lapi/syscalls.h"
16 #include "tst_safe_stdio.h"
17 #include "lapi/fcntl.h"
18
19 static const char pathname[] = "unlinkattestdir",
20 subpathname[] = "unlinkatsubtestdir",
21 subpathdir[] = "unlinkattestdir/unlinkatsubtestdir",
22 testfile[] = "unlinkattestfile.txt",
23 testfile2[] = "unlinkattestdir/unlinkattestfile.txt";
24
25 static char *testfile3;
26
27 static int fd;
getfd(int i)28 static int getfd(int i)
29 {
30 if (i == 2)
31 fd = SAFE_OPEN(testfile3, O_CREAT | O_RDWR, 0600);
32 else
33 fd = SAFE_OPEN(pathname, O_DIRECTORY);
34
35 return fd;
36 }
37
38 static struct tcase {
39 int fd;
40 const char *filename;
41 int flag;
42 int exp_errno;
43 } tc[] = {
44 {0, testfile, 0, 0},
45 {0, NULL, 0, 0},
46 {0, testfile, 0, ENOTDIR},
47 {100, testfile, 0, EBADF},
48 {0, testfile, 9999, EINVAL},
49 {AT_FDCWD, testfile, 0, 0},
50 {0, subpathname, AT_REMOVEDIR, 0},
51 };
52
run(unsigned int i)53 static void run(unsigned int i)
54 {
55 /* tesfile2 will be unlinked by test0. */
56 if (access(testfile2, F_OK))
57 SAFE_FILE_PRINTF(testfile2, testfile2);
58
59 /* testfile3 will be unlined by test1. */
60 if (access(testfile3, F_OK))
61 SAFE_OPEN(testfile3, O_CREAT | O_RDWR, 0600);
62
63 /* subpathdir will be unlinked by test6. */
64 if (access(subpathdir, F_OK))
65 SAFE_MKDIR(subpathdir, 0700);
66
67 /* testfile must exist except test1 and test6. */
68 if (access(testfile, F_OK))
69 SAFE_FILE_PRINTF(testfile, testfile);
70
71 if (tc[i].fd)
72 TEST(unlinkat(tc[i].fd, tc[i].filename, tc[i].flag));
73 else
74 TEST(unlinkat(getfd(i), tc[i].filename, tc[i].flag));
75
76 if (TST_ERR == tc[i].exp_errno)
77 tst_res(TPASS | TTERRNO, "unlinkat() returned expected errno");
78 else
79 tst_res(TFAIL | TTERRNO, "unlinkat() failed");
80
81 if (!tc[i].fd)
82 SAFE_CLOSE(fd);
83 }
84
setup(void)85 static void setup(void)
86 {
87 char buf[PATH_MAX];
88 SAFE_GETCWD(buf, PATH_MAX);
89 SAFE_ASPRINTF(&testfile3, "%s/unlinkatfile3.txt", buf);
90 tc[1].filename = testfile3;
91
92 SAFE_MKDIR(pathname, 0700);
93 }
94
cleanup(void)95 static void cleanup(void)
96 {
97 SAFE_UNLINK(testfile);
98 SAFE_UNLINK(testfile2);
99 SAFE_RMDIR(pathname);
100 }
101
102 static struct tst_test test = {
103 .needs_tmpdir = 1,
104 .tcnt = ARRAY_SIZE(tc),
105 .min_kver = "2.6.16",
106 .setup = setup,
107 .test = run,
108 .cleanup = cleanup,
109 };
110