1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 //go:build darwin && go1.13
6 // +build darwin,go1.13
13 "golang.org/x/sys/internal/unsafeheader"
16 //sys closedir(dir uintptr) (err error)
17 //sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
19 func fdopendir(fd
int) (dir
uintptr, err error
) {
20 r0
, _
, e1
:= syscall_syscallPtr(libc_fdopendir_trampoline_addr
, uintptr(fd
), 0, 0)
28 var libc_fdopendir_trampoline_addr
uintptr
30 //go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
32 func Getdirentries(fd
int, buf
[]byte, basep
*uintptr) (n
int, err error
) {
33 // Simulate Getdirentries using fdopendir/readdir_r/closedir.
34 // We store the number of entries to skip in the seek
35 // offset of fd. See issue #31368.
36 // It's not the full required semantics, but should handle the case
37 // of calling Getdirentries or ReadDirent repeatedly.
38 // It won't handle assigning the results of lseek to *basep, or handle
39 // the directory being edited underfoot.
40 skip
, err
:= Seek(fd
, 0, 1 /* SEEK_CUR */)
45 // We need to duplicate the incoming file descriptor
46 // because the caller expects to retain control of it, but
47 // fdopendir expects to take control of its argument.
48 // Just Dup'ing the file descriptor is not enough, as the
49 // result shares underlying state. Use Openat to make a really
50 // new file descriptor referring to the same directory.
51 fd2
, err
:= Openat(fd
, ".", O_RDONLY
, 0)
55 d
, err
:= fdopendir(fd2
)
66 e
:= readdir_r(d
, &entry
, &entryp
)
79 reclen
:= int(entry
.Reclen
)
80 if reclen
> len(buf
) {
81 // Not enough room. Return for now.
82 // The counter will let us know where we should start up again.
83 // Note: this strategy for suspending in the middle and
84 // restarting is O(n^2) in the length of the directory. Oh well.
88 // Copy entry into return buffer.
90 hdr
:= (*unsafeheader
.Slice
)(unsafe
.Pointer(&s
))
91 hdr
.Data
= unsafe
.Pointer(&entry
)
100 // Set the seek offset of the input fd to record
101 // how many files we've already returned.
102 _
, err
= Seek(fd
, cnt
, 0 /* SEEK_SET */)