|
| 1 | +// This file contains Windows specific calls. |
| 2 | + |
| 3 | +// +build windows |
| 4 | + |
| 5 | +package cmd |
| 6 | + |
| 7 | +// Even though Windows has a POSIX layer, it's implemented in userspace and, |
| 8 | +// consequently, the "syscall" lib doesn't export it. |
| 9 | +// Because of it, we need to use specific Windows calls to handle some of the |
| 10 | +// syscall we're using the `lab`. |
| 11 | + |
| 12 | +import "syscall" |
| 13 | + |
| 14 | +// SetStdHandle is not exported by golang syscall lib, we need to get it |
| 15 | +// ourselves from kernel32.dll. |
| 16 | +var ( |
| 17 | + kernel32 = syscall.MustLoadDLL("kernel32.dll") |
| 18 | + procSetStdHandleAddr = kernel32.MustFindProc("SetStdHandle").Addr() |
| 19 | +) |
| 20 | + |
| 21 | +// Windows has the concept of "Handles", which in Unix can be directly |
| 22 | +// converted to integers. |
| 23 | +var ( |
| 24 | + sysStdout = int(syscall.Stdout) |
| 25 | + sysStderr = int(syscall.Stderr) |
| 26 | +) |
| 27 | + |
| 28 | +// closeFD behaves the as POSIX close() |
| 29 | +func closeFD(fd int) error { |
| 30 | + return syscall.Close(syscall.Handle(fd)) |
| 31 | +} |
| 32 | + |
| 33 | +// dupFD behaves the same as POSIX dup() |
| 34 | +func dupFD(fd int) (int, error) { |
| 35 | + proc, err := syscall.GetCurrentProcess() |
| 36 | + if err != nil { |
| 37 | + return 0, err |
| 38 | + } |
| 39 | + |
| 40 | + var hndl syscall.Handle |
| 41 | + err = syscall.DuplicateHandle(proc, syscall.Handle(fd), proc, &hndl, 0, true, syscall.DUPLICATE_SAME_ACCESS) |
| 42 | + return int(hndl), err |
| 43 | +} |
| 44 | + |
| 45 | +// dupFD2 behaves the same as POSIX dup2() |
| 46 | +func dupFD2(oldFD, newFD int) error { |
| 47 | + ret, _, err := syscall.Syscall(procSetStdHandleAddr, 2, uintptr(oldFD), uintptr(newFD), 0) |
| 48 | + if err != 0 { |
| 49 | + return error(err) |
| 50 | + } |
| 51 | + |
| 52 | + if ret == 0 { |
| 53 | + return syscall.EINVAL |
| 54 | + } |
| 55 | + |
| 56 | + return nil |
| 57 | +} |
0 commit comments