1 //===-- Linux implementation of getcwd ------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "src/unistd/getcwd.h"
11 #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12 #include "src/__support/common.h"
13 #include "src/string/allocating_string_utils.h" // For strdup.
15 #include "src/errno/libc_errno.h"
16 #include <linux/limits.h> // This is safe to include without any name pollution.
18 #include <sys/syscall.h> // For syscall numbers.
20 namespace LIBC_NAMESPACE
{
24 bool getcwd_syscall(char *buf
, size_t size
) {
25 int ret
= LIBC_NAMESPACE::syscall_impl
<int>(SYS_getcwd
, buf
, size
);
29 } else if (ret
== 0 || buf
[0] != '/') {
36 } // anonymous namespace
38 LLVM_LIBC_FUNCTION(char *, getcwd
, (char *buf
, size_t size
)) {
40 // We match glibc's behavior here and return the cwd in a malloc-ed buffer.
41 // We will allocate a static buffer of size PATH_MAX first and fetch the cwd
42 // into it. This way, if the syscall fails, we avoid unnecessary malloc
44 char pathbuf
[PATH_MAX
];
45 if (!getcwd_syscall(pathbuf
, PATH_MAX
))
47 auto cwd
= internal::strdup(pathbuf
);
53 } else if (size
== 0) {
58 // TODO: When buf is not sufficient, evaluate the full cwd path using
59 // alternate approaches.
61 if (!getcwd_syscall(buf
, size
))
66 } // namespace LIBC_NAMESPACE