dirent.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/StdLibExtras.h>
  9. #include <AK/Vector.h>
  10. #include <dirent.h>
  11. #include <errno.h>
  12. #include <fcntl.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <sys/stat.h>
  17. #include <syscall.h>
  18. #include <unistd.h>
  19. extern "C" {
  20. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/opendir.html
  21. DIR* opendir(char const* name)
  22. {
  23. int fd = open(name, O_RDONLY | O_DIRECTORY);
  24. if (fd == -1)
  25. return nullptr;
  26. return fdopendir(fd);
  27. }
  28. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdopendir.html
  29. DIR* fdopendir(int fd)
  30. {
  31. if (fd == -1)
  32. return nullptr;
  33. DIR* dirp = (DIR*)malloc(sizeof(DIR));
  34. dirp->fd = fd;
  35. dirp->buffer = nullptr;
  36. dirp->buffer_size = 0;
  37. dirp->nextptr = nullptr;
  38. return dirp;
  39. }
  40. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/closedir.html
  41. int closedir(DIR* dirp)
  42. {
  43. if (!dirp || dirp->fd == -1)
  44. return -EBADF;
  45. free(dirp->buffer);
  46. int rc = close(dirp->fd);
  47. if (rc == 0)
  48. dirp->fd = -1;
  49. free(dirp);
  50. return rc;
  51. }
  52. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rewinddir.html
  53. void rewinddir(DIR* dirp)
  54. {
  55. free(dirp->buffer);
  56. dirp->buffer = nullptr;
  57. dirp->buffer_size = 0;
  58. dirp->nextptr = nullptr;
  59. lseek(dirp->fd, 0, SEEK_SET);
  60. }
  61. struct [[gnu::packed]] sys_dirent {
  62. ino_t ino;
  63. u8 file_type;
  64. u32 namelen;
  65. char name[];
  66. size_t total_size()
  67. {
  68. return sizeof(ino_t) + sizeof(u8) + sizeof(u32) + sizeof(char) * namelen;
  69. }
  70. };
  71. static void create_struct_dirent(sys_dirent* sys_ent, struct dirent* str_ent)
  72. {
  73. str_ent->d_ino = sys_ent->ino;
  74. str_ent->d_type = sys_ent->file_type;
  75. str_ent->d_off = 0;
  76. str_ent->d_reclen = sizeof(struct dirent);
  77. VERIFY(sizeof(str_ent->d_name) > sys_ent->namelen);
  78. // Note: We can't use any normal string function as sys_ent->name is
  79. // not null terminated. All string copy functions will attempt to read
  80. // the non-existent null terminator past the end of the source string.
  81. memcpy(str_ent->d_name, sys_ent->name, sys_ent->namelen);
  82. str_ent->d_name[sys_ent->namelen] = '\0';
  83. }
  84. static int allocate_dirp_buffer(DIR* dirp)
  85. {
  86. if (dirp->buffer) {
  87. return 0;
  88. }
  89. struct stat st;
  90. // preserve errno since this could be a reentrant call
  91. int old_errno = errno;
  92. int rc = fstat(dirp->fd, &st);
  93. if (rc < 0) {
  94. int new_errno = errno;
  95. errno = old_errno;
  96. return new_errno;
  97. }
  98. size_t size_to_allocate = max(st.st_size, static_cast<off_t>(4096));
  99. dirp->buffer = (char*)malloc(size_to_allocate);
  100. if (!dirp->buffer)
  101. return ENOMEM;
  102. for (;;) {
  103. ssize_t nread = syscall(SC_get_dir_entries, dirp->fd, dirp->buffer, size_to_allocate);
  104. if (nread < 0) {
  105. if (nread == -EINVAL) {
  106. size_to_allocate *= 2;
  107. char* new_buffer = (char*)realloc(dirp->buffer, size_to_allocate);
  108. if (new_buffer) {
  109. dirp->buffer = new_buffer;
  110. continue;
  111. } else {
  112. nread = -ENOMEM;
  113. }
  114. }
  115. // uh-oh, the syscall returned an error
  116. free(dirp->buffer);
  117. dirp->buffer = nullptr;
  118. return -nread;
  119. }
  120. dirp->buffer_size = nread;
  121. dirp->nextptr = dirp->buffer;
  122. break;
  123. }
  124. return 0;
  125. }
  126. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html
  127. dirent* readdir(DIR* dirp)
  128. {
  129. if (!dirp)
  130. return nullptr;
  131. if (dirp->fd == -1)
  132. return nullptr;
  133. if (int new_errno = allocate_dirp_buffer(dirp)) {
  134. // readdir is allowed to mutate errno
  135. errno = new_errno;
  136. return nullptr;
  137. }
  138. if (dirp->nextptr >= (dirp->buffer + dirp->buffer_size))
  139. return nullptr;
  140. auto* sys_ent = (sys_dirent*)dirp->nextptr;
  141. create_struct_dirent(sys_ent, &dirp->cur_ent);
  142. dirp->nextptr += sys_ent->total_size();
  143. return &dirp->cur_ent;
  144. }
  145. static bool compare_sys_struct_dirent(sys_dirent* sys_ent, struct dirent* str_ent)
  146. {
  147. size_t namelen = min((size_t)256, sys_ent->namelen);
  148. // These fields are guaranteed by create_struct_dirent to be the same
  149. return sys_ent->ino == str_ent->d_ino
  150. && sys_ent->file_type == str_ent->d_type
  151. && sys_ent->total_size() == str_ent->d_reclen
  152. && strncmp(sys_ent->name, str_ent->d_name, namelen) == 0;
  153. }
  154. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir_r.html
  155. int readdir_r(DIR* dirp, struct dirent* entry, struct dirent** result)
  156. {
  157. if (!dirp || dirp->fd == -1) {
  158. *result = nullptr;
  159. return EBADF;
  160. }
  161. if (int new_errno = allocate_dirp_buffer(dirp)) {
  162. *result = nullptr;
  163. return new_errno;
  164. }
  165. // This doesn't care about dirp state; seek until we find the entry.
  166. // Unfortunately, we can't just compare struct dirent to sys_dirent, so
  167. // manually compare the fields. This seems a bit risky, but could work.
  168. auto* buffer = dirp->buffer;
  169. auto* sys_ent = (sys_dirent*)buffer;
  170. bool found = false;
  171. while (!(found || buffer >= dirp->buffer + dirp->buffer_size)) {
  172. found = compare_sys_struct_dirent(sys_ent, entry);
  173. // Make sure if we found one, it's the one after (end of buffer or not)
  174. buffer += sys_ent->total_size();
  175. sys_ent = (sys_dirent*)buffer;
  176. }
  177. // If we found one, but hit end of buffer, then EOD
  178. if (found && buffer >= dirp->buffer + dirp->buffer_size) {
  179. *result = nullptr;
  180. return 0;
  181. }
  182. // If we never found a match for entry in buffer, start from the beginning
  183. else if (!found) {
  184. buffer = dirp->buffer;
  185. sys_ent = (sys_dirent*)buffer;
  186. }
  187. *result = entry;
  188. create_struct_dirent(sys_ent, entry);
  189. return 0;
  190. }
  191. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/dirfd.html
  192. int dirfd(DIR* dirp)
  193. {
  194. VERIFY(dirp);
  195. return dirp->fd;
  196. }
  197. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/alphasort.html
  198. int alphasort(const struct dirent** d1, const struct dirent** d2)
  199. {
  200. return strcoll((*d1)->d_name, (*d2)->d_name);
  201. }
  202. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html
  203. int scandir(char const* dir_name,
  204. struct dirent*** namelist,
  205. int (*select)(const struct dirent*),
  206. int (*compare)(const struct dirent**, const struct dirent**))
  207. {
  208. auto dir = opendir(dir_name);
  209. if (dir == nullptr)
  210. return -1;
  211. ScopeGuard guard = [&] {
  212. closedir(dir);
  213. };
  214. Vector<struct dirent*> tmp_names;
  215. ScopeGuard names_guard = [&] {
  216. tmp_names.remove_all_matching([&](auto& entry) {
  217. free(entry);
  218. return true;
  219. });
  220. };
  221. while (true) {
  222. errno = 0;
  223. auto entry = readdir(dir);
  224. if (!entry)
  225. break;
  226. // Omit entries the caller chooses to ignore.
  227. if (select && !select(entry))
  228. continue;
  229. auto entry_copy = (struct dirent*)malloc(entry->d_reclen);
  230. if (!entry_copy)
  231. break;
  232. memcpy(entry_copy, entry, entry->d_reclen);
  233. tmp_names.append(entry_copy);
  234. }
  235. // Propagate any errors encountered while accumulating back to the user.
  236. if (errno) {
  237. return -1;
  238. }
  239. // Sort the entries if the user provided a comparator.
  240. if (compare) {
  241. qsort(tmp_names.data(), tmp_names.size(), sizeof(struct dirent*), (int (*)(void const*, void const*))compare);
  242. }
  243. int const size = tmp_names.size();
  244. auto** names = static_cast<struct dirent**>(kmalloc_array(size, sizeof(struct dirent*)));
  245. if (names == nullptr) {
  246. return -1;
  247. }
  248. for (auto i = 0; i < size; i++) {
  249. names[i] = tmp_names[i];
  250. }
  251. // Disable the scope guard which free's names on error.
  252. tmp_names.clear();
  253. *namelist = names;
  254. return size;
  255. }
  256. }