Files
Reims-Go/internal/plugin/vmjob_windows.go
T

192 lines
5.1 KiB
Go

//go:build windows
package plugin
import (
"fmt"
"sync"
"unsafe"
"golang.org/x/sys/windows"
)
const (
jobObjectMsgActiveProcessZero = 4
vmJobCompletionKey = 0x5247564d // "RGVM"
)
// vmJobAssociateCompletionPort mirrors JOBOBJECT_ASSOCIATE_COMPLETION_PORT.
type vmJobAssociateCompletionPort struct {
CompletionKey uintptr
CompletionPort windows.Handle
}
// vmJob holds the process tree of one driver-spawned VM. Unlike sidecarJob it
// does not kill its processes when the handle closes: a VM must survive a
// restart of the desktop client (for example an in-app update). Only an
// explicit Terminate stops it. A completion port reports when the last
// process of the tree has exited.
type vmJob struct {
mu sync.Mutex
job windows.Handle
port windows.Handle
done chan struct{}
doneOnce sync.Once
}
func newVMJob() (*vmJob, error) {
job, err := windows.CreateJobObject(nil, nil)
if err != nil {
return nil, fmt.Errorf("CreateJobObject: %w", err)
}
port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 1)
if err != nil {
_ = windows.CloseHandle(job)
return nil, fmt.Errorf("CreateIoCompletionPort: %w", err)
}
assoc := vmJobAssociateCompletionPort{CompletionKey: vmJobCompletionKey, CompletionPort: port}
if _, err := windows.SetInformationJobObject(job, windows.JobObjectAssociateCompletionPortInformation,
uintptr(unsafe.Pointer(&assoc)), uint32(unsafe.Sizeof(assoc))); err != nil {
_ = windows.CloseHandle(port)
_ = windows.CloseHandle(job)
return nil, fmt.Errorf("associate job completion port: %w", err)
}
j := &vmJob{job: job, port: port, done: make(chan struct{})}
go j.watch(port)
return j, nil
}
func (j *vmJob) watch(port windows.Handle) {
for {
var qty uint32
var key uintptr
var ov *windows.Overlapped
if err := windows.GetQueuedCompletionStatus(port, &qty, &key, &ov, windows.INFINITE); err != nil {
// The port was closed.
j.markDone()
return
}
if key == vmJobCompletionKey && qty == jobObjectMsgActiveProcessZero {
j.markDone()
return
}
}
}
func (j *vmJob) markDone() { j.doneOnce.Do(func() { close(j.done) }) }
// Done is closed once the job holds no process.
func (j *vmJob) Done() <-chan struct{} { return j.done }
// RootExited tells the job the root process was reaped. On Windows the job
// itself reports when the whole tree is gone, so there is nothing to do.
func (j *vmJob) RootExited() {}
// Assign puts the process, and every child it starts afterwards, in the job.
func (j *vmJob) Assign(pid int) error {
if j == nil || pid <= 0 {
return nil
}
j.mu.Lock()
defer j.mu.Unlock()
if j.job == 0 {
return fmt.Errorf("job closed")
}
proc, err := windows.OpenProcess(windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, uint32(pid))
if err != nil {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer windows.CloseHandle(proc)
return windows.AssignProcessToJobObject(j.job, proc)
}
// PIDs lists the processes currently in the job.
func (j *vmJob) PIDs() []uint32 {
if j == nil {
return nil
}
j.mu.Lock()
defer j.mu.Unlock()
if j.job == 0 {
return nil
}
const header = 8 // NumberOfAssignedProcesses + NumberOfProcessIdsInList
size := header + 8*16
for attempt := 0; attempt < 6; attempt++ {
buf := make([]byte, size)
var ret uint32
err := windows.QueryInformationJobObject(j.job, windows.JobObjectBasicProcessIdList,
uintptr(unsafe.Pointer(&buf[0])), uint32(len(buf)), &ret)
if err == windows.ERROR_MORE_DATA {
assigned := int(*(*uint32)(unsafe.Pointer(&buf[0])))
size = header + int(unsafe.Sizeof(uintptr(0)))*(assigned+16)
continue
}
if err != nil {
return nil
}
n := int(*(*uint32)(unsafe.Pointer(&buf[4])))
out := make([]uint32, 0, n)
for i := 0; i < n; i++ {
off := header + i*int(unsafe.Sizeof(uintptr(0)))
out = append(out, uint32(*(*uintptr)(unsafe.Pointer(&buf[off]))))
}
return out
}
return nil
}
// SetAffinity limits every process of the job, present and future, to mask.
// A zero mask removes the limit.
func (j *vmJob) SetAffinity(mask uint64) error {
if j == nil {
return nil
}
j.mu.Lock()
defer j.mu.Unlock()
if j.job == 0 {
return fmt.Errorf("job closed")
}
var info windows.JOBOBJECT_BASIC_LIMIT_INFORMATION
if mask != 0 {
info.LimitFlags = windows.JOB_OBJECT_LIMIT_AFFINITY
info.Affinity = uintptr(mask)
}
if _, err := windows.SetInformationJobObject(j.job, windows.JobObjectBasicLimitInformation,
uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))); err != nil {
return fmt.Errorf("SetInformationJobObject(affinity 0x%X): %w", mask, err)
}
return nil
}
// Terminate kills every process of the job.
func (j *vmJob) Terminate() error {
if j == nil {
return nil
}
j.mu.Lock()
defer j.mu.Unlock()
if j.job == 0 {
return nil
}
return windows.TerminateJobObject(j.job, 1)
}
// Close releases the handles without touching the processes.
func (j *vmJob) Close() {
if j == nil {
return
}
j.mu.Lock()
job, port := j.job, j.port
j.job, j.port = 0, 0
j.mu.Unlock()
if port != 0 {
_ = windows.CloseHandle(port)
}
if job != 0 {
_ = windows.CloseHandle(job)
}
j.markDone()
}