dirent.cpp 8.0 KB

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