1 //===--- Linux implementation of the Dir helpers --------------------------===//
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 //===----------------------------------------------------------------------===//
8 
9 #include "dir.h"
10 
11 #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12 
13 #include <errno.h>
14 #include <fcntl.h>       // For open flags
15 #include <sys/syscall.h> // For syscall numbers
16 
17 namespace __llvm_libc {
18 
19 int platform_opendir(const char *name) {
20   int open_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
21 #ifdef SYS_open
22   int fd = __llvm_libc::syscall(SYS_open, name, open_flags);
23 #elif defined(SYS_openat)
24   int fd = __llvm_libc::syscall(SYS_openat, AT_FDCWD, name, open_flags);
25 #else
26 #error                                                                         \
27     "SYS_open and SYS_openat syscalls not available to perform an open operation."
28 #endif
29 
30   if (fd < 0) {
31     errno = -fd;
32     return -1;
33   }
34   return fd;
35 }
36 
37 size_t platform_fetch_dirents(int fd, cpp::MutableArrayRef<uint8_t> buffer) {
38   long size =
39       __llvm_libc::syscall(SYS_getdents, fd, buffer.data(), buffer.size());
40   if (size < 0) {
41     errno = -size;
42     return 0;
43   }
44   return size;
45 }
46 
47 bool platform_closedir(int fd) {
48   long ret = __llvm_libc::syscall(SYS_close, fd);
49   if (ret < 0) {
50     errno = -ret;
51     return false;
52   }
53   return true;
54 }
55 
56 } // namespace __llvm_libc
57