Skip to content

Commit 08e8c02

Browse files
committed
Fix usage of PowerUnregisterSuspendResumeNotification
1 parent 7beca62 commit 08e8c02

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

common/winpowrprof/event_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ func TestPowerEvents(t *testing.T) {
1111
if runtime.GOOS != "windows" {
1212
t.SkipNow()
1313
}
14+
t.Parallel()
1415
listener, err := NewEventListener(func(event int) {})
1516
require.NoError(t, err)
1617
require.NotNil(t, listener)

common/winpowrprof/event_windows.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ var suspendResumeNotificationCallback = common.OnceValue(func() uintptr {
4242
})
4343

4444
type powerEventListener struct {
45+
pinner myPinner
4546
callback EventCallback
4647
handle uintptr
4748
}
@@ -61,6 +62,7 @@ func NewEventListener(callback EventCallback) (EventListener, error) {
6162
}
6263

6364
func (l *powerEventListener) Start() error {
65+
l.pinner.Pin(&l.callback)
6466
type DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS struct {
6567
callback uintptr
6668
context unsafe.Pointer
@@ -77,15 +79,21 @@ func (l *powerEventListener) Start() error {
7779
uintptr(unsafe.Pointer(&l.handle)),
7880
)
7981
if errno != 0 {
82+
l.pinner.Unpin()
8083
return errno
8184
}
8285
return nil
8386
}
8487

8588
func (l *powerEventListener) Close() error {
86-
_, _, errno := syscall.SyscallN(procPowerUnregisterSuspendResumeNotification.Addr(), uintptr(unsafe.Pointer(&l.handle)))
87-
if errno != 0 {
88-
return errno
89+
if l.handle == 0 {
90+
return nil
91+
}
92+
defer l.pinner.Unpin()
93+
r0, _, _ := syscall.SyscallN(procPowerUnregisterSuspendResumeNotification.Addr(), l.handle)
94+
if r0 != windows.NO_ERROR {
95+
return syscall.Errno(r0)
8996
}
97+
l.handle = 0
9098
return nil
9199
}

common/winpowrprof/pinner.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
//go:build go1.21
2+
3+
package winpowrprof
4+
5+
import "runtime"
6+
7+
type myPinner = runtime.Pinner

common/winpowrprof/pinner_compat.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//go:build !go1.21
2+
3+
package winpowrprof
4+
5+
type myPinner struct{}
6+
7+
func (p *myPinner) Pin(pointer any) {
8+
}
9+
10+
func (p *myPinner) Unpin() {
11+
}

0 commit comments

Comments
 (0)