1 /* Read the contents of a symbolic link.
2 Copyright (C) 2003-2007, 2009-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file 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 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
28 /* readlink() substitute for systems that don't have a readlink() function,
29 such as DJGPP 2.03 and mingw32. */
32 readlink (char const *file
, _GL_UNUSED
char *buf
,
33 _GL_UNUSED
size_t bufsize
)
37 /* In general we should use lstat() here, not stat(). But on platforms
38 without symbolic links, lstat() - if it exists - would be equivalent to
39 stat(), therefore we can use stat(). This saves us a configure check. */
40 if (stat (file
, &statbuf
) >= 0)
45 #else /* HAVE_READLINK */
49 /* readlink() wrapper that uses correct types, for systems like cygwin
50 1.5.x where readlink returns int, and which rejects trailing slash,
54 rpl_readlink (char const *file
, char *buf
, size_t bufsize
)
56 # if READLINK_TRAILING_SLASH_BUG
57 size_t file_len
= strlen (file
);
58 if (file_len
&& file
[file_len
- 1] == '/')
60 /* Even if FILE without the slash is a symlink to a directory,
61 both lstat() and stat() must resolve the trailing slash to
62 the directory rather than the symlink. We can therefore
63 safely use stat() to distinguish between EINVAL and
64 ENOTDIR/ENOENT, avoiding extra overhead of rpl_lstat(). */
66 if (stat (file
, &st
) == 0 || errno
== EOVERFLOW
)
70 # endif /* READLINK_TRAILING_SLASH_BUG */
72 ssize_t r
= readlink (file
, buf
, bufsize
);
74 # if READLINK_TRUNCATE_BUG
75 if (r
< 0 && errno
== ERANGE
)
77 /* Try again with a bigger buffer. This is just for test cases;
78 real code invariably discards short reads. */
80 r
= readlink (file
, stackbuf
, sizeof stackbuf
);
85 /* Clear the buffer, which is good enough for real code.
86 Thankfully, no test cases try short reads of enormous
87 symlinks and what would be the point anyway? */
96 memcpy (buf
, stackbuf
, r
);
101 # if defined __CYGWIN__
102 /* On Cygwin 3.3.6, readlink("/dev/null") returns "\\Device\\Null", which
103 is unusable. Better fail with EINVAL. */
104 if (r
> 0 && strncmp (file
, "/dev/", 5) == 0 && buf
[0] == '\\')
114 #endif /* HAVE_READLINK */