1 /* xreadlink.c -- readlink wrapper to return the link name in malloc'd storage
3 Copyright (C) 2001, 2003-2007 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 2, or (at your option)
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; see the file COPYING.
17 If not, write to the Free Software Foundation,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* Written by Jim Meyering <jim@meyering.net>
21 and Bruno Haible <bruno@clisp.org>. */
26 #include "xreadlink.h"
32 #include <sys/types.h>
37 # define SIZE_MAX ((size_t) -1)
40 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
44 # define xmalloc malloc
49 /* Call readlink to get the symbolic link value of FILENAME.
50 Return a pointer to that NUL-terminated string in malloc'd storage.
51 If readlink fails, return NULL (caller may use errno to diagnose).
52 If realloc fails, or if the link value is longer than SIZE_MAX :-),
53 give a diagnostic and exit. */
56 xreadlink (char const *filename)
58 /* The initial buffer size for the link value. A power of 2
59 detects arithmetic overflow earlier, but is not required. */
60 #define INITIAL_BUF_SIZE 1024
62 /* Allocate the initial buffer on the stack. This way, in the common
63 case of a symlink of small size, we get away with a single small malloc()
64 instead of a big malloc() followed by a shrinking realloc(). */
65 char initial_buf[INITIAL_BUF_SIZE];
67 char *buffer = initial_buf;
68 size_t buf_size = sizeof (initial_buf);
72 /* Attempt to read the link into the current buffer. */
73 ssize_t link_length = readlink (filename, buffer, buf_size);
75 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
76 with errno == ERANGE if the buffer is too small. */
77 if (link_length < 0 && errno != ERANGE)
79 if (buffer != initial_buf)
81 int saved_errno = errno;
88 if ((size_t) link_length < buf_size)
90 buffer[link_length++] = '\0';
92 /* Return it in a chunk of memory as small as possible. */
93 if (buffer == initial_buf)
95 buffer = (char *) xmalloc (link_length);
100 memcpy (buffer, initial_buf, link_length);
104 /* Shrink buffer before returning it. */
105 if ((size_t) link_length < buf_size)
107 char *smaller_buffer = (char *) realloc (buffer, link_length);
109 if (smaller_buffer != NULL)
110 buffer = smaller_buffer;
116 if (buffer != initial_buf)
119 if (SSIZE_MAX < buf_size || (SIZE_MAX / 2 < SSIZE_MAX && buf_size == 0))
125 buffer = (char *) xmalloc (buf_size);