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 "src/__support/File/dir.h"
10
11#include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12#include "src/__support/error_or.h"
13
14#include <fcntl.h> // For open flags
15#include <sys/syscall.h> // For syscall numbers
16
17namespace LIBC_NAMESPACE {
18
19ErrorOr<int> platform_opendir(const char *name) {
20 int open_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
21#ifdef SYS_open
22 int fd = LIBC_NAMESPACE::syscall_impl<int>(SYS_open, ts: name, ts: open_flags);
23#elif defined(SYS_openat)
24 int fd =
25 LIBC_NAMESPACE::syscall_impl<int>(SYS_openat, AT_FDCWD, name, open_flags);
26#else
27#error \
28 "SYS_open and SYS_openat syscalls not available to perform an open operation."
29#endif
30
31 if (fd < 0) {
32 return LIBC_NAMESPACE::Error(-fd);
33 }
34 return fd;
35}
36
37ErrorOr<size_t> platform_fetch_dirents(int fd, cpp::span<uint8_t> buffer) {
38#ifdef SYS_getdents64
39 long size = LIBC_NAMESPACE::syscall_impl<long>(SYS_getdents64, ts: fd,
40 ts: buffer.data(), ts: buffer.size());
41#else
42#error "getdents64 syscalls not available to perform a fetch dirents operation."
43#endif
44
45 if (size < 0) {
46 return LIBC_NAMESPACE::Error(static_cast<int>(-size));
47 }
48 return size;
49}
50
51int platform_closedir(int fd) {
52 int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_close, ts: fd);
53 if (ret < 0) {
54 return static_cast<int>(-ret);
55 }
56 return 0;
57}
58
59} // namespace LIBC_NAMESPACE
60

source code of libc/src/__support/File/linux/dir.cpp