1 /* areadlink.c -- readlink wrapper to return the link name in malloc'd storage
2 Unlike xreadlink and xreadlink_with_size, don't ever call exit.
4 Copyright (C) 2001, 2003-2007 Free Software Foundation, Inc.
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>
22 and Bruno Haible <bruno@clisp.org>. */
27 #include "areadlink.h"
32 #include <sys/types.h>
37 # define SIZE_MAX ((size_t) -1)
40 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
43 /* Call readlink to get the symbolic link value of FILENAME.
44 Return a pointer to that NUL-terminated string in malloc'd storage.
45 If readlink fails, return NULL and set errno.
46 If realloc fails, or if the link value is longer than SIZE_MAX :-),
47 return NULL and set errno to ENOMEM. */
50 areadlink (char const *filename)
52 /* The initial buffer size for the link value. A power of 2
53 detects arithmetic overflow earlier, but is not required. */
54 #define INITIAL_BUF_SIZE 1024
56 /* Allocate the initial buffer on the stack. This way, in the common
57 case of a symlink of small size, we get away with a single small malloc()
58 instead of a big malloc() followed by a shrinking realloc(). */
59 char initial_buf[INITIAL_BUF_SIZE];
61 char *buffer = initial_buf;
62 size_t buf_size = sizeof (initial_buf);
66 /* Attempt to read the link into the current buffer. */
67 ssize_t link_length = readlink (filename, buffer, buf_size);
69 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
70 with errno == ERANGE if the buffer is too small. */
71 if (link_length < 0 && errno != ERANGE)
73 if (buffer != initial_buf)
75 int saved_errno = errno;
82 if ((size_t) link_length < buf_size)
84 buffer[link_length++] = '\0';
86 /* Return it in a chunk of memory as small as possible. */
87 if (buffer == initial_buf)
89 buffer = (char *) malloc (link_length);
91 /* errno is ENOMEM. */
93 memcpy (buffer, initial_buf, link_length);
97 /* Shrink buffer before returning it. */
98 if ((size_t) link_length < buf_size)
100 char *smaller_buffer = (char *) realloc (buffer, link_length);
102 if (smaller_buffer != NULL)
103 buffer = smaller_buffer;
109 if (buffer != initial_buf)
112 if (SSIZE_MAX < buf_size || (SIZE_MAX / 2 < SSIZE_MAX && buf_size == 0))
117 buffer = (char *) malloc (buf_size);
119 /* errno is ENOMEM. */