in lib:
[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 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 <stdio.h>
27 #include <errno.h>
28 #ifndef errno
29 extern int errno;
30 #endif
31
32 #include <limits.h>
33 #if HAVE_SYS_TYPES_H
34 # include <sys/types.h>
35 #endif
36 #if HAVE_STDLIB_H
37 # include <stdlib.h>
38 #endif
39 #if HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42
43 #ifndef SIZE_MAX
44 # define SIZE_MAX ((size_t) -1)
45 #endif
46 #ifndef SSIZE_MAX
47 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
48 #endif
49
50 #include "xalloc.h"
51 #include "xreadlink.h"
52
53 /* Call readlink to get the symbolic link value of FILENAME.
54    Return a pointer to that NUL-terminated string in malloc'd storage.
55    If readlink fails, return NULL (caller may use errno to diagnose).
56    If realloc fails, or if the link value is longer than SIZE_MAX :-),
57    give a diagnostic and exit.  */
58
59 char *
60 xreadlink (char const *filename)
61 {
62   /* The initial buffer size for the link value.  A power of 2
63      detects arithmetic overflow earlier, but is not required.  */
64   size_t buf_size = 128;
65
66   while (1)
67     {
68       char *buffer = xmalloc (buf_size);
69       ssize_t link_length = readlink (filename, buffer, buf_size);
70
71       if (link_length < 0)
72         {
73           int saved_errno = errno;
74           free (buffer);
75           errno = saved_errno;
76           return NULL;
77         }
78
79       if ((size_t) link_length < buf_size)
80         {
81           buffer[link_length] = 0;
82           return buffer;
83         }
84
85       free (buffer);
86       buf_size *= 2;
87       if (SSIZE_MAX < buf_size || (SIZE_MAX / 2 < SSIZE_MAX && buf_size == 0))
88         xalloc_die ();
89     }
90 }