1 /* Provide a replacement for the POSIX getcwd function.
2 Copyright (C) 2003, 2004 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)
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 */
25 #include <sys/types.h>
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
35 #define MAX_SAFE_LEN (PATH_MAX - 1 - KLUDGE_POSIX_NAME_MAX - 1)
37 /* Undefine getcwd here, as near the use as possible, in case any
38 of the files included above define it to rpl_getcwd. */
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);
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.
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. */
56 rpl_getcwd (char *buf, size_t size)
58 char *cwd = getcwd (buf, size);
63 if (strlen (cwd) <= MAX_SAFE_LEN || same_name (cwd, "."))