summaryrefslogtreecommitdiff
path: root/libc/src/__support/File/linux_dir.cpp
blob: 86aaaae907d22ba0a52dbf0e9c14daaa75f2e583 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//===--- Linux implementation of the Dir helpers --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "dir.h"

#include "src/__support/OSUtil/syscall.h" // For internal syscall function.
#include "src/__support/error_or.h"

#include <fcntl.h>       // For open flags
#include <sys/syscall.h> // For syscall numbers

namespace __llvm_libc {

ErrorOr<int> platform_opendir(const char *name) {
  int open_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
#ifdef SYS_open
  int fd = __llvm_libc::syscall_impl(SYS_open, name, open_flags);
#elif defined(SYS_openat)
  int fd = __llvm_libc::syscall_impl(SYS_openat, AT_FDCWD, name, open_flags);
#else
#error                                                                         \
    "SYS_open and SYS_openat syscalls not available to perform an open operation."
#endif

  if (fd < 0) {
    return __llvm_libc::Error(-fd);
  }
  return fd;
}

ErrorOr<size_t> platform_fetch_dirents(int fd, cpp::span<uint8_t> buffer) {
  long size =
      __llvm_libc::syscall_impl(SYS_getdents, fd, buffer.data(), buffer.size());
  if (size < 0) {
    return __llvm_libc::Error(static_cast<int>(-size));
  }
  return size;
}

int platform_closedir(int fd) {
  long ret = __llvm_libc::syscall_impl(SYS_close, fd);
  if (ret < 0) {
    return static_cast<int>(-ret);
  }
  return 0;
}

} // namespace __llvm_libc