blob: e486e6ec2381537e09f8f5e876ea3d61552d6623 [file] [log] [blame]
Reid Spencerb016a372004-09-15 05:49:50 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +00002//
Reid Spencer52a7efa2004-08-29 19:20:41 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +00007//
Reid Spencer52a7efa2004-08-29 19:20:41 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000014#include "Windows.h"
Reid Spencer32f55532006-06-07 23:18:34 +000015#include <cstdio>
Reid Spencerb016a372004-09-15 05:49:50 +000016#include <malloc.h>
Jeff Cohen875d08e2005-02-20 02:43:04 +000017#include <io.h>
Reid Spencer32f55532006-06-07 23:18:34 +000018#include <fcntl.h>
Reid Spencerb016a372004-09-15 05:49:50 +000019
Reid Spencer52a7efa2004-08-29 19:20:41 +000020//===----------------------------------------------------------------------===//
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +000021//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb016a372004-09-15 05:49:50 +000022//=== and must not be UNIX code
Reid Spencer52a7efa2004-08-29 19:20:41 +000023//===----------------------------------------------------------------------===//
24
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000025namespace {
26 struct Win32ProcessInfo {
27 HANDLE hProcess;
28 DWORD dwProcessId;
29 };
30}
31
Reid Spencerb016a372004-09-15 05:49:50 +000032namespace llvm {
33using namespace sys;
34
Daniel Dunbar57d69032009-09-22 04:44:56 +000035Program::Program() : Data_(0) {}
36
37Program::~Program() {
38 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000039 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
40 CloseHandle(wpi->hProcess);
41 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +000042 Data_ = 0;
43 }
44}
45
46unsigned Program::GetPid() const {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000047 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
48 return wpi->dwProcessId;
Daniel Dunbar57d69032009-09-22 04:44:56 +000049}
50
Reid Spencerb016a372004-09-15 05:49:50 +000051// This function just uses the PATH environment variable to find the program.
52Path
53Program::FindProgramByName(const std::string& progName) {
54
55 // Check some degenerate cases
56 if (progName.length() == 0) // no program
57 return Path();
58 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000059 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000060 return Path();
Mikhail Glushenkov9cd59712010-11-02 20:32:39 +000061 // Return paths with slashes verbatim.
62 if (progName.find('\\') != std::string::npos ||
63 progName.find('/') != std::string::npos)
Reid Spencerb016a372004-09-15 05:49:50 +000064 return temp;
65
Mikhail Glushenkov9cd59712010-11-02 20:32:39 +000066 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb016a372004-09-15 05:49:50 +000067 // Let Windows search for it.
68 char buffer[MAX_PATH];
69 char *dummy = NULL;
70 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
71 buffer, &dummy);
72
73 // See if it wasn't found.
74 if (len == 0)
75 return Path();
76
77 // See if we got the entire path.
78 if (len < MAX_PATH)
79 return Path(buffer);
80
81 // Buffer was too small; grow and retry.
82 while (true) {
83 char *b = reinterpret_cast<char *>(_alloca(len+1));
84 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
85
86 // It is unlikely the search failed, but it's always possible some file
87 // was added or removed since the last search, so be paranoid...
88 if (len2 == 0)
89 return Path();
90 else if (len2 <= len)
91 return Path(b);
92
93 len = len2;
94 }
95}
96
Reid Spencer4ce5dc62006-08-21 06:02:44 +000097static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +000098 HANDLE h;
99 if (path == 0) {
100 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
101 GetCurrentProcess(), &h,
102 0, TRUE, DUPLICATE_SAME_ACCESS);
103 return h;
104 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000105
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000106 const char *fname;
107 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +0000108 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000109 else
Chris Lattner74382b72009-08-23 22:45:37 +0000110 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +0000111
112 SECURITY_ATTRIBUTES sa;
113 sa.nLength = sizeof(sa);
114 sa.lpSecurityDescriptor = 0;
115 sa.bInheritHandle = TRUE;
116
117 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000118 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000119 FILE_ATTRIBUTE_NORMAL, NULL);
120 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000121 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000122 (fd ? "input: " : "output: "));
123 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000124
Jeff Cohen875d08e2005-02-20 02:43:04 +0000125 return h;
126}
127
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000128/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
129/// CreateProcess.
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000130static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi0f0889e2011-02-05 08:53:12 +0000131 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000132}
133
Anton Korobeynikov81244292010-03-28 15:07:02 +0000134
135/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
136/// CreateProcess and returns length of quoted arg with escaped quotes
137static unsigned int ArgLenWithQuotes(const char *Str) {
138 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
139
140 while (*Str != '\0') {
141 if (*Str == '\"')
142 ++len;
143
144 ++len;
145 ++Str;
146 }
147
148 return len;
149}
150
151
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000152bool
153Program::Execute(const Path& path,
154 const char** args,
155 const char** envp,
156 const Path** redirects,
157 unsigned memoryLimit,
158 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000159 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000160 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
161 CloseHandle(wpi->hProcess);
162 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000163 Data_ = 0;
164 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000165
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000166 if (!path.canExecute()) {
167 if (ErrMsg)
168 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000169 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000170 }
Reid Spencerb016a372004-09-15 05:49:50 +0000171
172 // Windows wants a command line, not an array of args, to pass to the new
173 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000174 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000175
176 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000177 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000178 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikov81244292010-03-28 15:07:02 +0000179 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb016a372004-09-15 05:49:50 +0000180 }
181
182 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000183 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000184 char *p = command;
185
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000186 for (unsigned i = 0; args[i]; i++) {
187 const char *arg = args[i];
Anton Korobeynikov81244292010-03-28 15:07:02 +0000188
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000189 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000190 if (needsQuoting)
191 *p++ = '"';
Anton Korobeynikov81244292010-03-28 15:07:02 +0000192
193 while (*arg != '\0') {
194 if (*arg == '\"')
195 *p++ = '\\';
196
197 *p++ = *arg++;
198 }
199
Reid Spencerb016a372004-09-15 05:49:50 +0000200 if (needsQuoting)
201 *p++ = '"';
202 *p++ = ' ';
203 }
204
205 *p = 0;
206
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000207 // The pointer to the environment block for the new process.
208 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000209
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000210 if (envp) {
211 // An environment block consists of a null-terminated block of
212 // null-terminated strings. Convert the array of environment variables to
213 // an environment block by concatenating them.
214
215 // First, determine the length of the environment block.
216 len = 0;
217 for (unsigned i = 0; envp[i]; i++)
218 len += strlen(envp[i]) + 1;
219
220 // Now build the environment block.
221 envblock = reinterpret_cast<char *>(_alloca(len+1));
222 p = envblock;
223
224 for (unsigned i = 0; envp[i]; i++) {
225 const char *ev = envp[i];
226 size_t len = strlen(ev) + 1;
227 memcpy(p, ev, len);
228 p += len;
229 }
230
231 *p = 0;
232 }
233
Reid Spencerb016a372004-09-15 05:49:50 +0000234 // Create a child process.
235 STARTUPINFO si;
236 memset(&si, 0, sizeof(si));
237 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000238 si.hStdInput = INVALID_HANDLE_VALUE;
239 si.hStdOutput = INVALID_HANDLE_VALUE;
240 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000241
Jeff Cohen875d08e2005-02-20 02:43:04 +0000242 if (redirects) {
243 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000244
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000245 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
246 if (si.hStdInput == INVALID_HANDLE_VALUE) {
247 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000248 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000249 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000250 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000251 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000252 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000253 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000254 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000255 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000256 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
257 // If stdout and stderr should go to the same place, redirect stderr
258 // to the handle already open for stdout.
259 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
260 GetCurrentProcess(), &si.hStdError,
261 0, TRUE, DUPLICATE_SAME_ACCESS);
262 } else {
263 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000264 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000265 if (si.hStdError == INVALID_HANDLE_VALUE) {
266 CloseHandle(si.hStdInput);
267 CloseHandle(si.hStdOutput);
268 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000269 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000270 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000271 }
272 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000273
Reid Spencerb016a372004-09-15 05:49:50 +0000274 PROCESS_INFORMATION pi;
275 memset(&pi, 0, sizeof(pi));
276
Jeff Cohen875d08e2005-02-20 02:43:04 +0000277 fflush(stdout);
278 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000279 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000280 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000281 DWORD err = GetLastError();
282
283 // Regardless of whether the process got created or not, we are done with
284 // the handles we created for it to inherit.
285 CloseHandle(si.hStdInput);
286 CloseHandle(si.hStdOutput);
287 CloseHandle(si.hStdError);
288
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000289 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000290 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000291 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000292 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000293 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000294 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000295 }
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000296 Win32ProcessInfo* wpi = new Win32ProcessInfo;
297 wpi->hProcess = pi.hProcess;
298 wpi->dwProcessId = pi.dwProcessId;
299 Data_ = wpi;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000300
Jeff Cohen0a182672007-03-05 05:22:08 +0000301 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000302 AutoHandle hThread(pi.hThread);
303
304 // Assign the process to a job if a memory limit is defined.
305 AutoHandle hJob(0);
306 if (memoryLimit != 0) {
307 hJob = CreateJobObject(0, 0);
308 bool success = false;
309 if (hJob != 0) {
310 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
311 memset(&jeli, 0, sizeof(jeli));
312 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000313 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000314 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
315 &jeli, sizeof(jeli))) {
316 if (AssignProcessToJobObject(hJob, pi.hProcess))
317 success = true;
318 }
319 }
320 if (!success) {
321 SetLastError(GetLastError());
322 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
323 TerminateProcess(pi.hProcess, 1);
324 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000325 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000326 }
327 }
328
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000329 return true;
330}
331
332int
Dan Gohmane5f77cd2010-10-29 16:54:25 +0000333Program::Wait(const Path &path,
334 unsigned secondsToWait,
Andrew Trickdc5948d2011-05-21 00:56:46 +0000335 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000336 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000337 MakeErrMsg(ErrMsg, "Process not started!");
338 return -1;
339 }
340
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000341 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
342 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000343
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000344 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000345 DWORD millisecondsToWait = INFINITE;
346 if (secondsToWait > 0)
347 millisecondsToWait = secondsToWait * 1000;
348
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000349 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
350 if (!TerminateProcess(hProcess, 1)) {
351 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Andrew Trickdc5948d2011-05-21 00:56:46 +0000352 // -2 indicates a crash or timeout as opposed to failure to execute.
353 return -2;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000354 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000355 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000356 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000357
Reid Spencerb016a372004-09-15 05:49:50 +0000358 // Get its exit status.
359 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000360 BOOL rc = GetExitCodeProcess(hProcess, &status);
361 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000362
Jeff Cohen875d08e2005-02-20 02:43:04 +0000363 if (!rc) {
364 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000365 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Andrew Trickdc5948d2011-05-21 00:56:46 +0000366 // -2 indicates a crash or timeout as opposed to failure to execute.
367 return -2;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000368 }
Reid Spencerb016a372004-09-15 05:49:50 +0000369
370 return status;
371}
372
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000373bool
374Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000375 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000376 MakeErrMsg(ErrMsg, "Process not started!");
377 return true;
378 }
379
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000380 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
381 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000382 if (TerminateProcess(hProcess, 1) == 0) {
383 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
384 return true;
385 }
386
387 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000388}
389
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000390bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000391 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000392 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000393}
394
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000395bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000396 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000397 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000398}
399
Douglas Gregor21569cd2010-01-28 06:42:08 +0000400bool Program::ChangeStderrToBinary(){
401 int result = _setmode( _fileno(stderr), _O_BINARY );
402 return result == -1;
403}
404
Reid Spencerb016a372004-09-15 05:49:50 +0000405}