-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
dirent_linux.go
102 lines (86 loc) · 2.33 KB
/
dirent_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
// Copyright 2009 The Go Authors. All rights reserved.
//go:build linux
package procutil
import (
"bytes"
"syscall"
"unsafe"
"github.com/DataDog/datadog-agent/pkg/util/native"
)
var (
dotBytes = []byte(".")
doubleDotBytes = []byte("..")
)
// countDirent parses directory entries in buf and return the number of entries
func countDirent(buf []byte) (consumed int, count int) {
origlen := len(buf)
count = 0
for len(buf) > 0 {
reclen, ok := direntReclen(buf)
if !ok || reclen > uint64(len(buf)) {
return origlen, count
}
rec := buf[:reclen]
buf = buf[reclen:]
ino, ok := direntIno(rec)
if !ok {
break
}
if ino == 0 { // File absent in directory.
continue
}
const namoff = uint64(unsafe.Offsetof(syscall.Dirent{}.Name))
namlen, ok := direntNamlen(rec)
if !ok || namoff+namlen > uint64(len(rec)) {
break
}
name := rec[namoff : namoff+namlen]
for i, c := range name {
if c == 0 {
name = name[:i]
break
}
}
// skip "." and ".." directories
if bytes.Equal(name, dotBytes) || bytes.Equal(name, doubleDotBytes) {
continue
}
count++
}
return origlen - len(buf), count
}
func direntReclen(buf []byte) (uint64, bool) {
return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Reclen), unsafe.Sizeof(syscall.Dirent{}.Reclen))
}
func direntIno(buf []byte) (uint64, bool) {
return readInt(buf, unsafe.Offsetof(syscall.Dirent{}.Ino), unsafe.Sizeof(syscall.Dirent{}.Ino))
}
func direntNamlen(buf []byte) (uint64, bool) {
reclen, ok := direntReclen(buf)
if !ok {
return 0, false
}
return reclen - uint64(unsafe.Offsetof(syscall.Dirent{}.Name)), true
}
// readInt returns the size-bytes unsigned integer in native byte order at offset off.
func readInt(b []byte, off, size uintptr) (u uint64, ok bool) {
if len(b) < int(off+size) {
return 0, false
}
switch size {
case 1:
return uint64(b[off]), true
case 2:
return uint64(native.Endian.Uint16(b[off:])), true
case 4:
return uint64(native.Endian.Uint32(b[off:])), true
case 8:
return native.Endian.Uint64(b[off:]), true
default:
panic("syscall: readInt with unsupported size")
}
}