dirent.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* SPDX-License-Identifier: LGPL-2.1 OR MIT */
  2. /*
  3. * Directory access for NOLIBC
  4. * Copyright (C) 2025 Thomas Weißschuh <linux@weissschuh.net>
  5. */
  6. /* make sure to include all global symbols */
  7. #include "nolibc.h"
  8. #ifndef _NOLIBC_DIRENT_H
  9. #define _NOLIBC_DIRENT_H
  10. #include "compiler.h"
  11. #include "stdint.h"
  12. #include "types.h"
  13. #include "fcntl.h"
  14. #include <linux/limits.h>
  15. struct dirent {
  16. ino_t d_ino;
  17. char d_name[NAME_MAX + 1];
  18. };
  19. /* See comment of FILE in stdio.h */
  20. typedef struct {
  21. char dummy[1];
  22. } DIR;
  23. static __attribute__((unused))
  24. DIR *fdopendir(int fd)
  25. {
  26. if (fd < 0) {
  27. SET_ERRNO(EBADF);
  28. return NULL;
  29. }
  30. return (DIR *)(intptr_t)~fd;
  31. }
  32. static __attribute__((unused))
  33. DIR *opendir(const char *name)
  34. {
  35. int fd;
  36. fd = open(name, O_RDONLY);
  37. if (fd == -1)
  38. return NULL;
  39. return fdopendir(fd);
  40. }
  41. static __attribute__((unused))
  42. int closedir(DIR *dirp)
  43. {
  44. intptr_t i = (intptr_t)dirp;
  45. if (i >= 0) {
  46. SET_ERRNO(EBADF);
  47. return -1;
  48. }
  49. return close(~i);
  50. }
  51. static __attribute__((unused))
  52. int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
  53. {
  54. char buf[sizeof(struct linux_dirent64) + NAME_MAX + 1] __nolibc_aligned_as(struct linux_dirent64);
  55. struct linux_dirent64 *ldir = (void *)buf;
  56. intptr_t i = (intptr_t)dirp;
  57. int fd, ret;
  58. if (i >= 0)
  59. return EBADF;
  60. fd = ~i;
  61. ret = sys_getdents64(fd, ldir, sizeof(buf));
  62. if (ret < 0)
  63. return -ret;
  64. if (ret == 0) {
  65. *result = NULL;
  66. return 0;
  67. }
  68. /*
  69. * getdents64() returns as many entries as fit the buffer.
  70. * readdir() can only return one entry at a time.
  71. * Make sure the non-returned ones are not skipped.
  72. */
  73. ret = sys_lseek(fd, ldir->d_off, SEEK_SET);
  74. if (ret < 0)
  75. return -ret;
  76. entry->d_ino = ldir->d_ino;
  77. /* the destination should always be big enough */
  78. strlcpy(entry->d_name, ldir->d_name, sizeof(entry->d_name));
  79. *result = entry;
  80. return 0;
  81. }
  82. #endif /* _NOLIBC_DIRENT_H */