blob: 2d6e665377e01a230aff012b849bdad3eb0a4b38 [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();
Mikhail Glushenkov9cd59712010-11-02 20:32:39 +000070 // Return paths with slashes verbatim.
71 if (progName.find('\\') != std::string::npos ||
72 progName.find('/') != std::string::npos)
Reid Spencerb016a372004-09-15 05:49:50 +000073 return temp;
74
Mikhail Glushenkov9cd59712010-11-02 20:32:39 +000075 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb016a372004-09-15 05:49:50 +000076 // Let Windows search for it.
77 char buffer[MAX_PATH];
78 char *dummy = NULL;
79 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
80 buffer, &dummy);
81
82 // See if it wasn't found.
83 if (len == 0)
84 return Path();
85
86 // See if we got the entire path.
87 if (len < MAX_PATH)
88 return Path(buffer);
89
90 // Buffer was too small; grow and retry.
91 while (true) {
92 char *b = reinterpret_cast<char *>(_alloca(len+1));
93 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
94
95 // It is unlikely the search failed, but it's always possible some file
96 // was added or removed since the last search, so be paranoid...
97 if (len2 == 0)
98 return Path();
99 else if (len2 <= len)
100 return Path(b);
101
102 len = len2;
103 }
104}
105
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000106static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000107 HANDLE h;
108 if (path == 0) {
109 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
110 GetCurrentProcess(), &h,
111 0, TRUE, DUPLICATE_SAME_ACCESS);
112 return h;
113 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000114
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000115 const char *fname;
116 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +0000117 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000118 else
Chris Lattner74382b72009-08-23 22:45:37 +0000119 fname = path->c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +0000120
121 SECURITY_ATTRIBUTES sa;
122 sa.nLength = sizeof(sa);
123 sa.lpSecurityDescriptor = 0;
124 sa.bInheritHandle = TRUE;
125
126 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +0000127 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +0000128 FILE_ATTRIBUTE_NORMAL, NULL);
129 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000130 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +0000131 (fd ? "input: " : "output: "));
132 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000133
Jeff Cohen875d08e2005-02-20 02:43:04 +0000134 return h;
135}
136
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000137/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
138/// CreateProcess.
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000139static bool ArgNeedsQuotes(const char *Str) {
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000140 return Str[0] == '\0' || strchr(Str, ' ') != 0;
141}
142
Anton Korobeynikov81244292010-03-28 15:07:02 +0000143
144/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
145/// CreateProcess and returns length of quoted arg with escaped quotes
146static unsigned int ArgLenWithQuotes(const char *Str) {
147 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
148
149 while (*Str != '\0') {
150 if (*Str == '\"')
151 ++len;
152
153 ++len;
154 ++Str;
155 }
156
157 return len;
158}
159
160
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000161bool
162Program::Execute(const Path& path,
163 const char** args,
164 const char** envp,
165 const Path** redirects,
166 unsigned memoryLimit,
167 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000168 if (Data_) {
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000169 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
170 CloseHandle(wpi->hProcess);
171 delete wpi;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000172 Data_ = 0;
173 }
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000174
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000175 if (!path.canExecute()) {
176 if (ErrMsg)
177 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000178 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000179 }
Reid Spencerb016a372004-09-15 05:49:50 +0000180
181 // Windows wants a command line, not an array of args, to pass to the new
182 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000183 // have embedded spaces (or are empty).
Reid Spencerb016a372004-09-15 05:49:50 +0000184
185 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000186 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000187 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikov81244292010-03-28 15:07:02 +0000188 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb016a372004-09-15 05:49:50 +0000189 }
190
191 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000192 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000193 char *p = command;
194
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000195 for (unsigned i = 0; args[i]; i++) {
196 const char *arg = args[i];
Anton Korobeynikov81244292010-03-28 15:07:02 +0000197
Daniel Dunbar9a0b5742009-08-02 20:41:09 +0000198 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb016a372004-09-15 05:49:50 +0000199 if (needsQuoting)
200 *p++ = '"';
Anton Korobeynikov81244292010-03-28 15:07:02 +0000201
202 while (*arg != '\0') {
203 if (*arg == '\"')
204 *p++ = '\\';
205
206 *p++ = *arg++;
207 }
208
Reid Spencerb016a372004-09-15 05:49:50 +0000209 if (needsQuoting)
210 *p++ = '"';
211 *p++ = ' ';
212 }
213
214 *p = 0;
215
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000216 // The pointer to the environment block for the new process.
217 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000218
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000219 if (envp) {
220 // An environment block consists of a null-terminated block of
221 // null-terminated strings. Convert the array of environment variables to
222 // an environment block by concatenating them.
223
224 // First, determine the length of the environment block.
225 len = 0;
226 for (unsigned i = 0; envp[i]; i++)
227 len += strlen(envp[i]) + 1;
228
229 // Now build the environment block.
230 envblock = reinterpret_cast<char *>(_alloca(len+1));
231 p = envblock;
232
233 for (unsigned i = 0; envp[i]; i++) {
234 const char *ev = envp[i];
235 size_t len = strlen(ev) + 1;
236 memcpy(p, ev, len);
237 p += len;
238 }
239
240 *p = 0;
241 }
242
Reid Spencerb016a372004-09-15 05:49:50 +0000243 // Create a child process.
244 STARTUPINFO si;
245 memset(&si, 0, sizeof(si));
246 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000247 si.hStdInput = INVALID_HANDLE_VALUE;
248 si.hStdOutput = INVALID_HANDLE_VALUE;
249 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000250
Jeff Cohen875d08e2005-02-20 02:43:04 +0000251 if (redirects) {
252 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000253
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000254 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
255 if (si.hStdInput == INVALID_HANDLE_VALUE) {
256 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000257 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000258 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000259 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000260 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000261 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000262 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000263 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000264 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000265 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
266 // If stdout and stderr should go to the same place, redirect stderr
267 // to the handle already open for stdout.
268 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
269 GetCurrentProcess(), &si.hStdError,
270 0, TRUE, DUPLICATE_SAME_ACCESS);
271 } else {
272 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000273 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000274 if (si.hStdError == INVALID_HANDLE_VALUE) {
275 CloseHandle(si.hStdInput);
276 CloseHandle(si.hStdOutput);
277 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000278 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000279 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000280 }
281 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000282
Reid Spencerb016a372004-09-15 05:49:50 +0000283 PROCESS_INFORMATION pi;
284 memset(&pi, 0, sizeof(pi));
285
Jeff Cohen875d08e2005-02-20 02:43:04 +0000286 fflush(stdout);
287 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000288 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000289 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000290 DWORD err = GetLastError();
291
292 // Regardless of whether the process got created or not, we are done with
293 // the handles we created for it to inherit.
294 CloseHandle(si.hStdInput);
295 CloseHandle(si.hStdOutput);
296 CloseHandle(si.hStdError);
297
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000298 // Now return an error if the process didn't get created.
Chris Lattner74382b72009-08-23 22:45:37 +0000299 if (!rc) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000300 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000301 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattner74382b72009-08-23 22:45:37 +0000302 path.str() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000303 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000304 }
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000305 Win32ProcessInfo* wpi = new Win32ProcessInfo;
306 wpi->hProcess = pi.hProcess;
307 wpi->dwProcessId = pi.dwProcessId;
308 Data_ = wpi;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000309
Jeff Cohen0a182672007-03-05 05:22:08 +0000310 // Make sure these get closed no matter what.
Jeff Cohen0a182672007-03-05 05:22:08 +0000311 AutoHandle hThread(pi.hThread);
312
313 // Assign the process to a job if a memory limit is defined.
314 AutoHandle hJob(0);
315 if (memoryLimit != 0) {
316 hJob = CreateJobObject(0, 0);
317 bool success = false;
318 if (hJob != 0) {
319 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
320 memset(&jeli, 0, sizeof(jeli));
321 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000322 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000323 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
324 &jeli, sizeof(jeli))) {
325 if (AssignProcessToJobObject(hJob, pi.hProcess))
326 success = true;
327 }
328 }
329 if (!success) {
330 SetLastError(GetLastError());
331 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
332 TerminateProcess(pi.hProcess, 1);
333 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000334 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000335 }
336 }
337
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000338 return true;
339}
340
341int
Dan Gohmane5f77cd2010-10-29 16:54:25 +0000342Program::Wait(const Path &path,
343 unsigned secondsToWait,
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000344 std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000345 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000346 MakeErrMsg(ErrMsg, "Process not started!");
347 return -1;
348 }
349
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000350 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
351 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000352
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000353 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000354 DWORD millisecondsToWait = INFINITE;
355 if (secondsToWait > 0)
356 millisecondsToWait = secondsToWait * 1000;
357
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000358 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
359 if (!TerminateProcess(hProcess, 1)) {
360 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000361 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000362 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000363 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000364 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000365
Reid Spencerb016a372004-09-15 05:49:50 +0000366 // Get its exit status.
367 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000368 BOOL rc = GetExitCodeProcess(hProcess, &status);
369 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000370
Jeff Cohen875d08e2005-02-20 02:43:04 +0000371 if (!rc) {
372 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000373 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000374 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000375 }
Reid Spencerb016a372004-09-15 05:49:50 +0000376
377 return status;
378}
379
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000380bool
381Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000382 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000383 MakeErrMsg(ErrMsg, "Process not started!");
384 return true;
385 }
386
Mikhail Glushenkov92d32362009-09-22 15:40:32 +0000387 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
388 HANDLE hProcess = wpi->hProcess;
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000389 if (TerminateProcess(hProcess, 1) == 0) {
390 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
391 return true;
392 }
393
394 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000395}
396
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000397bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000398 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000399 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000400}
401
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000402bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000403 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000404 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000405}
406
Douglas Gregor21569cd2010-01-28 06:42:08 +0000407bool Program::ChangeStderrToBinary(){
408 int result = _setmode( _fileno(stderr), _O_BINARY );
409 return result == -1;
410}
411
Reid Spencerb016a372004-09-15 05:49:50 +0000412}