1 /* xreadlink.c -- readlink wrapper to return the link name in malloc'd storage
3 Copyright (C) 2001, 2003, 2004, 2005, 2006 Free Software
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; see the file COPYING.
18 If not, write to the Free Software Foundation,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
21 /* Written by Jim Meyering <jim@meyering.net> */
25 #include "xreadlink.h"
30 #include <sys/types.h>
35 # define SIZE_MAX ((size_t) -1)
38 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
41 /* SYMLINK_MAX is used only for an initial memory-allocation sanity
42 check, so it's OK to guess too small on hosts where there is no
43 arbitrary limit to symbolic link length. */
45 # define SYMLINK_MAX 1024
48 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
52 /* Call readlink to get the symbolic link value of FILE.
53 SIZE is a hint as to how long the link is expected to be;
54 typically it is taken from st_size. It need not be correct.
55 Return a pointer to that NUL-terminated string in malloc'd storage.
56 If readlink fails, return NULL (caller may use errno to diagnose).
57 If malloc fails, or if the link value is longer than SSIZE_MAX :-),
58 give a diagnostic and exit. */
61 xreadlink (char const *file
, size_t size
)
63 /* Some buggy file systems report garbage in st_size. Defend
64 against them by ignoring outlandish st_size values in the initial
66 size_t symlink_max
= SYMLINK_MAX
;
67 size_t INITIAL_LIMIT_BOUND
= 8 * 1024;
68 size_t initial_limit
= (symlink_max
< INITIAL_LIMIT_BOUND
70 : INITIAL_LIMIT_BOUND
);
72 /* The initial buffer size for the link value. */
73 size_t buf_size
= size
< initial_limit
? size
+ 1 : initial_limit
;
77 char *buffer
= xmalloc (buf_size
);
78 ssize_t r
= readlink (file
, buffer
, buf_size
);
79 size_t link_length
= r
;
81 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
82 with errno == ERANGE if the buffer is too small. */
83 if (r
< 0 && errno
!= ERANGE
)
85 int saved_errno
= errno
;
91 if (link_length
< buf_size
)
93 buffer
[link_length
] = 0;
98 if (buf_size
<= MAXSIZE
/ 2)
100 else if (buf_size
< MAXSIZE
)