timespec_get: New module.
[gnulib.git] / lib / symlinkat.c
blob404fa653311d633fdaf3411ea2776c02d3dd5298
1 /* Create a symlink relative to an open directory.
2 Copyright (C) 2009-2021 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* written by Eric Blake */
19 #include <config.h>
21 /* Specification. */
22 #include <unistd.h>
24 #include <errno.h>
25 #include <stdlib.h>
27 #if HAVE_SYMLINKAT
28 # undef symlinkat
30 #include <sys/stat.h>
31 #include <string.h>
33 /* Create a symlink, but reject trailing slash. */
34 int
35 rpl_symlinkat (char const *contents, int fd, char const *name)
37 size_t len = strlen (name);
38 if (len && name[len - 1] == '/')
40 struct stat st;
41 if (fstatat (fd, name, &st, 0) == 0 || errno == EOVERFLOW)
42 errno = EEXIST;
43 return -1;
45 return symlinkat (contents, fd, name);
48 #elif !HAVE_SYMLINK
49 /* Mingw lacks symlink, and it is more efficient to provide a trivial
50 wrapper than to go through at-func.c to call rpl_symlink. */
52 int
53 symlinkat (char const *path1 _GL_UNUSED, int fd _GL_UNUSED,
54 char const *path2 _GL_UNUSED)
56 errno = ENOSYS;
57 return -1;
60 #else /* HAVE_SYMLINK */
62 /* Our openat helper functions expect the directory parameter first,
63 not second. These shims make life easier. */
65 /* Like symlink, but with arguments reversed. */
66 static int
67 symlink_reversed (char const *file, char const *contents)
69 return symlink (contents, file);
72 /* Like symlinkat, but with arguments reversed. */
74 static int
75 symlinkat_reversed (int fd, char const *file, char const *contents);
77 # define AT_FUNC_NAME symlinkat_reversed
78 # define AT_FUNC_F1 symlink_reversed
79 # define AT_FUNC_POST_FILE_PARAM_DECLS , char const *contents
80 # define AT_FUNC_POST_FILE_ARGS , contents
81 # include "at-func.c"
82 # undef AT_FUNC_NAME
83 # undef AT_FUNC_F1
84 # undef AT_FUNC_POST_FILE_PARAM_DECLS
85 # undef AT_FUNC_POST_FILE_ARGS
87 /* Create a symlink FILE, in the directory open on descriptor FD,
88 holding CONTENTS. If possible, do it without changing the
89 working directory. Otherwise, resort to using save_cwd/fchdir,
90 then symlink/restore_cwd. If either the save_cwd or the restore_cwd
91 fails, then give a diagnostic and exit nonzero. */
93 int
94 symlinkat (char const *contents, int fd, char const *file)
96 return symlinkat_reversed (fd, file, contents);
99 #endif /* HAVE_SYMLINK */