blob: af6cce6de1a710d3da29eed1c94691fffc5e2bfc [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
Reid Spencerb016a372004-09-15 05:49:50 +000025namespace llvm {
26using namespace sys;
27
Daniel Dunbar57d69032009-09-22 04:44:56 +000028Program::Program() : Data_(0) {}
29
30Program::~Program() {
31 if (Data_) {
32 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
33 CloseHandle(hProcess);
34 Data_ = 0;
35 }
36}
37
38unsigned Program::GetPid() const {
39 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
40 return GetProcessId(hProcess);
41}
42
Reid Spencerb016a372004-09-15 05:49:50 +000043// This function just uses the PATH environment variable to find the program.
44Path
45Program::FindProgramByName(const std::string& progName) {
46
47 // Check some degenerate cases
48 if (progName.length() == 0) // no program
49 return Path();
50 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000051 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000052 return Path();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000053 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000054 return temp;
55
56 // At this point, the file name is valid and its not executable.
57 // Let Windows search for it.
58 char buffer[MAX_PATH];
59 char *dummy = NULL;
60 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
61 buffer, &dummy);
62
63 // See if it wasn't found.
64 if (len == 0)
65 return Path();
66
67 // See if we got the entire path.
68 if (len < MAX_PATH)
69 return Path(buffer);
70
71 // Buffer was too small; grow and retry.
72 while (true) {
73 char *b = reinterpret_cast<char *>(_alloca(len+1));
74 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
75
76 // It is unlikely the search failed, but it's always possible some file
77 // was added or removed since the last search, so be paranoid...
78 if (len2 == 0)
79 return Path();
80 else if (len2 <= len)
81 return Path(b);
82
83 len = len2;
84 }
85}
86
Reid Spencer4ce5dc62006-08-21 06:02:44 +000087static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +000088 HANDLE h;
89 if (path == 0) {
90 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
91 GetCurrentProcess(), &h,
92 0, TRUE, DUPLICATE_SAME_ACCESS);
93 return h;
94 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +000095
Matthijs Kooijman905261e2008-06-12 10:47:18 +000096 const char *fname;
97 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +000098 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +000099 else
Chris Lattner74382b72009-08-23 22:45:37 +0000100 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +0000101
102 SECURITY_ATTRIBUTES sa;
103 sa.nLength = sizeof(sa);
104 sa.lpSecurityDescriptor = 0;
105 sa.bInheritHandle = TRUE;
106
107 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000108 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000109 FILE_ATTRIBUTE_NORMAL, NULL);
110 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000111 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000112 (fd ? "input: " : "output: "));
113 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000114
Jeff Cohen875d08e2005-02-20 02:43:04 +0000115 return h;
116}
117
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000118#ifdef __MINGW32__
119 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
Anton Korobeynikovd437db12007-03-19 20:19:08 +0000120 extern "C"
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000121 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
122 JOBOBJECTINFOCLASS JobObjectInfoClass,
123 LPVOID lpJobObjectInfo,
124 DWORD cbJobObjectInfoLength);
125#endif
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000126
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000127/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
128/// CreateProcess.
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000129static bool ArgNeedsQuotes(const char *Str) {
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000130 return Str[0] == '\0' || strchr(Str, ' ') != 0;
131}
132
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000133bool
134Program::Execute(const Path& path,
135 const char** args,
136 const char** envp,
137 const Path** redirects,
138 unsigned memoryLimit,
139 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000140 if (Data_) {
141 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
142 CloseHandle(Data_);
143 Data_ = 0;
144 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000145
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000146 if (!path.canExecute()) {
147 if (ErrMsg)
148 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000149 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000150 }
Reid Spencerb016a372004-09-15 05:49:50 +0000151
152 // Windows wants a command line, not an array of args, to pass to the new
153 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000154 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000155
156 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000157 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000158 for (unsigned i = 0; args[i]; i++) {
159 len += strlen(args[i]) + 1;
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000160 if (ArgNeedsQuotes(args[i]))
Reid Spencerb016a372004-09-15 05:49:50 +0000161 len += 2;
162 }
163
164 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000165 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000166 char *p = command;
167
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000168 for (unsigned i = 0; args[i]; i++) {
169 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000170 size_t len = strlen(arg);
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000171 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000172 if (needsQuoting)
173 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000174 memcpy(p, arg, len);
175 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000176 if (needsQuoting)
177 *p++ = '"';
178 *p++ = ' ';
179 }
180
181 *p = 0;
182
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000183 // The pointer to the environment block for the new process.
184 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000185
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000186 if (envp) {
187 // An environment block consists of a null-terminated block of
188 // null-terminated strings. Convert the array of environment variables to
189 // an environment block by concatenating them.
190
191 // First, determine the length of the environment block.
192 len = 0;
193 for (unsigned i = 0; envp[i]; i++)
194 len += strlen(envp[i]) + 1;
195
196 // Now build the environment block.
197 envblock = reinterpret_cast<char *>(_alloca(len+1));
198 p = envblock;
199
200 for (unsigned i = 0; envp[i]; i++) {
201 const char *ev = envp[i];
202 size_t len = strlen(ev) + 1;
203 memcpy(p, ev, len);
204 p += len;
205 }
206
207 *p = 0;
208 }
209
Reid Spencerb016a372004-09-15 05:49:50 +0000210 // Create a child process.
211 STARTUPINFO si;
212 memset(&si, 0, sizeof(si));
213 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000214 si.hStdInput = INVALID_HANDLE_VALUE;
215 si.hStdOutput = INVALID_HANDLE_VALUE;
216 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000217
Jeff Cohen875d08e2005-02-20 02:43:04 +0000218 if (redirects) {
219 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000220
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000221 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
222 if (si.hStdInput == INVALID_HANDLE_VALUE) {
223 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000224 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000225 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000226 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000227 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000228 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000229 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000230 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000231 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000232 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
233 // If stdout and stderr should go to the same place, redirect stderr
234 // to the handle already open for stdout.
235 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
236 GetCurrentProcess(), &si.hStdError,
237 0, TRUE, DUPLICATE_SAME_ACCESS);
238 } else {
239 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000240 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000241 if (si.hStdError == INVALID_HANDLE_VALUE) {
242 CloseHandle(si.hStdInput);
243 CloseHandle(si.hStdOutput);
244 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000245 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000246 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000247 }
248 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000249
Reid Spencerb016a372004-09-15 05:49:50 +0000250 PROCESS_INFORMATION pi;
251 memset(&pi, 0, sizeof(pi));
252
Jeff Cohen875d08e2005-02-20 02:43:04 +0000253 fflush(stdout);
254 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000255 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000256 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000257 DWORD err = GetLastError();
258
259 // Regardless of whether the process got created or not, we are done with
260 // the handles we created for it to inherit.
261 CloseHandle(si.hStdInput);
262 CloseHandle(si.hStdOutput);
263 CloseHandle(si.hStdError);
264
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000265 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000266 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000267 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000268 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000269 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000270 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000271 }
Daniel Dunbar57d69032009-09-22 04:44:56 +0000272 Data_ = reinterpret_cast<void*>(pi.hProcess);
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000273
Jeff Cohen0a182672007-03-05 05:22:08 +0000274 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000275 AutoHandle hThread(pi.hThread);
276
277 // Assign the process to a job if a memory limit is defined.
278 AutoHandle hJob(0);
279 if (memoryLimit != 0) {
280 hJob = CreateJobObject(0, 0);
281 bool success = false;
282 if (hJob != 0) {
283 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
284 memset(&jeli, 0, sizeof(jeli));
285 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000286 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000287 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
288 &jeli, sizeof(jeli))) {
289 if (AssignProcessToJobObject(hJob, pi.hProcess))
290 success = true;
291 }
292 }
293 if (!success) {
294 SetLastError(GetLastError());
295 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
296 TerminateProcess(pi.hProcess, 1);
297 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000298 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000299 }
300 }
301
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000302 return true;
303}
304
305int
306Program::Wait(unsigned secondsToWait,
307 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000308 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000309 MakeErrMsg(ErrMsg, "Process not started!");
310 return -1;
311 }
312
Daniel Dunbar57d69032009-09-22 04:44:56 +0000313 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000314
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000315 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000316 DWORD millisecondsToWait = INFINITE;
317 if (secondsToWait > 0)
318 millisecondsToWait = secondsToWait * 1000;
319
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000320 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
321 if (!TerminateProcess(hProcess, 1)) {
322 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000323 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000324 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000325 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000326 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000327
Reid Spencerb016a372004-09-15 05:49:50 +0000328 // Get its exit status.
329 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000330 BOOL rc = GetExitCodeProcess(hProcess, &status);
331 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000332
Jeff Cohen875d08e2005-02-20 02:43:04 +0000333 if (!rc) {
334 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000335 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000336 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000337 }
Reid Spencerb016a372004-09-15 05:49:50 +0000338
339 return status;
340}
341
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000342bool
343Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000344 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000345 MakeErrMsg(ErrMsg, "Process not started!");
346 return true;
347 }
348
Daniel Dunbar57d69032009-09-22 04:44:56 +0000349 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000350 if (TerminateProcess(hProcess, 1) == 0) {
351 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
352 return true;
353 }
354
355 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000356}
357
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000358bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000359 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000360 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000361}
362
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000363bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000364 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000365 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000366}
367
Reid Spencerb016a372004-09-15 05:49:50 +0000368}