blob: b55aa2fa80ff4d781b517d33746c55a07c8be9cf [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
Reid Spencerb016a372004-09-15 05:49:50 +000014#include "Win32.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
NAKAMURA Takumi4cec6e22010-09-17 11:14:18 +000025#ifdef __MINGW32__
26// Ancient mingw32's w32api might not have this declaration.
27extern "C"
28BOOL WINAPI SetInformationJobObject(HANDLE hJob,
29 JOBOBJECTINFOCLASS JobObjectInfoClass,
30 LPVOID lpJobObjectInfo,
31 DWORD cbJobObjectInfoLength);
32#endif
33
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000034namespace {
35 struct Win32ProcessInfo {
36 HANDLE hProcess;
37 DWORD dwProcessId;
38 };
39}
40
Reid Spencerb016a372004-09-15 05:49:50 +000041namespace llvm {
42using namespace sys;
43
Daniel Dunbar57d69032009-09-22 04:44:56 +000044Program::Program() : Data_(0) {}
45
46Program::~Program() {
47 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000048 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
49 CloseHandle(wpi->hProcess);
50 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +000051 Data_ = 0;
52 }
53}
54
55unsigned Program::GetPid() const {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +000056 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
57 return wpi->dwProcessId;
Daniel Dunbar57d69032009-09-22 04:44:56 +000058}
59
Reid Spencerb016a372004-09-15 05:49:50 +000060// This function just uses the PATH environment variable to find the program.
61Path
62Program::FindProgramByName(const std::string& progName) {
63
64 // Check some degenerate cases
65 if (progName.length() == 0) // no program
66 return Path();
67 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000068 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000069 return Path();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000070 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000071 return temp;
72
73 // At this point, the file name is valid and its not executable.
74 // Let Windows search for it.
75 char buffer[MAX_PATH];
76 char *dummy = NULL;
77 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
78 buffer, &dummy);
79
80 // See if it wasn't found.
81 if (len == 0)
82 return Path();
83
84 // See if we got the entire path.
85 if (len < MAX_PATH)
86 return Path(buffer);
87
88 // Buffer was too small; grow and retry.
89 while (true) {
90 char *b = reinterpret_cast<char *>(_alloca(len+1));
91 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
92
93 // It is unlikely the search failed, but it's always possible some file
94 // was added or removed since the last search, so be paranoid...
95 if (len2 == 0)
96 return Path();
97 else if (len2 <= len)
98 return Path(b);
99
100 len = len2;
101 }
102}
103
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000104static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000105 HANDLE h;
106 if (path == 0) {
107 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
108 GetCurrentProcess(), &h,
109 0, TRUE, DUPLICATE_SAME_ACCESS);
110 return h;
111 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000112
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000113 const char *fname;
114 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +0000115 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000116 else
Chris Lattner74382b72009-08-23 22:45:37 +0000117 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +0000118
119 SECURITY_ATTRIBUTES sa;
120 sa.nLength = sizeof(sa);
121 sa.lpSecurityDescriptor = 0;
122 sa.bInheritHandle = TRUE;
123
124 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000125 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000126 FILE_ATTRIBUTE_NORMAL, NULL);
127 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000128 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000129 (fd ? "input: " : "output: "));
130 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000131
Jeff Cohen875d08e2005-02-20 02:43:04 +0000132 return h;
133}
134
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000135/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
136/// CreateProcess.
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000137static bool ArgNeedsQuotes(const char *Str) {
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000138 return Str[0] == '\0' || strchr(Str, ' ') != 0;
139}
140
Anton Korobeynikov81244292010-03-28 15:07:02 +0000141
142/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
143/// CreateProcess and returns length of quoted arg with escaped quotes
144static unsigned int ArgLenWithQuotes(const char *Str) {
145 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
146
147 while (*Str != '\0') {
148 if (*Str == '\"')
149 ++len;
150
151 ++len;
152 ++Str;
153 }
154
155 return len;
156}
157
158
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000159bool
160Program::Execute(const Path& path,
161 const char** args,
162 const char** envp,
163 const Path** redirects,
164 unsigned memoryLimit,
165 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000166 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000167 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
168 CloseHandle(wpi->hProcess);
169 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000170 Data_ = 0;
171 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000172
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000173 if (!path.canExecute()) {
174 if (ErrMsg)
175 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000176 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000177 }
Reid Spencerb016a372004-09-15 05:49:50 +0000178
179 // Windows wants a command line, not an array of args, to pass to the new
180 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000181 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000182
183 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000184 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000185 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikov81244292010-03-28 15:07:02 +0000186 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb016a372004-09-15 05:49:50 +0000187 }
188
189 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000190 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000191 char *p = command;
192
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000193 for (unsigned i = 0; args[i]; i++) {
194 const char *arg = args[i];
Anton Korobeynikov81244292010-03-28 15:07:02 +0000195
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000196 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000197 if (needsQuoting)
198 *p++ = '"';
Anton Korobeynikov81244292010-03-28 15:07:02 +0000199
200 while (*arg != '\0') {
201 if (*arg == '\"')
202 *p++ = '\\';
203
204 *p++ = *arg++;
205 }
206
Reid Spencerb016a372004-09-15 05:49:50 +0000207 if (needsQuoting)
208 *p++ = '"';
209 *p++ = ' ';
210 }
211
212 *p = 0;
213
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000214 // The pointer to the environment block for the new process.
215 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000216
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000217 if (envp) {
218 // An environment block consists of a null-terminated block of
219 // null-terminated strings. Convert the array of environment variables to
220 // an environment block by concatenating them.
221
222 // First, determine the length of the environment block.
223 len = 0;
224 for (unsigned i = 0; envp[i]; i++)
225 len += strlen(envp[i]) + 1;
226
227 // Now build the environment block.
228 envblock = reinterpret_cast<char *>(_alloca(len+1));
229 p = envblock;
230
231 for (unsigned i = 0; envp[i]; i++) {
232 const char *ev = envp[i];
233 size_t len = strlen(ev) + 1;
234 memcpy(p, ev, len);
235 p += len;
236 }
237
238 *p = 0;
239 }
240
Reid Spencerb016a372004-09-15 05:49:50 +0000241 // Create a child process.
242 STARTUPINFO si;
243 memset(&si, 0, sizeof(si));
244 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000245 si.hStdInput = INVALID_HANDLE_VALUE;
246 si.hStdOutput = INVALID_HANDLE_VALUE;
247 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000248
Jeff Cohen875d08e2005-02-20 02:43:04 +0000249 if (redirects) {
250 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000251
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000252 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
253 if (si.hStdInput == INVALID_HANDLE_VALUE) {
254 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000255 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000256 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000257 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000258 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000259 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000260 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000261 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000262 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000263 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
264 // If stdout and stderr should go to the same place, redirect stderr
265 // to the handle already open for stdout.
266 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
267 GetCurrentProcess(), &si.hStdError,
268 0, TRUE, DUPLICATE_SAME_ACCESS);
269 } else {
270 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000271 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000272 if (si.hStdError == INVALID_HANDLE_VALUE) {
273 CloseHandle(si.hStdInput);
274 CloseHandle(si.hStdOutput);
275 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000276 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000277 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000278 }
279 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000280
Reid Spencerb016a372004-09-15 05:49:50 +0000281 PROCESS_INFORMATION pi;
282 memset(&pi, 0, sizeof(pi));
283
Jeff Cohen875d08e2005-02-20 02:43:04 +0000284 fflush(stdout);
285 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000286 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000287 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000288 DWORD err = GetLastError();
289
290 // Regardless of whether the process got created or not, we are done with
291 // the handles we created for it to inherit.
292 CloseHandle(si.hStdInput);
293 CloseHandle(si.hStdOutput);
294 CloseHandle(si.hStdError);
295
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000296 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000297 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000298 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000299 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000300 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000301 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000302 }
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000303 Win32ProcessInfo* wpi = new Win32ProcessInfo;
304 wpi->hProcess = pi.hProcess;
305 wpi->dwProcessId = pi.dwProcessId;
306 Data_ = wpi;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000307
Jeff Cohen0a182672007-03-05 05:22:08 +0000308 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000309 AutoHandle hThread(pi.hThread);
310
311 // Assign the process to a job if a memory limit is defined.
312 AutoHandle hJob(0);
313 if (memoryLimit != 0) {
314 hJob = CreateJobObject(0, 0);
315 bool success = false;
316 if (hJob != 0) {
317 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
318 memset(&jeli, 0, sizeof(jeli));
319 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000320 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000321 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
322 &jeli, sizeof(jeli))) {
323 if (AssignProcessToJobObject(hJob, pi.hProcess))
324 success = true;
325 }
326 }
327 if (!success) {
328 SetLastError(GetLastError());
329 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
330 TerminateProcess(pi.hProcess, 1);
331 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000332 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000333 }
334 }
335
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000336 return true;
337}
338
339int
Dan Gohmane5f77cd2010-10-29 16:54:25 +0000340Program::Wait(const Path &path,
341 unsigned secondsToWait,
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000342 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000343 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000344 MakeErrMsg(ErrMsg, "Process not started!");
345 return -1;
346 }
347
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000348 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
349 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000350
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000351 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000352 DWORD millisecondsToWait = INFINITE;
353 if (secondsToWait > 0)
354 millisecondsToWait = secondsToWait * 1000;
355
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000356 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
357 if (!TerminateProcess(hProcess, 1)) {
358 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000359 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000360 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000361 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000362 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000363
Reid Spencerb016a372004-09-15 05:49:50 +0000364 // Get its exit status.
365 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000366 BOOL rc = GetExitCodeProcess(hProcess, &status);
367 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000368
Jeff Cohen875d08e2005-02-20 02:43:04 +0000369 if (!rc) {
370 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000371 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000372 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000373 }
Reid Spencerb016a372004-09-15 05:49:50 +0000374
375 return status;
376}
377
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000378bool
379Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000380 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000381 MakeErrMsg(ErrMsg, "Process not started!");
382 return true;
383 }
384
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000385 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
386 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000387 if (TerminateProcess(hProcess, 1) == 0) {
388 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
389 return true;
390 }
391
392 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000393}
394
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000395bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000396 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000397 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000398}
399
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000400bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000401 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000402 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000403}
404
Douglas Gregor21569cd2010-01-28 06:42:08 +0000405bool Program::ChangeStderrToBinary(){
406 int result = _setmode( _fileno(stderr), _O_BINARY );
407 return result == -1;
408}
409
Reid Spencerb016a372004-09-15 05:49:50 +0000410}