blob: 804273bf23df7eab44cefecf8f1dc248b8fc3f5c [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
Daniel Dunbar1b399062009-08-03 05:02:46 +000028Program::Program() : Pid_(0), Data(0) {}
29
30Program::~Program() {
31 if (Data) {
32 HANDLE hProcess = (HANDLE) Data;
33 CloseHandle(hProcess);
34 Data = 0;
35 }
36}
37
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
46 if (!temp.set(progName)) // invalid name
47 return Path();
48 if (temp.canExecute()) // already executable as is
49 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
82static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
83 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 Glushenkova5140f72009-04-14 21:31:14 +000090
Matthijs Kooijman641150d2008-06-12 10:47:18 +000091 const char *fname;
92 if (path->isEmpty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 fname = "NUL";
Matthijs Kooijman641150d2008-06-12 10:47:18 +000094 else
Chris Lattnerb1aa85b2009-08-23 22:45:37 +000095 fname = path->c_str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +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,
103 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
104 FILE_ATTRIBUTE_NORMAL, NULL);
105 if (h == INVALID_HANDLE_VALUE) {
106 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
107 (fd ? "input: " : "output: "));
108 }
109
110 return h;
111}
112
113#ifdef __MINGW32__
114 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
115 extern "C"
116 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
117 JOBOBJECTINFOCLASS JobObjectInfoClass,
118 LPVOID lpJobObjectInfo,
119 DWORD cbJobObjectInfoLength);
120#endif
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000121
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000122/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
123/// CreateProcess.
124static bool ArgNeedsQuotes(const char *Str) {
125 return Str[0] == '\0' || strchr(Str, ' ') != 0;
126}
127
Mikhail Glushenkovb23120b2009-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 Dunbar1b399062009-08-03 05:02:46 +0000135 if (Data) {
136 HANDLE hProcess = (HANDLE) Data;
137 CloseHandle(Data);
138 Data = 0;
139 }
140
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 if (!path.canExecute()) {
142 if (ErrMsg)
143 *ErrMsg = "program not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000144 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
146
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 Dunbaraad7ba12009-08-02 20:41:09 +0000149 // have embedded spaces (or are empty).
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
151 // First, determine the length of the command line.
152 unsigned len = 0;
153 for (unsigned i = 0; args[i]; i++) {
154 len += strlen(args[i]) + 1;
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000155 if (ArgNeedsQuotes(args[i]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 len += 2;
157 }
158
159 // Now build the command line.
Anton Korobeynikov27f1ebc2008-01-24 01:20:48 +0000160 char *command = reinterpret_cast<char *>(_alloca(len+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 char *p = command;
162
163 for (unsigned i = 0; args[i]; i++) {
164 const char *arg = args[i];
165 size_t len = strlen(arg);
Daniel Dunbaraad7ba12009-08-02 20:41:09 +0000166 bool needsQuoting = ArgNeedsQuotes(arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 if (needsQuoting)
168 *p++ = '"';
169 memcpy(p, arg, len);
170 p += len;
171 if (needsQuoting)
172 *p++ = '"';
173 *p++ = ' ';
174 }
175
176 *p = 0;
177
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000178 // The pointer to the environment block for the new process.
179 char *envblock = 0;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000180
Argiris Kirtzidis715b3872008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 // Create a child process.
206 STARTUPINFO si;
207 memset(&si, 0, sizeof(si));
208 si.cb = sizeof(si);
209 si.hStdInput = INVALID_HANDLE_VALUE;
210 si.hStdOutput = INVALID_HANDLE_VALUE;
211 si.hStdError = INVALID_HANDLE_VALUE;
212
213 if (redirects) {
214 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000215
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
217 if (si.hStdInput == INVALID_HANDLE_VALUE) {
218 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000219 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 }
221 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
222 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
223 CloseHandle(si.hStdInput);
224 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000225 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 }
Matthijs Kooijman0e7dc8a2008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
236 if (si.hStdError == INVALID_HANDLE_VALUE) {
237 CloseHandle(si.hStdInput);
238 CloseHandle(si.hStdOutput);
239 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000240 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 }
243 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000244
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 PROCESS_INFORMATION pi;
246 memset(&pi, 0, sizeof(pi));
247
248 fflush(stdout);
249 fflush(stderr);
Mikhail Glushenkovaa9f1022009-04-14 21:31:36 +0000250 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000251 envblock, NULL, &si, &pi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
260 // Now return an error if the process didn't get created.
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000261 if (!rc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 SetLastError(err);
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000263 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000264 path.str() + "'");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000265 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 }
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000267 Pid_ = pi.dwProcessId;
Daniel Dunbar1b399062009-08-03 05:02:46 +0000268 Data = pi.hProcess;
269
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 // Make sure these get closed no matter what.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
282 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
283 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 Glushenkovb23120b2009-07-18 21:43:12 +0000294 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 }
296 }
297
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000298 return true;
299}
300
301int
302Program::Wait(unsigned secondsToWait,
303 std::string* ErrMsg) {
Daniel Dunbar1b399062009-08-03 05:02:46 +0000304 if (Data == 0) {
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000305 MakeErrMsg(ErrMsg, "Process not started!");
306 return -1;
307 }
308
Daniel Dunbar1b399062009-08-03 05:02:46 +0000309 HANDLE hProcess = (HANDLE) Data;
310
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000311 // Wait for the process to terminate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 DWORD millisecondsToWait = INFINITE;
313 if (secondsToWait > 0)
314 millisecondsToWait = secondsToWait * 1000;
315
Mikhail Glushenkovb23120b2009-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.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 return -1;
320 }
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000321 WaitForSingleObject(hProcess, INFINITE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 // Get its exit status.
325 DWORD status;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000326 BOOL rc = GetExitCodeProcess(hProcess, &status);
327 DWORD err = GetLastError();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
329 if (!rc) {
330 SetLastError(err);
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000331 MakeErrMsg(ErrMsg, "Failed getting status for program.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332 return -1;
333 }
334
335 return status;
336}
337
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338bool Program::ChangeStdinToBinary(){
339 int result = _setmode( _fileno(stdin), _O_BINARY );
340 return result == -1;
341}
342
343bool Program::ChangeStdoutToBinary(){
344 int result = _setmode( _fileno(stdout), _O_BINARY );
345 return result == -1;
346}
347
348}