getdents.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
  3. *
  4. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  5. */
  6. #include <alloca.h>
  7. #include <assert.h>
  8. #include <errno.h>
  9. #include <dirent.h>
  10. #include <stddef.h>
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <sys/param.h>
  15. #include <sys/types.h>
  16. #include <sys/syscall.h>
  17. libc_hidden_proto(memcpy)
  18. libc_hidden_proto(lseek)
  19. #ifndef offsetof
  20. # define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  21. #endif
  22. struct kernel_dirent
  23. {
  24. long d_ino;
  25. __kernel_off_t d_off;
  26. unsigned short d_reclen;
  27. char d_name[256];
  28. };
  29. #define __NR___syscall_getdents __NR_getdents
  30. static inline _syscall3(int, __syscall_getdents, int, fd, unsigned char *, kdirp, size_t, count);
  31. ssize_t attribute_hidden __getdents (int fd, char *buf, size_t nbytes)
  32. {
  33. struct dirent *dp;
  34. off_t last_offset = -1;
  35. ssize_t retval;
  36. size_t red_nbytes;
  37. struct kernel_dirent *skdp, *kdp;
  38. const size_t size_diff = (offsetof (struct dirent, d_name)
  39. - offsetof (struct kernel_dirent, d_name));
  40. red_nbytes = MIN (nbytes - ((nbytes /
  41. (offsetof (struct dirent, d_name) + 14)) * size_diff),
  42. nbytes - size_diff);
  43. dp = (struct dirent *) buf;
  44. skdp = kdp = alloca (red_nbytes);
  45. retval = __syscall_getdents(fd, (char *)kdp, red_nbytes);
  46. if (retval == -1)
  47. return -1;
  48. while ((char *) kdp < (char *) skdp + retval) {
  49. const size_t alignment = __alignof__ (struct dirent);
  50. /* Since kdp->d_reclen is already aligned for the kernel structure
  51. this may compute a value that is bigger than necessary. */
  52. size_t new_reclen = ((kdp->d_reclen + size_diff + alignment - 1)
  53. & ~(alignment - 1));
  54. if ((char *) dp + new_reclen > buf + nbytes) {
  55. /* Our heuristic failed. We read too many entries. Reset
  56. the stream. */
  57. assert (last_offset != -1);
  58. lseek(fd, last_offset, SEEK_SET);
  59. if ((char *) dp == buf) {
  60. /* The buffer the user passed in is too small to hold even
  61. one entry. */
  62. __set_errno (EINVAL);
  63. return -1;
  64. }
  65. break;
  66. }
  67. last_offset = kdp->d_off;
  68. dp->d_ino = kdp->d_ino;
  69. dp->d_off = kdp->d_off;
  70. dp->d_reclen = new_reclen;
  71. dp->d_type = DT_UNKNOWN;
  72. memcpy (dp->d_name, kdp->d_name,
  73. kdp->d_reclen - offsetof (struct kernel_dirent, d_name));
  74. dp = (struct dirent *) ((char *) dp + new_reclen);
  75. kdp = (struct kernel_dirent *) (((char *) kdp) + kdp->d_reclen);
  76. }
  77. return (char *) dp - buf;
  78. }