blob: 4f4b6b32b1d4eb6c45114bd671298027901a737e [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 Dunbardefc8532009-08-03 05:02:46 +000028Program::Program() : Pid_(0), Data(0) {}
29
30Program::~Program() {
Mikhail Glushenkova6072022009-09-08 19:50:27 +000031 if (Data) {
32 HANDLE hProcess = (HANDLE) Data;
33 CloseHandle(hProcess);
34 Data = 0;
35 }
Daniel Dunbardefc8532009-08-03 05:02:46 +000036}
37
Reid Spencerb016a372004-09-15 05:49:50 +000038// This function just uses the PATH environment variable to find the program.
39Path
40Program::FindProgramByName(const std::string& progName) {
41
42 // Check some degenerate cases
43 if (progName.length() == 0) // no program
44 return Path();
45 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000046 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000047 return Path();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000048 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000049 return temp;
50
51 // At this point, the file name is valid and its not executable.
52 // Let Windows search for it.
53 char buffer[MAX_PATH];
54 char *dummy = NULL;
55 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
56 buffer, &dummy);
57
58 // See if it wasn't found.
59 if (len == 0)
60 return Path();
61
62 // See if we got the entire path.
63 if (len < MAX_PATH)
64 return Path(buffer);
65
66 // Buffer was too small; grow and retry.
67 while (true) {
68 char *b = reinterpret_cast<char *>(_alloca(len+1));
69 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
70
71 // It is unlikely the search failed, but it's always possible some file
72 // was added or removed since the last search, so be paranoid...
73 if (len2 == 0)
74 return Path();
75 else if (len2 <= len)
76 return Path(b);
77
78 len = len2;
79 }
80}
81
Reid Spencer4ce5dc62006-08-21 06:02:44 +000082static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +000083 HANDLE h;
84 if (path == 0) {
85 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
86 GetCurrentProcess(), &h,
87 0, TRUE, DUPLICATE_SAME_ACCESS);
88 return h;
89 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +000090
Matthijs Kooijman905261e2008-06-12 10:47:18 +000091 const char *fname;
92 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +000093 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +000094 else
Chris Lattner74382b72009-08-23 22:45:37 +000095 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +000096
97 SECURITY_ATTRIBUTES sa;
98 sa.nLength = sizeof(sa);
99 sa.lpSecurityDescriptor = 0;
100 sa.bInheritHandle = TRUE;
101
102 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000103 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000104 FILE_ATTRIBUTE_NORMAL, NULL);
105 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000106 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000107 (fd ? "input: " : "output: "));
108 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000109
Jeff Cohen875d08e2005-02-20 02:43:04 +0000110 return h;
111}
112
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000113#ifdef __MINGW32__
114 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
Anton Korobeynikovd437db12007-03-19 20:19:08 +0000115 extern "C"
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000116 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
117 JOBOBJECTINFOCLASS JobObjectInfoClass,
118 LPVOID lpJobObjectInfo,
119 DWORD cbJobObjectInfoLength);
120#endif
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000121
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000122/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
123/// CreateProcess.
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000124static bool ArgNeedsQuotes(const char *Str) {
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000125 return Str[0] == '\0' || strchr(Str, ' ') != 0;
126}
127
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000128bool
129Program::Execute(const Path& path,
130 const char** args,
131 const char** envp,
132 const Path** redirects,
133 unsigned memoryLimit,
134 std::string* ErrMsg) {
Daniel Dunbardefc8532009-08-03 05:02:46 +0000135 if (Data) {
136 HANDLE hProcess = (HANDLE) Data;
137 CloseHandle(Data);
138 Data = 0;
139 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000140
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000141 if (!path.canExecute()) {
142 if (ErrMsg)
143 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000144 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000145 }
Reid Spencerb016a372004-09-15 05:49:50 +0000146
147 // Windows wants a command line, not an array of args, to pass to the new
148 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000149 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000150
151 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000152 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000153 for (unsigned i = 0; args[i]; i++) {
154 len += strlen(args[i]) + 1;
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000155 if (ArgNeedsQuotes(args[i]))
Reid Spencerb016a372004-09-15 05:49:50 +0000156 len += 2;
157 }
158
159 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000160 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000161 char *p = command;
162
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000163 for (unsigned i = 0; args[i]; i++) {
164 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000165 size_t len = strlen(arg);
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000166 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000167 if (needsQuoting)
168 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000169 memcpy(p, arg, len);
170 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000171 if (needsQuoting)
172 *p++ = '"';
173 *p++ = ' ';
174 }
175
176 *p = 0;
177
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000178 // The pointer to the environment block for the new process.
179 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000180
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000181 if (envp) {
182 // An environment block consists of a null-terminated block of
183 // null-terminated strings. Convert the array of environment variables to
184 // an environment block by concatenating them.
185
186 // First, determine the length of the environment block.
187 len = 0;
188 for (unsigned i = 0; envp[i]; i++)
189 len += strlen(envp[i]) + 1;
190
191 // Now build the environment block.
192 envblock = reinterpret_cast<char *>(_alloca(len+1));
193 p = envblock;
194
195 for (unsigned i = 0; envp[i]; i++) {
196 const char *ev = envp[i];
197 size_t len = strlen(ev) + 1;
198 memcpy(p, ev, len);
199 p += len;
200 }
201
202 *p = 0;
203 }
204
Reid Spencerb016a372004-09-15 05:49:50 +0000205 // Create a child process.
206 STARTUPINFO si;
207 memset(&si, 0, sizeof(si));
208 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000209 si.hStdInput = INVALID_HANDLE_VALUE;
210 si.hStdOutput = INVALID_HANDLE_VALUE;
211 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000212
Jeff Cohen875d08e2005-02-20 02:43:04 +0000213 if (redirects) {
214 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000215
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000216 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
217 if (si.hStdInput == INVALID_HANDLE_VALUE) {
218 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000219 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000220 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000221 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000222 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000223 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000224 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000225 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000226 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000227 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
228 // If stdout and stderr should go to the same place, redirect stderr
229 // to the handle already open for stdout.
230 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
231 GetCurrentProcess(), &si.hStdError,
232 0, TRUE, DUPLICATE_SAME_ACCESS);
233 } else {
234 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000235 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000236 if (si.hStdError == INVALID_HANDLE_VALUE) {
237 CloseHandle(si.hStdInput);
238 CloseHandle(si.hStdOutput);
239 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000240 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000241 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000242 }
243 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000244
Reid Spencerb016a372004-09-15 05:49:50 +0000245 PROCESS_INFORMATION pi;
246 memset(&pi, 0, sizeof(pi));
247
Jeff Cohen875d08e2005-02-20 02:43:04 +0000248 fflush(stdout);
249 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000250 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000251 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000252 DWORD err = GetLastError();
253
254 // Regardless of whether the process got created or not, we are done with
255 // the handles we created for it to inherit.
256 CloseHandle(si.hStdInput);
257 CloseHandle(si.hStdOutput);
258 CloseHandle(si.hStdError);
259
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000260 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000261 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000262 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000263 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000264 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000265 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000266 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000267 Pid_ = pi.dwProcessId;
Daniel Dunbardefc8532009-08-03 05:02:46 +0000268 Data = pi.hProcess;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000269
Jeff Cohen0a182672007-03-05 05:22:08 +0000270 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000271 AutoHandle hThread(pi.hThread);
272
273 // Assign the process to a job if a memory limit is defined.
274 AutoHandle hJob(0);
275 if (memoryLimit != 0) {
276 hJob = CreateJobObject(0, 0);
277 bool success = false;
278 if (hJob != 0) {
279 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
280 memset(&jeli, 0, sizeof(jeli));
281 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000282 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000283 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
284 &jeli, sizeof(jeli))) {
285 if (AssignProcessToJobObject(hJob, pi.hProcess))
286 success = true;
287 }
288 }
289 if (!success) {
290 SetLastError(GetLastError());
291 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
292 TerminateProcess(pi.hProcess, 1);
293 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000294 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000295 }
296 }
297
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000298 return true;
299}
300
301int
302Program::Wait(unsigned secondsToWait,
303 std::string* ErrMsg) {
Daniel Dunbardefc8532009-08-03 05:02:46 +0000304 if (Data == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000305 MakeErrMsg(ErrMsg, "Process not started!");
306 return -1;
307 }
308
Daniel Dunbardefc8532009-08-03 05:02:46 +0000309 HANDLE hProcess = (HANDLE) Data;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000310
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000311 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000312 DWORD millisecondsToWait = INFINITE;
313 if (secondsToWait > 0)
314 millisecondsToWait = secondsToWait * 1000;
315
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000316 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
317 if (!TerminateProcess(hProcess, 1)) {
318 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000319 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000320 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000321 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000322 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000323
Reid Spencerb016a372004-09-15 05:49:50 +0000324 // Get its exit status.
325 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000326 BOOL rc = GetExitCodeProcess(hProcess, &status);
327 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000328
Jeff Cohen875d08e2005-02-20 02:43:04 +0000329 if (!rc) {
330 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000331 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000332 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000333 }
Reid Spencerb016a372004-09-15 05:49:50 +0000334
335 return status;
336}
337
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000338bool
339Program::Kill(std::string* ErrMsg) {
340 if (Data == 0) {
341 MakeErrMsg(ErrMsg, "Process not started!");
342 return true;
343 }
344
345 HANDLE hProcess = reinterpret_cast<HANDLE>(Data);
346 return TerminateProcess(hProcess, 1);
347}
348
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000349bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000350 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000351 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000352}
353
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000354bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000355 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000356 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000357}
358
Reid Spencerb016a372004-09-15 05:49:50 +0000359}