New getcwd module, imported from coreutils.
[gnulib.git] / lib / getcwd.c
1 /* Provide a replacement for the POSIX getcwd function.
2    Copyright (C) 2003, 2004 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <sys/types.h>
26
27 #include "pathmax.h"
28 #include "same.h"
29
30 /* Guess high, because that makes the test below more conservative.
31    But this is a kludge, because we should really use
32    pathconf (".", _PC_NAME_MAX).  But it's probably not worth the cost.  */
33 #define KLUDGE_POSIX_NAME_MAX 255
34
35 #define MAX_SAFE_LEN (PATH_MAX - 1 - KLUDGE_POSIX_NAME_MAX - 1)
36
37 /* Undefine getcwd here, as near the use as possible, in case any
38    of the files included above define it to rpl_getcwd.  */
39 #undef getcwd
40
41 /* Any declaration of getcwd from headers included above has
42    been changed to a declaration of rpl_getcwd.  Declare it here.  */
43 extern char *getcwd (char *buf, size_t size);
44
45 /* This is a wrapper for getcwd.
46    Some implementations (at least GNU libc 2.3.1 + linux-2.4.20) return
47    non-NULL for a working directory name longer than PATH_MAX, yet the
48    returned string is a strict prefix of the desired directory name.
49    Upon such a failure, free the offending string, set errno to
50    ENAMETOOLONG, and return NULL.
51
52    I've heard that this is a Linux kernel bug, and that it has
53    been fixed between 2.4.21-pre3 and 2.4.21-pre4.  */
54
55 char *
56 rpl_getcwd (char *buf, size_t size)
57 {
58   char *cwd = getcwd (buf, size);
59
60   if (cwd == NULL)
61     return NULL;
62
63   if (strlen (cwd) <= MAX_SAFE_LEN || same_name (cwd, "."))
64     return cwd;
65
66   free (cwd);
67   errno = ENAMETOOLONG;
68   return NULL;
69 }