1 /* Work around unlinkat bugs on Solaris 9 and Hurd.
3 Copyright (C) 2009-2024 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Written by Eric Blake. */
38 /* unlinkat without AT_REMOVEDIR does not honor trailing / on Solaris 9.
39 Hurd has the same issue.
41 unlinkat without AT_REMOVEDIR erroneously ignores ".." on Darwin 14.
43 Solve these in a similar manner to unlink. */
46 rpl_unlinkat (int fd
, char const *name
, int flag
)
50 /* rmdir behavior has no problems with trailing slash. */
51 if (flag
& AT_REMOVEDIR
)
52 return unlinkat (fd
, name
, flag
);
55 if (len
&& ISSLASH (name
[len
- 1]))
57 /* See the lengthy comment in unlink.c why we disobey the POSIX
58 rule of letting unlink("link-to-dir/") attempt to unlink a
61 result
= fstatat (fd
, name
, &st
, AT_SYMLINK_NOFOLLOW
);
62 if (result
== 0 || errno
== EOVERFLOW
)
64 /* Trailing NUL will overwrite the trailing slash. */
65 char *short_name
= malloc (len
);
71 memcpy (short_name
, name
, len
);
72 while (len
&& ISSLASH (short_name
[len
- 1]))
73 short_name
[--len
] = '\0';
74 if (len
&& (fstatat (fd
, short_name
, &st
, AT_SYMLINK_NOFOLLOW
)
75 || S_ISLNK (st
.st_mode
)))
87 # if UNLINK_PARENT_BUG
88 if (len
>= 2 && name
[len
- 1] == '.' && name
[len
- 2] == '.'
89 && (len
== 2 || ISSLASH (name
[len
- 3])))
91 errno
= EISDIR
; /* could also use EPERM */
95 result
= unlinkat (fd
, name
, flag
);
100 #else /* !HAVE_UNLINKAT */
102 /* Replacement for Solaris' function by the same name.
103 <https://www.google.com/search?q=unlinkat+site:docs.oracle.com>
104 First, try to simulate it via (unlink|rmdir) ("/proc/self/fd/FD/FILE").
105 Failing that, simulate it via save_cwd/fchdir/(unlink|rmdir)/restore_cwd.
106 If either the save_cwd or the restore_cwd fails (relatively unlikely),
107 then give a diagnostic and exit nonzero.
108 Otherwise, this function works just like Solaris' unlinkat. */
110 # define AT_FUNC_NAME unlinkat
111 # define AT_FUNC_F1 rmdir
112 # define AT_FUNC_F2 unlink
113 # define AT_FUNC_USE_F1_COND AT_REMOVEDIR
114 # define AT_FUNC_POST_FILE_PARAM_DECLS , int flag
115 # define AT_FUNC_POST_FILE_ARGS /* empty */
116 # include "at-func.c"
120 # undef AT_FUNC_USE_F1_COND
121 # undef AT_FUNC_POST_FILE_PARAM_DECLS
122 # undef AT_FUNC_POST_FILE_ARGS
124 #endif /* !HAVE_UNLINKAT */