1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package os
6
7import (
8	"errors"
9	"runtime"
10	"sync/atomic"
11	"syscall"
12	"time"
13	"unsafe"
14)
15
16func (p *Process) wait() (ps *ProcessState, err error) {
17	handle := atomic.LoadUintptr(&p.handle)
18	s, e := syscall.WaitForSingleObject(syscall.Handle(handle), syscall.INFINITE)
19	switch s {
20	case syscall.WAIT_OBJECT_0:
21		break
22	case syscall.WAIT_FAILED:
23		return nil, NewSyscallError("WaitForSingleObject", e)
24	default:
25		return nil, errors.New("os: unexpected result from WaitForSingleObject")
26	}
27	var ec uint32
28	e = syscall.GetExitCodeProcess(syscall.Handle(handle), &ec)
29	if e != nil {
30		return nil, NewSyscallError("GetExitCodeProcess", e)
31	}
32	var u syscall.Rusage
33	e = syscall.GetProcessTimes(syscall.Handle(handle), &u.CreationTime, &u.ExitTime, &u.KernelTime, &u.UserTime)
34	if e != nil {
35		return nil, NewSyscallError("GetProcessTimes", e)
36	}
37	p.setDone()
38	// NOTE(brainman): It seems that sometimes process is not dead
39	// when WaitForSingleObject returns. But we do not know any
40	// other way to wait for it. Sleeping for a while seems to do
41	// the trick sometimes. So we will sleep and smell the roses.
42	defer time.Sleep(5 * time.Millisecond)
43	defer p.Release()
44	return &ProcessState{p.Pid, syscall.WaitStatus{ExitCode: ec}, &u}, nil
45}
46
47func terminateProcess(pid, exitcode int) error {
48	h, e := syscall.OpenProcess(syscall.PROCESS_TERMINATE, false, uint32(pid))
49	if e != nil {
50		return NewSyscallError("OpenProcess", e)
51	}
52	defer syscall.CloseHandle(h)
53	e = syscall.TerminateProcess(h, uint32(exitcode))
54	return NewSyscallError("TerminateProcess", e)
55}
56
57func (p *Process) signal(sig Signal) error {
58	handle := atomic.LoadUintptr(&p.handle)
59	if handle == uintptr(syscall.InvalidHandle) {
60		return syscall.EINVAL
61	}
62	if p.done() {
63		return errors.New("os: process already finished")
64	}
65	if sig == Kill {
66		err := terminateProcess(p.Pid, 1)
67		runtime.KeepAlive(p)
68		return err
69	}
70	// TODO(rsc): Handle Interrupt too?
71	return syscall.Errno(syscall.EWINDOWS)
72}
73
74func (p *Process) release() error {
75	handle := atomic.LoadUintptr(&p.handle)
76	if handle == uintptr(syscall.InvalidHandle) {
77		return syscall.EINVAL
78	}
79	e := syscall.CloseHandle(syscall.Handle(handle))
80	if e != nil {
81		return NewSyscallError("CloseHandle", e)
82	}
83	atomic.StoreUintptr(&p.handle, uintptr(syscall.InvalidHandle))
84	// no need for a finalizer anymore
85	runtime.SetFinalizer(p, nil)
86	return nil
87}
88
89func findProcess(pid int) (p *Process, err error) {
90	const da = syscall.STANDARD_RIGHTS_READ |
91		syscall.PROCESS_QUERY_INFORMATION | syscall.SYNCHRONIZE
92	h, e := syscall.OpenProcess(da, false, uint32(pid))
93	if e != nil {
94		return nil, NewSyscallError("OpenProcess", e)
95	}
96	return newProcess(pid, uintptr(h)), nil
97}
98
99func init() {
100	p := syscall.GetCommandLine()
101	cmd := syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(p))[:])
102	if len(cmd) == 0 {
103		arg0, _ := Executable()
104		Args = []string{arg0}
105	} else {
106		Args = commandLineToArgv(cmd)
107	}
108}
109
110// appendBSBytes appends n '\\' bytes to b and returns the resulting slice.
111func appendBSBytes(b []byte, n int) []byte {
112	for ; n > 0; n-- {
113		b = append(b, '\\')
114	}
115	return b
116}
117
118// readNextArg splits command line string cmd into next
119// argument and command line remainder.
120func readNextArg(cmd string) (arg []byte, rest string) {
121	var b []byte
122	var inquote bool
123	var nslash int
124	for ; len(cmd) > 0; cmd = cmd[1:] {
125		c := cmd[0]
126		switch c {
127		case ' ', '\t':
128			if !inquote {
129				return appendBSBytes(b, nslash), cmd[1:]
130			}
131		case '"':
132			b = appendBSBytes(b, nslash/2)
133			if nslash%2 == 0 {
134				// use "Prior to 2008" rule from
135				// http://daviddeley.com/autohotkey/parameters/parameters.htm
136				// section 5.2 to deal with double double quotes
137				if inquote && len(cmd) > 1 && cmd[1] == '"' {
138					b = append(b, c)
139					cmd = cmd[1:]
140				}
141				inquote = !inquote
142			} else {
143				b = append(b, c)
144			}
145			nslash = 0
146			continue
147		case '\\':
148			nslash++
149			continue
150		}
151		b = appendBSBytes(b, nslash)
152		nslash = 0
153		b = append(b, c)
154	}
155	return appendBSBytes(b, nslash), ""
156}
157
158// commandLineToArgv splits a command line into individual argument
159// strings, following the Windows conventions documented
160// at http://daviddeley.com/autohotkey/parameters/parameters.htm#WINARGV
161func commandLineToArgv(cmd string) []string {
162	var args []string
163	for len(cmd) > 0 {
164		if cmd[0] == ' ' || cmd[0] == '\t' {
165			cmd = cmd[1:]
166			continue
167		}
168		var arg []byte
169		arg, cmd = readNextArg(cmd)
170		args = append(args, string(arg))
171	}
172	return args
173}
174
175func ftToDuration(ft *syscall.Filetime) time.Duration {
176	n := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime) // in 100-nanosecond intervals
177	return time.Duration(n*100) * time.Nanosecond
178}
179
180func (p *ProcessState) userTime() time.Duration {
181	return ftToDuration(&p.rusage.UserTime)
182}
183
184func (p *ProcessState) systemTime() time.Duration {
185	return ftToDuration(&p.rusage.KernelTime)
186}
187