Merge from coreutils CVS.
[gnulib.git] / lib / xreadlink.c
1 /* xreadlink.c -- readlink wrapper to return the link name in malloc'd storage
2
3    Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc.
4
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)
8    any later version.
9
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.
14
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    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* Written by Jim Meyering <jim@meyering.net>  */
21
22 #if HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include "xreadlink.h"
27
28 #include <stdio.h>
29 #include <errno.h>
30 #ifndef errno
31 extern int errno;
32 #endif
33
34 #include <limits.h>
35 #include <sys/types.h>
36 #include <stdlib.h>
37 #if HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40
41 #ifndef SIZE_MAX
42 # define SIZE_MAX ((size_t) -1)
43 #endif
44 #ifndef SSIZE_MAX
45 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
46 #endif
47
48 #include "xalloc.h"
49
50 /* Call readlink to get the symbolic link value of FILENAME.
51    SIZE is a hint as to how long the link is expected to be;
52    typically it is taken from st_size.  It need not be correct.
53    Return a pointer to that NUL-terminated string in malloc'd storage.
54    If readlink fails, return NULL (caller may use errno to diagnose).
55    If malloc fails, or if the link value is longer than SSIZE_MAX :-),
56    give a diagnostic and exit.  */
57
58 char *
59 xreadlink (char const *filename, size_t size)
60 {
61   /* The initial buffer size for the link value.  A power of 2
62      detects arithmetic overflow earlier, but is not required.  */
63   size_t buf_size = size + 1;
64
65   while (1)
66     {
67       char *buffer = xmalloc (buf_size);
68       ssize_t link_length = readlink (filename, buffer, buf_size);
69
70       if (link_length < 0)
71         {
72           int saved_errno = errno;
73           free (buffer);
74           errno = saved_errno;
75           return NULL;
76         }
77
78       if ((size_t) link_length < buf_size)
79         {
80           buffer[link_length] = 0;
81           return buffer;
82         }
83
84       free (buffer);
85       buf_size *= 2;
86       if (! (0 < buf_size && buf_size <= SSIZE_MAX))
87         xalloc_die ();
88     }
89 }