blob: a69826fdcef4cb5995e0d90e4bcb85f61578b489 [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
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();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000061 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000062 return temp;
63
64 // At this point, the file name is valid and its not executable.
65 // Let Windows search for it.
66 char buffer[MAX_PATH];
67 char *dummy = NULL;
68 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
69 buffer, &dummy);
70
71 // See if it wasn't found.
72 if (len == 0)
73 return Path();
74
75 // See if we got the entire path.
76 if (len < MAX_PATH)
77 return Path(buffer);
78
79 // Buffer was too small; grow and retry.
80 while (true) {
81 char *b = reinterpret_cast<char *>(_alloca(len+1));
82 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
83
84 // It is unlikely the search failed, but it's always possible some file
85 // was added or removed since the last search, so be paranoid...
86 if (len2 == 0)
87 return Path();
88 else if (len2 <= len)
89 return Path(b);
90
91 len = len2;
92 }
93}
94
Reid Spencer4ce5dc62006-08-21 06:02:44 +000095static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +000096 HANDLE h;
97 if (path == 0) {
98 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
99 GetCurrentProcess(), &h,
100 0, TRUE, DUPLICATE_SAME_ACCESS);
101 return h;
102 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000103
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000104 const char *fname;
105 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +0000106 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000107 else
Chris Lattner74382b72009-08-23 22:45:37 +0000108 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +0000109
110 SECURITY_ATTRIBUTES sa;
111 sa.nLength = sizeof(sa);
112 sa.lpSecurityDescriptor = 0;
113 sa.bInheritHandle = TRUE;
114
115 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000116 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000117 FILE_ATTRIBUTE_NORMAL, NULL);
118 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000119 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000120 (fd ? "input: " : "output: "));
121 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000122
Jeff Cohen875d08e2005-02-20 02:43:04 +0000123 return h;
124}
125
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000126#ifdef __MINGW32__
127 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
Anton Korobeynikovd437db12007-03-19 20:19:08 +0000128 extern "C"
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000129 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
130 JOBOBJECTINFOCLASS JobObjectInfoClass,
131 LPVOID lpJobObjectInfo,
132 DWORD cbJobObjectInfoLength);
133#endif
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000134
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
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000141bool
142Program::Execute(const Path& path,
143 const char** args,
144 const char** envp,
145 const Path** redirects,
146 unsigned memoryLimit,
147 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000148 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000149 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
150 CloseHandle(wpi->hProcess);
151 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000152 Data_ = 0;
153 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000154
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000155 if (!path.canExecute()) {
156 if (ErrMsg)
157 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000158 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000159 }
Reid Spencerb016a372004-09-15 05:49:50 +0000160
161 // Windows wants a command line, not an array of args, to pass to the new
162 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000163 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000164
165 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000166 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000167 for (unsigned i = 0; args[i]; i++) {
168 len += strlen(args[i]) + 1;
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000169 if (ArgNeedsQuotes(args[i]))
Reid Spencerb016a372004-09-15 05:49:50 +0000170 len += 2;
171 }
172
173 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000174 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000175 char *p = command;
176
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000177 for (unsigned i = 0; args[i]; i++) {
178 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000179 size_t len = strlen(arg);
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000180 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000181 if (needsQuoting)
182 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000183 memcpy(p, arg, len);
184 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000185 if (needsQuoting)
186 *p++ = '"';
187 *p++ = ' ';
188 }
189
190 *p = 0;
191
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000192 // The pointer to the environment block for the new process.
193 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000194
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000195 if (envp) {
196 // An environment block consists of a null-terminated block of
197 // null-terminated strings. Convert the array of environment variables to
198 // an environment block by concatenating them.
199
200 // First, determine the length of the environment block.
201 len = 0;
202 for (unsigned i = 0; envp[i]; i++)
203 len += strlen(envp[i]) + 1;
204
205 // Now build the environment block.
206 envblock = reinterpret_cast<char *>(_alloca(len+1));
207 p = envblock;
208
209 for (unsigned i = 0; envp[i]; i++) {
210 const char *ev = envp[i];
211 size_t len = strlen(ev) + 1;
212 memcpy(p, ev, len);
213 p += len;
214 }
215
216 *p = 0;
217 }
218
Reid Spencerb016a372004-09-15 05:49:50 +0000219 // Create a child process.
220 STARTUPINFO si;
221 memset(&si, 0, sizeof(si));
222 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000223 si.hStdInput = INVALID_HANDLE_VALUE;
224 si.hStdOutput = INVALID_HANDLE_VALUE;
225 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000226
Jeff Cohen875d08e2005-02-20 02:43:04 +0000227 if (redirects) {
228 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000229
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000230 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
231 if (si.hStdInput == INVALID_HANDLE_VALUE) {
232 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000233 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000234 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000235 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000236 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000237 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000238 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000239 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000240 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000241 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
242 // If stdout and stderr should go to the same place, redirect stderr
243 // to the handle already open for stdout.
244 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
245 GetCurrentProcess(), &si.hStdError,
246 0, TRUE, DUPLICATE_SAME_ACCESS);
247 } else {
248 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000249 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000250 if (si.hStdError == INVALID_HANDLE_VALUE) {
251 CloseHandle(si.hStdInput);
252 CloseHandle(si.hStdOutput);
253 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000254 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000255 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000256 }
257 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000258
Reid Spencerb016a372004-09-15 05:49:50 +0000259 PROCESS_INFORMATION pi;
260 memset(&pi, 0, sizeof(pi));
261
Jeff Cohen875d08e2005-02-20 02:43:04 +0000262 fflush(stdout);
263 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000264 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000265 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000266 DWORD err = GetLastError();
267
268 // Regardless of whether the process got created or not, we are done with
269 // the handles we created for it to inherit.
270 CloseHandle(si.hStdInput);
271 CloseHandle(si.hStdOutput);
272 CloseHandle(si.hStdError);
273
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000274 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000275 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000276 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000277 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000278 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000279 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000280 }
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000281 Win32ProcessInfo* wpi = new Win32ProcessInfo;
282 wpi->hProcess = pi.hProcess;
283 wpi->dwProcessId = pi.dwProcessId;
284 Data_ = wpi;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000285
Jeff Cohen0a182672007-03-05 05:22:08 +0000286 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000287 AutoHandle hThread(pi.hThread);
288
289 // Assign the process to a job if a memory limit is defined.
290 AutoHandle hJob(0);
291 if (memoryLimit != 0) {
292 hJob = CreateJobObject(0, 0);
293 bool success = false;
294 if (hJob != 0) {
295 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
296 memset(&jeli, 0, sizeof(jeli));
297 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000298 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000299 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
300 &jeli, sizeof(jeli))) {
301 if (AssignProcessToJobObject(hJob, pi.hProcess))
302 success = true;
303 }
304 }
305 if (!success) {
306 SetLastError(GetLastError());
307 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
308 TerminateProcess(pi.hProcess, 1);
309 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000310 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000311 }
312 }
313
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000314 return true;
315}
316
317int
318Program::Wait(unsigned secondsToWait,
319 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000320 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000321 MakeErrMsg(ErrMsg, "Process not started!");
322 return -1;
323 }
324
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000325 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
326 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000327
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000328 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000329 DWORD millisecondsToWait = INFINITE;
330 if (secondsToWait > 0)
331 millisecondsToWait = secondsToWait * 1000;
332
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000333 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
334 if (!TerminateProcess(hProcess, 1)) {
335 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000336 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000337 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000338 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000339 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000340
Reid Spencerb016a372004-09-15 05:49:50 +0000341 // Get its exit status.
342 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000343 BOOL rc = GetExitCodeProcess(hProcess, &status);
344 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000345
Jeff Cohen875d08e2005-02-20 02:43:04 +0000346 if (!rc) {
347 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000348 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000349 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000350 }
Reid Spencerb016a372004-09-15 05:49:50 +0000351
352 return status;
353}
354
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000355bool
356Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000357 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000358 MakeErrMsg(ErrMsg, "Process not started!");
359 return true;
360 }
361
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000362 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
363 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000364 if (TerminateProcess(hProcess, 1) == 0) {
365 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
366 return true;
367 }
368
369 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000370}
371
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000372bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000373 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000374 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000375}
376
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000377bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000378 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000379 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000380}
381
Reid Spencerb016a372004-09-15 05:49:50 +0000382}