1 //===--- A platform independent Dir class ---------------------------------===// 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 #ifndef LLVM_LIBC_SRC_SUPPORT_FILE_DIR_H 10 #define LLVM_LIBC_SRC_SUPPORT_FILE_DIR_H 11 12 #include "src/__support/CPP/ArrayRef.h" 13 #include "src/__support/threads/mutex.h" 14 15 #include <dirent.h> 16 #include <stdlib.h> 17 18 namespace __llvm_libc { 19 20 // Platform specific function which will open the directory |name| 21 // and return its file descriptor. Upon failure, this function sets the errno 22 // value as suitable. 23 int platform_opendir(const char *name); 24 25 // Platform specific function which will close the directory with 26 // file descriptor |fd|. Returns true on success, false on failure. 27 bool platform_closedir(int fd); 28 29 // Platform specific function which will fetch dirents in to buffer. 30 // Returns the number of bytes written into buffer 31 size_t platform_fetch_dirents(int fd, cpp::MutableArrayRef<uint8_t> buffer); 32 33 // This class is designed to allow implementation of the POSIX dirent.h API. 34 // By itself, it is platform independent but calls platform specific 35 // functions to perform OS operations. 36 class Dir { 37 static constexpr size_t BUFSIZE = 1024; 38 int fd; 39 size_t readptr = 0; // The current read pointer. 40 size_t fillsize = 0; // The number of valid bytes availabe in the buffer. 41 42 // This is a buffer of struct dirent values which will be fetched 43 // from the OS. Since the d_name of struct dirent can be of a variable 44 // size, we store the data in a byte array. 45 uint8_t buffer[BUFSIZE]; 46 47 Mutex mutex; 48 49 public: 50 // A directory is to be opened by the static method open and closed 51 // by the close method. So, all constructors and destructor are declared 52 // as deleted. 53 Dir() = delete; 54 Dir(const Dir &) = delete; 55 ~Dir() = delete; 56 57 Dir &operator=(const Dir &) = delete; 58 59 static Dir *open(const char *path); 60 61 struct ::dirent *read(); 62 63 int close(); 64 getfd()65 int getfd() { return fd; } 66 }; 67 68 } // namespace __llvm_libc 69 70 #endif // LLVM_LIBC_SRC_SUPPORT_FILE_DIR_H 71