-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
olreader.go
225 lines (200 loc) · 6.35 KB
/
olreader.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// 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.
//go:build windows
package olreader
// the olreader (OverlappedReader) provides a generic interface for
// doing overlapped reads from a particular handle. The handle is assumed
// to be a DataDog driver handle.
/*
#include <stdlib.h>
#include <memory.h>
*/
import "C"
import (
"fmt"
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
const (
// ERROR_INVALID_PARAMETER this error isn't in the windows package for some reason
ERROR_INVALID_PARAMETER windows.Errno = 87 //nolint:revive // use windows error naming convention
)
// This is the type that an overlapped read returns -- the overlapped object, which must be passed back to the kernel after reading
// followed by a predictably sized chunk of bytes
type readbuffer struct {
// ol _must_ be first, because it is the pointer returned from the overlapped
// operation and it's used to cast to the entire structure.
ol windows.Overlapped
buffersize int
data []uint8
}
// OverlappedCallbackFunc is called every time a read completes.
// if err is not nil, it will be set to
//
//nolint:revive // TODO(WKIT) Fix revive linter
type OverlappedCallback interface {
OnData([]uint8)
OnError(err error)
}
// OverlappedReader is the manager object for doing overlapped reads
// for a particular handle
//
//nolint:revive // TODO(WKIT) Fix revive linter
type OverlappedReader struct {
h windows.Handle
iocp windows.Handle
bufsz int
count int
cb OverlappedCallback
wg sync.WaitGroup
buffers []*readbuffer
}
//nolint:revive // TODO(WKIT) Fix revive linter
func NewOverlappedReader(cbfn OverlappedCallback, bufsz, count int) (*OverlappedReader, error) {
olr := &OverlappedReader{
cb: cbfn,
bufsz: bufsz,
count: count,
}
return olr, nil
}
//nolint:revive // TODO(WKIT) Fix revive linter
func (olr *OverlappedReader) Open(name string) error {
p, err := windows.UTF16PtrFromString(name)
if err != nil {
return fmt.Errorf("Failed to create device name %v", err)
}
h, err := windows.CreateFile(p,
windows.GENERIC_READ|windows.GENERIC_WRITE,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,
nil,
windows.OPEN_EXISTING,
windows.FILE_FLAG_OVERLAPPED,
windows.Handle(0))
if err != nil {
return fmt.Errorf("Failed to open handle to %s %v", name, err)
}
iocp, err := windows.CreateIoCompletionPort(h, windows.Handle(0), 0, 0)
if err != nil {
windows.CloseHandle(h)
return fmt.Errorf("error creating IO completion port %v", err)
}
olr.h = h
olr.iocp = iocp
return nil
}
//nolint:revive // TODO(WKIT) Fix revive linter
func (olr *OverlappedReader) Read() error {
if err := olr.createBuffers(); err != nil {
return fmt.Errorf("Failed to create overlapped read buffers")
}
if err := olr.initiateReads(); err != nil {
return err
}
olr.wg.Add(1)
go func() {
defer olr.wg.Done()
for {
var bytesRead uint32
var key uintptr
var ol *windows.Overlapped
err := windows.GetQueuedCompletionStatus(olr.iocp, &bytesRead, &key, &ol, windows.INFINITE)
if err != nil {
if err == syscall.Errno(syscall.WAIT_TIMEOUT) {
// this indicates that there was no queued completion status, this is fine
continue
}
if err == syscall.Errno(ERROR_INVALID_PARAMETER) {
// this should never occur. It means that we supplied a buffer
// too short for even the structure header.
olr.cb.OnError(err)
return
}
if err != syscall.Errno(syscall.ERROR_INSUFFICIENT_BUFFER) {
if ol == nil {
// the completion port was closed. time to go home
return
}
// if we get this error, there will still be at least
// the structure header. In any other case, fail out
olr.cb.OnError(err)
return
}
}
if ol == nil {
// the completion port was closed. time to go home
return
}
buf := (*readbuffer)(unsafe.Pointer(ol))
data := buf.data[:bytesRead]
olr.cb.OnData(data)
// re-initiate the read
// kick off another read
if err := windows.ReadFile(olr.h, buf.data[:], nil, &(buf.ol)); err != nil && err != windows.ERROR_IO_PENDING {
olr.cb.OnError(err)
}
}
}()
return nil
}
//nolint:revive // TODO(WKIT) Fix revive linter
func (olr *OverlappedReader) Stop() {
if olr.iocp != windows.Handle(0) {
_ = windows.CloseHandle(olr.iocp)
olr.iocp = windows.Handle(0)
}
if olr.h != windows.Handle(0) {
_ = windows.CloseHandle(olr.h)
olr.h = windows.Handle(0)
}
olr.wg.Wait()
olr.cleanBuffers()
}
// Ioctl passes an ioctl() through to the underlying handle
func (olr *OverlappedReader) Ioctl(ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *windows.Overlapped) (err error) {
return windows.DeviceIoControl(olr.h, ioControlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, bytesReturned, overlapped)
}
func (olr *OverlappedReader) initiateReads() error {
for _, buf := range olr.buffers {
if buf == nil {
// would only happen if `createbuffers` not called, or
// cleanbuffers was called. But ensure pointer is valid
return fmt.Errorf("Invalid buffer for read")
}
/*
* because this is an overlapped read, this will return ERROR_IO_PENDING
* even if we provide a buffer that's too small. The initial
* GetQueuedCompletionStatus() will return with the error if it's
* too small
*/
err := windows.ReadFile(olr.h, buf.data[:], nil, &buf.ol)
if err != nil && err != windows.ERROR_IO_PENDING {
return fmt.Errorf("Failed to initiate read %v", err)
}
}
return nil
}
func (olr *OverlappedReader) createBuffers() error {
olr.buffers = make([]*readbuffer, olr.count)
structsize := C.size_t(unsafe.Sizeof(readbuffer{}))
totalsize := C.size_t(olr.bufsz) + structsize
for i := 0; i < olr.count; i++ {
buf := (*readbuffer)(C.malloc(totalsize))
C.memset(unsafe.Pointer(buf), 0, C.size_t(unsafe.Sizeof(readbuffer{})))
bufpointer := unsafe.Add(unsafe.Pointer(buf), structsize)
buf.data = unsafe.Slice((*uint8)(bufpointer), olr.bufsz)
buf.buffersize = olr.bufsz
olr.buffers[i] = buf
}
return nil
}
func (olr *OverlappedReader) cleanBuffers() {
for idx, buf := range olr.buffers {
C.free(unsafe.Pointer(buf)) //nolint:govet
olr.buffers[idx] = nil
}
}