blob: 963946a985ee220f4f8ef1c1ecc1c0ebe462d24c [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Mikhail Glushenkova5140f72009-04-14 21:31:14 +00002//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-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 Glushenkova5140f72009-04-14 21:31:14 +00007//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Win32.h"
15#include <cstdio>
16#include <malloc.h>
17#include <io.h>
18#include <fcntl.h>
19
20//===----------------------------------------------------------------------===//
Mikhail Glushenkova5140f72009-04-14 21:31:14 +000021//=== WARNING: Implementation here must contain only Win32 specific code
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022//=== and must not be UNIX code
23//===----------------------------------------------------------------------===//
24
25namespace 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;
36 if (!temp.set(progName)) // invalid name
37 return Path();
38 if (temp.canExecute()) // already executable as is
39 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
72static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
73 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 Glushenkova5140f72009-04-14 21:31:14 +000080
Matthijs Kooijman641150d2008-06-12 10:47:18 +000081 const char *fname;
82 if (path->isEmpty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 fname = "NUL";
Matthijs Kooijman641150d2008-06-12 10:47:18 +000084 else
85 fname = path->toString().c_str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +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,
93 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
94 FILE_ATTRIBUTE_NORMAL, NULL);
95 if (h == INVALID_HANDLE_VALUE) {
96 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
97 (fd ? "input: " : "output: "));
98 }
99
100 return h;
101}
102
103#ifdef __MINGW32__
104 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
105 extern "C"
106 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
107 JOBOBJECTINFOCLASS JobObjectInfoClass,
108 LPVOID lpJobObjectInfo,
109 DWORD cbJobObjectInfoLength);
110#endif
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000111
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000112/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
113/// CreateProcess.
114static bool ArgNeedsQuotes(const char *Str) {
115 return Str[0] == '\0' || strchr(Str, ' ') != 0;
116}
117
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000118bool
119Program::Execute(const Path& path,
120 const char** args,
121 const char** envp,
122 const Path** redirects,
123 unsigned memoryLimit,
124 std::string* ErrMsg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 if (!path.canExecute()) {
126 if (ErrMsg)
127 *ErrMsg = "program not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000128 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 }
130
131 // Windows wants a command line, not an array of args, to pass to the new
132 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000133 // have embedded spaces (or are empty).
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134
135 // First, determine the length of the command line.
136 unsigned len = 0;
137 for (unsigned i = 0; args[i]; i++) {
138 len += strlen(args[i]) + 1;
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000139 if (ArgNeedsQuotes(args[i]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 len += 2;
141 }
142
143 // Now build the command line.
Anton Korobeynikov27f1ebc2008-01-24 01:20:48 +0000144 char *command = reinterpret_cast<char *>(_alloca(len+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 char *p = command;
146
147 for (unsigned i = 0; args[i]; i++) {
148 const char *arg = args[i];
149 size_t len = strlen(arg);
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000150 bool needsQuoting = ArgNeedsQuotes(arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 if (needsQuoting)
152 *p++ = '"';
153 memcpy(p, arg, len);
154 p += len;
155 if (needsQuoting)
156 *p++ = '"';
157 *p++ = ' ';
158 }
159
160 *p = 0;
161
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000162 // The pointer to the environment block for the new process.
163 char *envblock = 0;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000164
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000165 if (envp) {
166 // An environment block consists of a null-terminated block of
167 // null-terminated strings. Convert the array of environment variables to
168 // an environment block by concatenating them.
169
170 // First, determine the length of the environment block.
171 len = 0;
172 for (unsigned i = 0; envp[i]; i++)
173 len += strlen(envp[i]) + 1;
174
175 // Now build the environment block.
176 envblock = reinterpret_cast<char *>(_alloca(len+1));
177 p = envblock;
178
179 for (unsigned i = 0; envp[i]; i++) {
180 const char *ev = envp[i];
181 size_t len = strlen(ev) + 1;
182 memcpy(p, ev, len);
183 p += len;
184 }
185
186 *p = 0;
187 }
188
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 // Create a child process.
190 STARTUPINFO si;
191 memset(&si, 0, sizeof(si));
192 si.cb = sizeof(si);
193 si.hStdInput = INVALID_HANDLE_VALUE;
194 si.hStdOutput = INVALID_HANDLE_VALUE;
195 si.hStdError = INVALID_HANDLE_VALUE;
196
197 if (redirects) {
198 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
201 if (si.hStdInput == INVALID_HANDLE_VALUE) {
202 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000203 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 }
205 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
206 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
207 CloseHandle(si.hStdInput);
208 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000209 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000211 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
212 // If stdout and stderr should go to the same place, redirect stderr
213 // to the handle already open for stdout.
214 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
215 GetCurrentProcess(), &si.hStdError,
216 0, TRUE, DUPLICATE_SAME_ACCESS);
217 } else {
218 // Just redirect stderr
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
220 if (si.hStdError == INVALID_HANDLE_VALUE) {
221 CloseHandle(si.hStdInput);
222 CloseHandle(si.hStdOutput);
223 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000224 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 }
227 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000228
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 PROCESS_INFORMATION pi;
230 memset(&pi, 0, sizeof(pi));
231
232 fflush(stdout);
233 fflush(stderr);
Mikhail Glushenkovaa9f1022009-04-14 21:31:36 +0000234 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000235 envblock, NULL, &si, &pi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 DWORD err = GetLastError();
237
238 // Regardless of whether the process got created or not, we are done with
239 // the handles we created for it to inherit.
240 CloseHandle(si.hStdInput);
241 CloseHandle(si.hStdOutput);
242 CloseHandle(si.hStdError);
243
244 // Now return an error if the process didn't get created.
245 if (!rc)
246 {
247 SetLastError(err);
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000248 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 path.toString() + "'");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000250 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 }
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000252 Pid_ = pi.dwProcessId;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253
254 // Make sure these get closed no matter what.
255 AutoHandle hProcess(pi.hProcess);
256 AutoHandle hThread(pi.hThread);
257
258 // Assign the process to a job if a memory limit is defined.
259 AutoHandle hJob(0);
260 if (memoryLimit != 0) {
261 hJob = CreateJobObject(0, 0);
262 bool success = false;
263 if (hJob != 0) {
264 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
265 memset(&jeli, 0, sizeof(jeli));
266 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
267 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
268 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
269 &jeli, sizeof(jeli))) {
270 if (AssignProcessToJobObject(hJob, pi.hProcess))
271 success = true;
272 }
273 }
274 if (!success) {
275 SetLastError(GetLastError());
276 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
277 TerminateProcess(pi.hProcess, 1);
278 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000279 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 }
281 }
282
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000283 return true;
284}
285
286int
287Program::Wait(unsigned secondsToWait,
288 std::string* ErrMsg) {
289 if (Pid_ == 0) {
290 MakeErrMsg(ErrMsg, "Process not started!");
291 return -1;
292 }
293
294 AutoHandle hProcess = OpenProcess(SYNCHRONIZE, FALSE, Pid_);
295
296 // Wait for the process to terminate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 DWORD millisecondsToWait = INFINITE;
298 if (secondsToWait > 0)
299 millisecondsToWait = secondsToWait * 1000;
300
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000301 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
302 if (!TerminateProcess(hProcess, 1)) {
303 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 return -1;
305 }
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000306 WaitForSingleObject(hProcess, INFINITE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000308
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 // Get its exit status.
310 DWORD status;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000311 BOOL rc = GetExitCodeProcess(hProcess, &status);
312 DWORD err = GetLastError();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313
314 if (!rc) {
315 SetLastError(err);
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000316 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 return -1;
318 }
319
320 return status;
321}
322
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323bool Program::ChangeStdinToBinary(){
324 int result = _setmode( _fileno(stdin), _O_BINARY );
325 return result == -1;
326}
327
328bool Program::ChangeStdoutToBinary(){
329 int result = _setmode( _fileno(stdout), _O_BINARY );
330 return result == -1;
331}
332
333}