(expr invocation):
[coreutils.git] / lib / getcwd.c
blob2968a6e98023d79177028330c388d2b77489da80
1 /* Provide a replacement for the POSIX getcwd function.
2 Copyright (C) 2003 Free Software Foundation, Inc.
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.
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.
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. */
18 /* written by Jim Meyering */
20 #include <config.h>
22 #include <stdlib.h>
23 #include <string.h>
25 #include <errno.h>
26 #ifndef errno
27 extern int errno;
28 #endif
30 #include <sys/types.h>
32 #include "pathmax.h"
33 #include "same.h"
35 /* Guess high, because that makes the test below more conservative.
36 But this is a kludge, because we should really use
37 pathconf (".", _PC_NAME_MAX). But it's probably not worth the cost. */
38 #define KLUDGE_POSIX_NAME_MAX 255
40 #define MAX_SAFE_LEN (PATH_MAX - 1 - KLUDGE_POSIX_NAME_MAX - 1)
42 /* Undefine getcwd here, as near the use as possible, in case any
43 of the files included above define it to rpl_getcwd. */
44 #undef getcwd
46 /* Any declaration of getcwd from headers included above has
47 been changed to a declaration of rpl_getcwd. Declare it here. */
48 extern char *getcwd (char *buf, size_t size);
50 /* This is a wrapper for getcwd.
51 Some implementations (at least GNU libc 2.3.1 + linux-2.4.20) return
52 non-NULL for a working directory name longer than PATH_MAX, yet the
53 returned string is a strict prefix of the desired directory name.
54 Upon such a failure, free the offending string, set errno to
55 ENAMETOOLONG, and return NULL.
57 I've heard that this is a Linux kernel bug, and that it has
58 been fixed between 2.4.21-pre3 and 2.4.21-pre4. */
60 char *
61 rpl_getcwd (char *buf, size_t size)
63 char *cwd = getcwd (buf, size);
65 if (cwd == NULL)
66 return NULL;
68 if (strlen (cwd) <= MAX_SAFE_LEN || same_name (cwd, "."))
69 return cwd;
71 free (cwd);
72 errno = ENAMETOOLONG;
73 return NULL;