blob: 7dbfb3e6323ffeb71bc278b47b6c98637b45e5de [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
28// This function just uses the PATH environment variable to find the program.
29Path
30Program::FindProgramByName(const std::string& progName) {
31
32 // Check some degenerate cases
33 if (progName.length() == 0) // no program
34 return Path();
35 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000036 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000037 return Path();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000038 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000039 return temp;
40
41 // At this point, the file name is valid and its not executable.
42 // Let Windows search for it.
43 char buffer[MAX_PATH];
44 char *dummy = NULL;
45 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
46 buffer, &dummy);
47
48 // See if it wasn't found.
49 if (len == 0)
50 return Path();
51
52 // See if we got the entire path.
53 if (len < MAX_PATH)
54 return Path(buffer);
55
56 // Buffer was too small; grow and retry.
57 while (true) {
58 char *b = reinterpret_cast<char *>(_alloca(len+1));
59 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
60
61 // It is unlikely the search failed, but it's always possible some file
62 // was added or removed since the last search, so be paranoid...
63 if (len2 == 0)
64 return Path();
65 else if (len2 <= len)
66 return Path(b);
67
68 len = len2;
69 }
70}
71
Reid Spencer4ce5dc62006-08-21 06:02:44 +000072static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
Jeff Cohen875d08e2005-02-20 02:43:04 +000073 HANDLE h;
74 if (path == 0) {
75 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
76 GetCurrentProcess(), &h,
77 0, TRUE, DUPLICATE_SAME_ACCESS);
78 return h;
79 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +000080
Matthijs Kooijman905261e2008-06-12 10:47:18 +000081 const char *fname;
82 if (path->isEmpty())
Jeff Cohen875d08e2005-02-20 02:43:04 +000083 fname = "NUL";
Matthijs Kooijman905261e2008-06-12 10:47:18 +000084 else
85 fname = path->toString().c_str();
Jeff Cohen875d08e2005-02-20 02:43:04 +000086
87 SECURITY_ATTRIBUTES sa;
88 sa.nLength = sizeof(sa);
89 sa.lpSecurityDescriptor = 0;
90 sa.bInheritHandle = TRUE;
91
92 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +000093 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +000094 FILE_ATTRIBUTE_NORMAL, NULL);
95 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +000096 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +000097 (fd ? "input: " : "output: "));
98 }
Jeff Cohen0a182672007-03-05 05:22:08 +000099
Jeff Cohen875d08e2005-02-20 02:43:04 +0000100 return h;
101}
102
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000103#ifdef __MINGW32__
104 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
Anton Korobeynikovd437db12007-03-19 20:19:08 +0000105 extern "C"
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000106 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
107 JOBOBJECTINFOCLASS JobObjectInfoClass,
108 LPVOID lpJobObjectInfo,
109 DWORD cbJobObjectInfoLength);
110#endif
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000111
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000112bool
113Program::Execute(const Path& path,
114 const char** args,
115 const char** envp,
116 const Path** redirects,
117 unsigned memoryLimit,
118 std::string* ErrMsg) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000119 if (!path.canExecute()) {
120 if (ErrMsg)
121 *ErrMsg = "program not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000122 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000123 }
Reid Spencerb016a372004-09-15 05:49:50 +0000124
125 // Windows wants a command line, not an array of args, to pass to the new
126 // process. We have to concatenate them all, while quoting the args that
127 // have embedded spaces.
128
129 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000130 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000131 for (unsigned i = 0; args[i]; i++) {
132 len += strlen(args[i]) + 1;
133 if (strchr(args[i], ' '))
Reid Spencerb016a372004-09-15 05:49:50 +0000134 len += 2;
135 }
136
137 // Now build the command line.
Anton Korobeynikov58ea52a2008-01-24 01:20:48 +0000138 char *command = reinterpret_cast<char *>(_alloca(len+1));
Reid Spencerb016a372004-09-15 05:49:50 +0000139 char *p = command;
140
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000141 for (unsigned i = 0; args[i]; i++) {
142 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000143 size_t len = strlen(arg);
Jeff Cohene5f7e652005-02-16 04:43:45 +0000144 bool needsQuoting = strchr(arg, ' ') != 0;
Reid Spencerb016a372004-09-15 05:49:50 +0000145 if (needsQuoting)
146 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000147 memcpy(p, arg, len);
148 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000149 if (needsQuoting)
150 *p++ = '"';
151 *p++ = ' ';
152 }
153
154 *p = 0;
155
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000156 // The pointer to the environment block for the new process.
157 char *envblock = 0;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000158
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000159 if (envp) {
160 // An environment block consists of a null-terminated block of
161 // null-terminated strings. Convert the array of environment variables to
162 // an environment block by concatenating them.
163
164 // First, determine the length of the environment block.
165 len = 0;
166 for (unsigned i = 0; envp[i]; i++)
167 len += strlen(envp[i]) + 1;
168
169 // Now build the environment block.
170 envblock = reinterpret_cast<char *>(_alloca(len+1));
171 p = envblock;
172
173 for (unsigned i = 0; envp[i]; i++) {
174 const char *ev = envp[i];
175 size_t len = strlen(ev) + 1;
176 memcpy(p, ev, len);
177 p += len;
178 }
179
180 *p = 0;
181 }
182
Reid Spencerb016a372004-09-15 05:49:50 +0000183 // Create a child process.
184 STARTUPINFO si;
185 memset(&si, 0, sizeof(si));
186 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000187 si.hStdInput = INVALID_HANDLE_VALUE;
188 si.hStdOutput = INVALID_HANDLE_VALUE;
189 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000190
Jeff Cohen875d08e2005-02-20 02:43:04 +0000191 if (redirects) {
192 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000193
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000194 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
195 if (si.hStdInput == INVALID_HANDLE_VALUE) {
196 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000197 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000198 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000199 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000200 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000201 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000202 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000203 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000204 }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000205 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
206 // If stdout and stderr should go to the same place, redirect stderr
207 // to the handle already open for stdout.
208 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
209 GetCurrentProcess(), &si.hStdError,
210 0, TRUE, DUPLICATE_SAME_ACCESS);
211 } else {
212 // Just redirect stderr
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000213 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000214 if (si.hStdError == INVALID_HANDLE_VALUE) {
215 CloseHandle(si.hStdInput);
216 CloseHandle(si.hStdOutput);
217 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000218 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000219 }
Jeff Cohen875d08e2005-02-20 02:43:04 +0000220 }
221 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000222
Reid Spencerb016a372004-09-15 05:49:50 +0000223 PROCESS_INFORMATION pi;
224 memset(&pi, 0, sizeof(pi));
225
Jeff Cohen875d08e2005-02-20 02:43:04 +0000226 fflush(stdout);
227 fflush(stderr);
Mikhail Glushenkov05266532009-04-14 21:31:36 +0000228 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argyrios Kyrtzidisf1844d22008-06-15 03:54:39 +0000229 envblock, NULL, &si, &pi);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000230 DWORD err = GetLastError();
231
232 // Regardless of whether the process got created or not, we are done with
233 // the handles we created for it to inherit.
234 CloseHandle(si.hStdInput);
235 CloseHandle(si.hStdOutput);
236 CloseHandle(si.hStdError);
237
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000238 // Now return an error if the process didn't get created.
Jeff Cohen875d08e2005-02-20 02:43:04 +0000239 if (!rc)
Reid Spencerb016a372004-09-15 05:49:50 +0000240 {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000241 SetLastError(err);
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000242 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Reid Spencer707a27c2004-12-11 17:37:01 +0000243 path.toString() + "'");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000244 return false;
Reid Spencerb016a372004-09-15 05:49:50 +0000245 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000246 Pid_ = pi.dwProcessId;
Reid Spencerb016a372004-09-15 05:49:50 +0000247
Jeff Cohen0a182672007-03-05 05:22:08 +0000248 // Make sure these get closed no matter what.
249 AutoHandle hProcess(pi.hProcess);
250 AutoHandle hThread(pi.hThread);
251
252 // Assign the process to a job if a memory limit is defined.
253 AutoHandle hJob(0);
254 if (memoryLimit != 0) {
255 hJob = CreateJobObject(0, 0);
256 bool success = false;
257 if (hJob != 0) {
258 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
259 memset(&jeli, 0, sizeof(jeli));
260 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000261 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000262 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
263 &jeli, sizeof(jeli))) {
264 if (AssignProcessToJobObject(hJob, pi.hProcess))
265 success = true;
266 }
267 }
268 if (!success) {
269 SetLastError(GetLastError());
270 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
271 TerminateProcess(pi.hProcess, 1);
272 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000273 return false;
Jeff Cohen0a182672007-03-05 05:22:08 +0000274 }
275 }
276
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000277 return true;
278}
279
280int
281Program::Wait(unsigned secondsToWait,
282 std::string* ErrMsg) {
283 if (Pid_ == 0) {
284 MakeErrMsg(ErrMsg, "Process not started!");
285 return -1;
286 }
287
288 AutoHandle hProcess = OpenProcess(SYNCHRONIZE, FALSE, Pid_);
289
290 // Wait for the process to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000291 DWORD millisecondsToWait = INFINITE;
292 if (secondsToWait > 0)
293 millisecondsToWait = secondsToWait * 1000;
294
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000295 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
296 if (!TerminateProcess(hProcess, 1)) {
297 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000298 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000299 }
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000300 WaitForSingleObject(hProcess, INFINITE);
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000301 }
Mikhail Glushenkovbd50a162009-04-14 21:31:14 +0000302
Reid Spencerb016a372004-09-15 05:49:50 +0000303 // Get its exit status.
304 DWORD status;
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000305 BOOL rc = GetExitCodeProcess(hProcess, &status);
306 DWORD err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000307
Jeff Cohen875d08e2005-02-20 02:43:04 +0000308 if (!rc) {
309 SetLastError(err);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000310 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000311 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000312 }
Reid Spencerb016a372004-09-15 05:49:50 +0000313
314 return status;
315}
316
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000317bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000318 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000319 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000320}
321
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000322bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000323 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000324 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000325}
326
Reid Spencerb016a372004-09-15 05:49:50 +0000327}