]>
git.ipfire.org Git - thirdparty/glibc.git/blob - sysdeps/unix/sysv/linux/getcwd.c
1 /* Determine current working directory. Linux version.
2 Copyright (C) 1997-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
25 #include <sys/param.h>
28 #include <sys/syscall.h>
31 /* If we compile the file for use in ld.so we don't need the feature
32 that getcwd() allocates the buffers itself. */
34 # define NO_ALLOCATION 1
38 /* The "proc" filesystem provides an easy method to retrieve the value.
39 For each process, the corresponding directory contains a symbolic link
40 named `cwd'. Reading the content of this link immediate gives us the
41 information. But we have to take care for systems which do not have
42 the proc filesystem mounted. Use the POSIX implementation in this case. */
44 /* Get the code for the generic version. */
45 #define GETCWD_RETURN_TYPE static char *
46 #include <sysdeps/posix/getcwd.c>
49 __getcwd (char *buf
, size_t size
)
55 size_t alloc_size
= size
;
64 alloc_size
= MAX (PATH_MAX
, __getpagesize ());
69 path
= malloc (alloc_size
);
75 # define alloc_size size
81 retval
= INLINE_SYSCALL (getcwd
, 2, path
, alloc_size
);
82 if (retval
> 0 && path
[0] == '/')
85 if (buf
== NULL
&& size
== 0)
86 /* Ensure that the buffer is only as large as necessary. */
87 buf
= realloc (path
, (size_t) retval
);
90 /* Either buf was NULL all along, or `realloc' failed but
91 we still have the original string. */
98 /* The system call either cannot handle paths longer than a page
99 or can succeed without returning an absolute path. Just use the
100 generic implementation right away. */
101 if (retval
>= 0 || errno
== ENAMETOOLONG
)
103 #ifndef NO_ALLOCATION
104 if (buf
== NULL
&& size
== 0)
111 result
= __getcwd_generic (path
, size
);
113 #ifndef NO_ALLOCATION
114 if (result
== NULL
&& buf
== NULL
&& size
!= 0)
121 /* It should never happen that the `getcwd' syscall failed because
122 the buffer is too small if we allocated the buffer ourselves
124 assert (errno
!= ERANGE
|| buf
!= NULL
|| size
!= 0);
126 #ifndef NO_ALLOCATION
133 libc_hidden_def (__getcwd
)
134 weak_alias (__getcwd
, getcwd
)