1 // Copyright 2012 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "subprocess.h"
16
17 #include <assert.h>
18 #include <stdio.h>
19
20 #include <algorithm>
21
22 #include "util.h"
23
Subprocess(bool use_console)24 Subprocess::Subprocess(bool use_console) : child_(NULL) , overlapped_(),
25 is_reading_(false),
26 use_console_(use_console) {
27 }
28
~Subprocess()29 Subprocess::~Subprocess() {
30 if (pipe_) {
31 if (!CloseHandle(pipe_))
32 Win32Fatal("CloseHandle");
33 }
34 // Reap child if forgotten.
35 if (child_)
36 Finish();
37 }
38
SetupPipe(HANDLE ioport)39 HANDLE Subprocess::SetupPipe(HANDLE ioport) {
40 char pipe_name[100];
41 snprintf(pipe_name, sizeof(pipe_name),
42 "\\\\.\\pipe\\ninja_pid%lu_sp%p", GetCurrentProcessId(), this);
43
44 pipe_ = ::CreateNamedPipeA(pipe_name,
45 PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
46 PIPE_TYPE_BYTE,
47 PIPE_UNLIMITED_INSTANCES,
48 0, 0, INFINITE, NULL);
49 if (pipe_ == INVALID_HANDLE_VALUE)
50 Win32Fatal("CreateNamedPipe");
51
52 if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
53 Win32Fatal("CreateIoCompletionPort");
54
55 memset(&overlapped_, 0, sizeof(overlapped_));
56 if (!ConnectNamedPipe(pipe_, &overlapped_) &&
57 GetLastError() != ERROR_IO_PENDING) {
58 Win32Fatal("ConnectNamedPipe");
59 }
60
61 // Get the write end of the pipe as a handle inheritable across processes.
62 HANDLE output_write_handle =
63 CreateFileA(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
64 HANDLE output_write_child;
65 if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
66 GetCurrentProcess(), &output_write_child,
67 0, TRUE, DUPLICATE_SAME_ACCESS)) {
68 Win32Fatal("DuplicateHandle");
69 }
70 CloseHandle(output_write_handle);
71
72 return output_write_child;
73 }
74
Start(SubprocessSet * set,const string & command)75 bool Subprocess::Start(SubprocessSet* set, const string& command) {
76 HANDLE child_pipe = SetupPipe(set->ioport_);
77
78 SECURITY_ATTRIBUTES security_attributes;
79 memset(&security_attributes, 0, sizeof(SECURITY_ATTRIBUTES));
80 security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
81 security_attributes.bInheritHandle = TRUE;
82 // Must be inheritable so subprocesses can dup to children.
83 HANDLE nul =
84 CreateFileA("NUL", GENERIC_READ,
85 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
86 &security_attributes, OPEN_EXISTING, 0, NULL);
87 if (nul == INVALID_HANDLE_VALUE)
88 Fatal("couldn't open nul");
89
90 STARTUPINFOA startup_info;
91 memset(&startup_info, 0, sizeof(startup_info));
92 startup_info.cb = sizeof(STARTUPINFO);
93 if (!use_console_) {
94 startup_info.dwFlags = STARTF_USESTDHANDLES;
95 startup_info.hStdInput = nul;
96 startup_info.hStdOutput = child_pipe;
97 startup_info.hStdError = child_pipe;
98 }
99 // In the console case, child_pipe is still inherited by the child and closed
100 // when the subprocess finishes, which then notifies ninja.
101
102 PROCESS_INFORMATION process_info;
103 memset(&process_info, 0, sizeof(process_info));
104
105 // Ninja handles ctrl-c, except for subprocesses in console pools.
106 DWORD process_flags = use_console_ ? 0 : CREATE_NEW_PROCESS_GROUP;
107
108 // Do not prepend 'cmd /c' on Windows, this breaks command
109 // lines greater than 8,191 chars.
110 if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
111 /* inherit handles */ TRUE, process_flags,
112 NULL, NULL,
113 &startup_info, &process_info)) {
114 DWORD error = GetLastError();
115 if (error == ERROR_FILE_NOT_FOUND) {
116 // File (program) not found error is treated as a normal build
117 // action failure.
118 if (child_pipe)
119 CloseHandle(child_pipe);
120 CloseHandle(pipe_);
121 CloseHandle(nul);
122 pipe_ = NULL;
123 // child_ is already NULL;
124 buf_ = "CreateProcess failed: The system cannot find the file "
125 "specified.\n";
126 return true;
127 } else {
128 fprintf(stderr, "\nCreateProcess failed. Command attempted:\n\"%s\"\n",
129 command.c_str());
130 const char* hint = NULL;
131 // ERROR_INVALID_PARAMETER means the command line was formatted
132 // incorrectly. This can be caused by a command line being too long or
133 // leading whitespace in the command. Give extra context for this case.
134 if (error == ERROR_INVALID_PARAMETER) {
135 if (command.length() > 0 && (command[0] == ' ' || command[0] == '\t'))
136 hint = "command contains leading whitespace";
137 else
138 hint = "is the command line too long?";
139 }
140 Win32Fatal("CreateProcess", hint);
141 }
142 }
143
144 // Close pipe channel only used by the child.
145 if (child_pipe)
146 CloseHandle(child_pipe);
147 CloseHandle(nul);
148
149 CloseHandle(process_info.hThread);
150 child_ = process_info.hProcess;
151
152 return true;
153 }
154
OnPipeReady()155 void Subprocess::OnPipeReady() {
156 DWORD bytes;
157 if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
158 if (GetLastError() == ERROR_BROKEN_PIPE) {
159 CloseHandle(pipe_);
160 pipe_ = NULL;
161 return;
162 }
163 Win32Fatal("GetOverlappedResult");
164 }
165
166 if (is_reading_ && bytes)
167 buf_.append(overlapped_buf_, bytes);
168
169 memset(&overlapped_, 0, sizeof(overlapped_));
170 is_reading_ = true;
171 if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
172 &bytes, &overlapped_)) {
173 if (GetLastError() == ERROR_BROKEN_PIPE) {
174 CloseHandle(pipe_);
175 pipe_ = NULL;
176 return;
177 }
178 if (GetLastError() != ERROR_IO_PENDING)
179 Win32Fatal("ReadFile");
180 }
181
182 // Even if we read any bytes in the readfile call, we'll enter this
183 // function again later and get them at that point.
184 }
185
Finish()186 ExitStatus Subprocess::Finish() {
187 if (!child_)
188 return ExitFailure;
189
190 // TODO: add error handling for all of these.
191 WaitForSingleObject(child_, INFINITE);
192
193 DWORD exit_code = 0;
194 GetExitCodeProcess(child_, &exit_code);
195
196 CloseHandle(child_);
197 child_ = NULL;
198
199 return exit_code == 0 ? ExitSuccess :
200 exit_code == CONTROL_C_EXIT ? ExitInterrupted :
201 ExitFailure;
202 }
203
Done() const204 bool Subprocess::Done() const {
205 return pipe_ == NULL;
206 }
207
GetOutput() const208 const string& Subprocess::GetOutput() const {
209 return buf_;
210 }
211
212 HANDLE SubprocessSet::ioport_;
213
SubprocessSet()214 SubprocessSet::SubprocessSet() {
215 ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
216 if (!ioport_)
217 Win32Fatal("CreateIoCompletionPort");
218 if (!SetConsoleCtrlHandler(NotifyInterrupted, TRUE))
219 Win32Fatal("SetConsoleCtrlHandler");
220 }
221
~SubprocessSet()222 SubprocessSet::~SubprocessSet() {
223 Clear();
224
225 SetConsoleCtrlHandler(NotifyInterrupted, FALSE);
226 CloseHandle(ioport_);
227 }
228
NotifyInterrupted(DWORD dwCtrlType)229 BOOL WINAPI SubprocessSet::NotifyInterrupted(DWORD dwCtrlType) {
230 if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) {
231 if (!PostQueuedCompletionStatus(ioport_, 0, 0, NULL))
232 Win32Fatal("PostQueuedCompletionStatus");
233 return TRUE;
234 }
235
236 return FALSE;
237 }
238
Add(const string & command,bool use_console)239 Subprocess *SubprocessSet::Add(const string& command, bool use_console) {
240 Subprocess *subprocess = new Subprocess(use_console);
241 if (!subprocess->Start(this, command)) {
242 delete subprocess;
243 return 0;
244 }
245 if (subprocess->child_)
246 running_.push_back(subprocess);
247 else
248 finished_.push(subprocess);
249 return subprocess;
250 }
251
DoWork()252 bool SubprocessSet::DoWork() {
253 DWORD bytes_read;
254 Subprocess* subproc;
255 OVERLAPPED* overlapped;
256
257 if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
258 &overlapped, INFINITE)) {
259 if (GetLastError() != ERROR_BROKEN_PIPE)
260 Win32Fatal("GetQueuedCompletionStatus");
261 }
262
263 if (!subproc) // A NULL subproc indicates that we were interrupted and is
264 // delivered by NotifyInterrupted above.
265 return true;
266
267 subproc->OnPipeReady();
268
269 if (subproc->Done()) {
270 vector<Subprocess*>::iterator end =
271 remove(running_.begin(), running_.end(), subproc);
272 if (running_.end() != end) {
273 finished_.push(subproc);
274 running_.resize(end - running_.begin());
275 }
276 }
277
278 return false;
279 }
280
NextFinished()281 Subprocess* SubprocessSet::NextFinished() {
282 if (finished_.empty())
283 return NULL;
284 Subprocess* subproc = finished_.front();
285 finished_.pop();
286 return subproc;
287 }
288
Clear()289 void SubprocessSet::Clear() {
290 for (vector<Subprocess*>::iterator i = running_.begin();
291 i != running_.end(); ++i) {
292 // Since the foreground process is in our process group, it will receive a
293 // CTRL_C_EVENT or CTRL_BREAK_EVENT at the same time as us.
294 if ((*i)->child_ && !(*i)->use_console_) {
295 if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,
296 GetProcessId((*i)->child_))) {
297 Win32Fatal("GenerateConsoleCtrlEvent");
298 }
299 }
300 }
301 for (vector<Subprocess*>::iterator i = running_.begin();
302 i != running_.end(); ++i)
303 delete *i;
304 running_.clear();
305 }
306