Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / src / unistd / linux / getcwd.cpp
blob11c58f1585564d912b8043e3b4ec3cd588542bb8
1 //===-- Linux implementation of getcwd ------------------------------------===//
2 //
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
6 //
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.
17 #include <stdlib.h>
18 #include <sys/syscall.h> // For syscall numbers.
20 namespace LIBC_NAMESPACE {
22 namespace {
24 bool getcwd_syscall(char *buf, size_t size) {
25 int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_getcwd, buf, size);
26 if (ret < 0) {
27 libc_errno = -ret;
28 return false;
29 } else if (ret == 0 || buf[0] != '/') {
30 libc_errno = ENOENT;
31 return false;
33 return true;
36 } // anonymous namespace
38 LLVM_LIBC_FUNCTION(char *, getcwd, (char *buf, size_t size)) {
39 if (buf == nullptr) {
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
43 // and free.
44 char pathbuf[PATH_MAX];
45 if (!getcwd_syscall(pathbuf, PATH_MAX))
46 return nullptr;
47 auto cwd = internal::strdup(pathbuf);
48 if (!cwd) {
49 libc_errno = ENOMEM;
50 return nullptr;
52 return *cwd;
53 } else if (size == 0) {
54 libc_errno = EINVAL;
55 return nullptr;
58 // TODO: When buf is not sufficient, evaluate the full cwd path using
59 // alternate approaches.
61 if (!getcwd_syscall(buf, size))
62 return nullptr;
63 return buf;
66 } // namespace LIBC_NAMESPACE