blob: 691d6d45550123b7ee6a9f76d38b4fa30d453d22 [file] [log] [blame]
Reid Spencerb88212e2004-09-15 05:49:50 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +00002//
Reid Spencer76b83a12004-08-29 19:20:41 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Glushenkov3a62efb2009-04-14 21:31:14 +00007//
Reid Spencer76b83a12004-08-29 19:20:41 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
Michael J. Spencer447762d2010-11-29 18:16:10 +000014#include "Windows.h"
Reid Spencerab97f222006-06-07 23:18:34 +000015#include <cstdio>
Reid Spencerab97f222006-06-07 23:18:34 +000016#include <fcntl.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include <io.h>
18#include <malloc.h>
Reid Spencerb88212e2004-09-15 05:49:50 +000019
Reid Spencer76b83a12004-08-29 19:20:41 +000020//===----------------------------------------------------------------------===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000021//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb88212e2004-09-15 05:49:50 +000022//=== and must not be UNIX code
Reid Spencer76b83a12004-08-29 19:20:41 +000023//===----------------------------------------------------------------------===//
24
Mikhail Glushenkov88e98fe2009-09-22 15:40:32 +000025namespace {
26 struct Win32ProcessInfo {
27 HANDLE hProcess;
28 DWORD dwProcessId;
29 };
30}
31
Reid Spencerb88212e2004-09-15 05:49:50 +000032namespace llvm {
33using namespace sys;
34
Daniel Dunbar7b446a02009-09-22 04:44:56 +000035Program::Program() : Data_(0) {}
36
37Program::~Program() {
38 if (Data_) {
Mikhail Glushenkov88e98fe2009-09-22 15:40:32 +000039 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
40 CloseHandle(wpi->hProcess);
41 delete wpi;
Daniel Dunbar7b446a02009-09-22 04:44:56 +000042 Data_ = 0;
43 }
44}
45
Reid Spencerb88212e2004-09-15 05:49:50 +000046// This function just uses the PATH environment variable to find the program.
47Path
48Program::FindProgramByName(const std::string& progName) {
49
50 // Check some degenerate cases
51 if (progName.length() == 0) // no program
52 return Path();
53 Path temp;
Jeff Cohen215db902005-07-08 02:48:42 +000054 if (!temp.set(progName)) // invalid name
Reid Spencerb88212e2004-09-15 05:49:50 +000055 return Path();
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000056 // Return paths with slashes verbatim.
57 if (progName.find('\\') != std::string::npos ||
58 progName.find('/') != std::string::npos)
Reid Spencerb88212e2004-09-15 05:49:50 +000059 return temp;
60
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000061 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb88212e2004-09-15 05:49:50 +000062 // Let Windows search for it.
63 char buffer[MAX_PATH];
64 char *dummy = NULL;
65 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
66 buffer, &dummy);
67
68 // See if it wasn't found.
69 if (len == 0)
70 return Path();
71
72 // See if we got the entire path.
73 if (len < MAX_PATH)
74 return Path(buffer);
75
76 // Buffer was too small; grow and retry.
77 while (true) {
78 char *b = reinterpret_cast<char *>(_alloca(len+1));
79 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
80
81 // It is unlikely the search failed, but it's always possible some file
82 // was added or removed since the last search, so be paranoid...
83 if (len2 == 0)
84 return Path();
85 else if (len2 <= len)
86 return Path(b);
87
88 len = len2;
89 }
90}
91
Reid Spencer42bcf6e2006-08-21 06:02:44 +000092static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +000093 HANDLE h;
94 if (path == 0) {
95 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
96 GetCurrentProcess(), &h,
97 0, TRUE, DUPLICATE_SAME_ACCESS);
98 return h;
99 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000100
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000101 const char *fname;
102 if (path->isEmpty())
Jeff Cohen4220bf52005-02-20 02:43:04 +0000103 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000104 else
Chris Lattnerc521f542009-08-23 22:45:37 +0000105 fname = path->c_str();
Jeff Cohen4220bf52005-02-20 02:43:04 +0000106
107 SECURITY_ATTRIBUTES sa;
108 sa.nLength = sizeof(sa);
109 sa.lpSecurityDescriptor = 0;
110 sa.bInheritHandle = TRUE;
111
112 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen18cf7eb2005-02-20 02:48:51 +0000113 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen4220bf52005-02-20 02:43:04 +0000114 FILE_ATTRIBUTE_NORMAL, NULL);
115 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000116 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000117 (fd ? "input: " : "output: "));
118 }
Jeff Cohena531d042007-03-05 05:22:08 +0000119
Jeff Cohen4220bf52005-02-20 02:43:04 +0000120 return h;
121}
122
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000123/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
124/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000125static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000126 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000127}
128
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000129
130/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
131/// CreateProcess and returns length of quoted arg with escaped quotes
132static unsigned int ArgLenWithQuotes(const char *Str) {
133 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
134
135 while (*Str != '\0') {
136 if (*Str == '\"')
137 ++len;
138
139 ++len;
140 ++Str;
141 }
142
143 return len;
144}
145
146
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000147bool
148Program::Execute(const Path& path,
149 const char** args,
150 const char** envp,
151 const Path** redirects,
152 unsigned memoryLimit,
153 std::string* ErrMsg) {
Daniel Dunbar7b446a02009-09-22 04:44:56 +0000154 if (Data_) {
Mikhail Glushenkov88e98fe2009-09-22 15:40:32 +0000155 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
156 CloseHandle(wpi->hProcess);
157 delete wpi;
Daniel Dunbar7b446a02009-09-22 04:44:56 +0000158 Data_ = 0;
159 }
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000160
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000161 if (!path.canExecute()) {
162 if (ErrMsg)
163 *ErrMsg = "program not executable";
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000164 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000165 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000166
167 // Windows wants a command line, not an array of args, to pass to the new
168 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000169 // have embedded spaces (or are empty).
Reid Spencerb88212e2004-09-15 05:49:50 +0000170
171 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000172 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000173 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000174 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000175 }
176
177 // Now build the command line.
Anton Korobeynikova4f27602008-01-24 01:20:48 +0000178 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb88212e2004-09-15 05:49:50 +0000179 char *p = command;
180
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000181 for (unsigned i = 0; args[i]; i++) {
182 const char *arg = args[i];
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000183
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000184 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000185 if (needsQuoting)
186 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000187
188 while (*arg != '\0') {
189 if (*arg == '\"')
190 *p++ = '\\';
191
192 *p++ = *arg++;
193 }
194
Reid Spencerb88212e2004-09-15 05:49:50 +0000195 if (needsQuoting)
196 *p++ = '"';
197 *p++ = ' ';
198 }
199
200 *p = 0;
201
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000202 // The pointer to the environment block for the new process.
203 char *envblock = 0;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000204
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000205 if (envp) {
206 // An environment block consists of a null-terminated block of
207 // null-terminated strings. Convert the array of environment variables to
208 // an environment block by concatenating them.
209
210 // First, determine the length of the environment block.
211 len = 0;
212 for (unsigned i = 0; envp[i]; i++)
213 len += strlen(envp[i]) + 1;
214
215 // Now build the environment block.
216 envblock = reinterpret_cast<char *>(_alloca(len+1));
217 p = envblock;
218
219 for (unsigned i = 0; envp[i]; i++) {
220 const char *ev = envp[i];
221 size_t len = strlen(ev) + 1;
222 memcpy(p, ev, len);
223 p += len;
224 }
225
226 *p = 0;
227 }
228
Reid Spencerb88212e2004-09-15 05:49:50 +0000229 // Create a child process.
230 STARTUPINFO si;
231 memset(&si, 0, sizeof(si));
232 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000233 si.hStdInput = INVALID_HANDLE_VALUE;
234 si.hStdOutput = INVALID_HANDLE_VALUE;
235 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000236
Jeff Cohen4220bf52005-02-20 02:43:04 +0000237 if (redirects) {
238 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000239
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000240 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
241 if (si.hStdInput == INVALID_HANDLE_VALUE) {
242 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000243 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000244 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000245 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000246 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000247 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000248 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000249 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000250 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000251 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
252 // If stdout and stderr should go to the same place, redirect stderr
253 // to the handle already open for stdout.
254 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
255 GetCurrentProcess(), &si.hStdError,
256 0, TRUE, DUPLICATE_SAME_ACCESS);
257 } else {
258 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000259 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000260 if (si.hStdError == INVALID_HANDLE_VALUE) {
261 CloseHandle(si.hStdInput);
262 CloseHandle(si.hStdOutput);
263 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000264 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000265 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000266 }
267 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000268
Reid Spencerb88212e2004-09-15 05:49:50 +0000269 PROCESS_INFORMATION pi;
270 memset(&pi, 0, sizeof(pi));
271
Jeff Cohen4220bf52005-02-20 02:43:04 +0000272 fflush(stdout);
273 fflush(stderr);
Mikhail Glushenkov60cde5b2009-04-14 21:31:36 +0000274 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000275 envblock, NULL, &si, &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000276 DWORD err = GetLastError();
277
278 // Regardless of whether the process got created or not, we are done with
279 // the handles we created for it to inherit.
280 CloseHandle(si.hStdInput);
281 CloseHandle(si.hStdOutput);
282 CloseHandle(si.hStdError);
283
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000284 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000285 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000286 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000287 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattnerc521f542009-08-23 22:45:37 +0000288 path.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000289 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000290 }
Mikhail Glushenkov88e98fe2009-09-22 15:40:32 +0000291 Win32ProcessInfo* wpi = new Win32ProcessInfo;
292 wpi->hProcess = pi.hProcess;
293 wpi->dwProcessId = pi.dwProcessId;
294 Data_ = wpi;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000295
Jeff Cohena531d042007-03-05 05:22:08 +0000296 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000297 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000298
299 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000300 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000301 if (memoryLimit != 0) {
302 hJob = CreateJobObject(0, 0);
303 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000304 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000305 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
306 memset(&jeli, 0, sizeof(jeli));
307 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000308 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000309 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
310 &jeli, sizeof(jeli))) {
311 if (AssignProcessToJobObject(hJob, pi.hProcess))
312 success = true;
313 }
314 }
315 if (!success) {
316 SetLastError(GetLastError());
317 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
318 TerminateProcess(pi.hProcess, 1);
319 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000320 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000321 }
322 }
323
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000324 return true;
325}
326
327int
Dan Gohmanfc815792010-10-29 16:54:25 +0000328Program::Wait(const Path &path,
329 unsigned secondsToWait,
Andrew Trickd5d07642011-05-21 00:56:46 +0000330 std::string* ErrMsg) {
Daniel Dunbar7b446a02009-09-22 04:44:56 +0000331 if (Data_ == 0) {
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000332 MakeErrMsg(ErrMsg, "Process not started!");
333 return -1;
334 }
335
Mikhail Glushenkov88e98fe2009-09-22 15:40:32 +0000336 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
337 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000338
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000339 // Wait for the process to terminate.
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000340 DWORD millisecondsToWait = INFINITE;
341 if (secondsToWait > 0)
342 millisecondsToWait = secondsToWait * 1000;
343
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000344 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
345 if (!TerminateProcess(hProcess, 1)) {
346 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Andrew Trickd5d07642011-05-21 00:56:46 +0000347 // -2 indicates a crash or timeout as opposed to failure to execute.
348 return -2;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000349 }
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000350 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000351 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000352
Reid Spencerb88212e2004-09-15 05:49:50 +0000353 // Get its exit status.
354 DWORD status;
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000355 BOOL rc = GetExitCodeProcess(hProcess, &status);
356 DWORD err = GetLastError();
Reid Spencerb88212e2004-09-15 05:49:50 +0000357
Jeff Cohen4220bf52005-02-20 02:43:04 +0000358 if (!rc) {
359 SetLastError(err);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000360 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Andrew Trickd5d07642011-05-21 00:56:46 +0000361 // -2 indicates a crash or timeout as opposed to failure to execute.
362 return -2;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000363 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000364
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000365 if (!status)
366 return 0;
367
368 // Pass 10(Warning) and 11(Error) to the callee as negative value.
369 if ((status & 0xBFFF0000U) == 0x80000000U)
370 return (int)status;
371
372 if (status & 0xFF)
373 return status & 0x7FFFFFFF;
374
375 return 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000376}
377
Michael J. Spencera2755f82011-12-13 23:16:49 +0000378error_code Program::ChangeStdinToBinary(){
Reid Spencerab97f222006-06-07 23:18:34 +0000379 int result = _setmode( _fileno(stdin), _O_BINARY );
Michael J. Spencera2755f82011-12-13 23:16:49 +0000380 if (result == -1)
381 return error_code(errno, generic_category());
382 return make_error_code(errc::success);
Reid Spencerab97f222006-06-07 23:18:34 +0000383}
384
Michael J. Spencera2755f82011-12-13 23:16:49 +0000385error_code Program::ChangeStdoutToBinary(){
Reid Spencerab97f222006-06-07 23:18:34 +0000386 int result = _setmode( _fileno(stdout), _O_BINARY );
Michael J. Spencera2755f82011-12-13 23:16:49 +0000387 if (result == -1)
388 return error_code(errno, generic_category());
389 return make_error_code(errc::success);
Reid Spencerab97f222006-06-07 23:18:34 +0000390}
391
Michael J. Spencera2755f82011-12-13 23:16:49 +0000392error_code Program::ChangeStderrToBinary(){
Douglas Gregor10519372010-01-28 06:42:08 +0000393 int result = _setmode( _fileno(stderr), _O_BINARY );
Michael J. Spencera2755f82011-12-13 23:16:49 +0000394 if (result == -1)
395 return error_code(errno, generic_category());
396 return make_error_code(errc::success);
Douglas Gregor10519372010-01-28 06:42:08 +0000397}
398
Reid Spencerb88212e2004-09-15 05:49:50 +0000399}