blob: 71f686ca02de6e0a643e4c3e51a07b492a211cf3 [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
112int
113Program::ExecuteAndWait(const Path& path,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 const char** args,
115 const char** envp,
116 const Path** redirects,
117 unsigned secondsToWait,
118 unsigned memoryLimit,
119 std::string* ErrMsg) {
120 if (!path.canExecute()) {
121 if (ErrMsg)
122 *ErrMsg = "program not executable";
123 return -1;
124 }
125
126 // Windows wants a command line, not an array of args, to pass to the new
127 // process. We have to concatenate them all, while quoting the args that
128 // have embedded spaces.
129
130 // First, determine the length of the command line.
131 unsigned len = 0;
132 for (unsigned i = 0; args[i]; i++) {
133 len += strlen(args[i]) + 1;
134 if (strchr(args[i], ' '))
135 len += 2;
136 }
137
138 // Now build the command line.
Anton Korobeynikov27f1ebc2008-01-24 01:20:48 +0000139 char *command = reinterpret_cast<char *>(_alloca(len+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 char *p = command;
141
142 for (unsigned i = 0; args[i]; i++) {
143 const char *arg = args[i];
144 size_t len = strlen(arg);
145 bool needsQuoting = strchr(arg, ' ') != 0;
146 if (needsQuoting)
147 *p++ = '"';
148 memcpy(p, arg, len);
149 p += len;
150 if (needsQuoting)
151 *p++ = '"';
152 *p++ = ' ';
153 }
154
155 *p = 0;
156
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000157 // The pointer to the environment block for the new process.
158 char *envblock = 0;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000159
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000160 if (envp) {
161 // An environment block consists of a null-terminated block of
162 // null-terminated strings. Convert the array of environment variables to
163 // an environment block by concatenating them.
164
165 // First, determine the length of the environment block.
166 len = 0;
167 for (unsigned i = 0; envp[i]; i++)
168 len += strlen(envp[i]) + 1;
169
170 // Now build the environment block.
171 envblock = reinterpret_cast<char *>(_alloca(len+1));
172 p = envblock;
173
174 for (unsigned i = 0; envp[i]; i++) {
175 const char *ev = envp[i];
176 size_t len = strlen(ev) + 1;
177 memcpy(p, ev, len);
178 p += len;
179 }
180
181 *p = 0;
182 }
183
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 // Create a child process.
185 STARTUPINFO si;
186 memset(&si, 0, sizeof(si));
187 si.cb = sizeof(si);
188 si.hStdInput = INVALID_HANDLE_VALUE;
189 si.hStdOutput = INVALID_HANDLE_VALUE;
190 si.hStdError = INVALID_HANDLE_VALUE;
191
192 if (redirects) {
193 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
196 if (si.hStdInput == INVALID_HANDLE_VALUE) {
197 MakeErrMsg(ErrMsg, "can't redirect stdin");
198 return -1;
199 }
200 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
201 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
202 CloseHandle(si.hStdInput);
203 MakeErrMsg(ErrMsg, "can't redirect stdout");
204 return -1;
205 }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000206 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
207 // If stdout and stderr should go to the same place, redirect stderr
208 // to the handle already open for stdout.
209 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
210 GetCurrentProcess(), &si.hStdError,
211 0, TRUE, DUPLICATE_SAME_ACCESS);
212 } else {
213 // Just redirect stderr
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
215 if (si.hStdError == INVALID_HANDLE_VALUE) {
216 CloseHandle(si.hStdInput);
217 CloseHandle(si.hStdOutput);
218 MakeErrMsg(ErrMsg, "can't redirect stderr");
219 return -1;
220 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 }
222 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000223
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 PROCESS_INFORMATION pi;
225 memset(&pi, 0, sizeof(pi));
226
227 fflush(stdout);
228 fflush(stderr);
Mikhail Glushenkovaa9f1022009-04-14 21:31:36 +0000229 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
Argiris Kirtzidis715b3872008-06-15 03:54:39 +0000230 envblock, NULL, &si, &pi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 DWORD err = GetLastError();
232
233 // Regardless of whether the process got created or not, we are done with
234 // the handles we created for it to inherit.
235 CloseHandle(si.hStdInput);
236 CloseHandle(si.hStdOutput);
237 CloseHandle(si.hStdError);
238
239 // Now return an error if the process didn't get created.
240 if (!rc)
241 {
242 SetLastError(err);
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000243 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 path.toString() + "'");
245 return -1;
246 }
247
248 // 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;
261 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
262 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);
273 return -1;
274 }
275 }
276
277 // Wait for it to terminate.
278 DWORD millisecondsToWait = INFINITE;
279 if (secondsToWait > 0)
280 millisecondsToWait = secondsToWait * 1000;
281
282 if (WaitForSingleObject(pi.hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
283 if (!TerminateProcess(pi.hProcess, 1)) {
284 MakeErrMsg(ErrMsg, std::string("Failed to terminate timed-out program '")
285 + path.toString() + "'");
286 return -1;
287 }
288 WaitForSingleObject(pi.hProcess, INFINITE);
289 }
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000290
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 // Get its exit status.
292 DWORD status;
293 rc = GetExitCodeProcess(pi.hProcess, &status);
294 err = GetLastError();
295
296 if (!rc) {
297 SetLastError(err);
Mikhail Glushenkova5140f72009-04-14 21:31:14 +0000298 MakeErrMsg(ErrMsg, std::string("Failed getting status for program '") +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 path.toString() + "'");
300 return -1;
301 }
302
303 return status;
304}
305
David Greenea6bedb12009-07-08 21:46:40 +0000306void
307Program::ExecuteNoWait(const Path& path,
308 const char** args,
309 const char** envp,
310 const Path** redirects,
311 unsigned memoryLimit,
312 std::string* ErrMsg) {
313 if (!path.canExecute()) {
314 if (ErrMsg)
315 *ErrMsg = "program not executable";
316 return;
317 }
318
319 // Windows wants a command line, not an array of args, to pass to the new
320 // process. We have to concatenate them all, while quoting the args that
321 // have embedded spaces.
322
323 // First, determine the length of the command line.
324 unsigned len = 0;
325 for (unsigned i = 0; args[i]; i++) {
326 len += strlen(args[i]) + 1;
327 if (strchr(args[i], ' '))
328 len += 2;
329 }
330
331 // Now build the command line.
332 char *command = reinterpret_cast<char *>(_alloca(len+1));
333 char *p = command;
334
335 for (unsigned i = 0; args[i]; i++) {
336 const char *arg = args[i];
337 size_t len = strlen(arg);
338 bool needsQuoting = strchr(arg, ' ') != 0;
339 if (needsQuoting)
340 *p++ = '"';
341 memcpy(p, arg, len);
342 p += len;
343 if (needsQuoting)
344 *p++ = '"';
345 *p++ = ' ';
346 }
347
348 *p = 0;
349
350 // The pointer to the environment block for the new process.
351 char *envblock = 0;
352
353 if (envp) {
354 // An environment block consists of a null-terminated block of
355 // null-terminated strings. Convert the array of environment variables to
356 // an environment block by concatenating them.
357
358 // First, determine the length of the environment block.
359 len = 0;
360 for (unsigned i = 0; envp[i]; i++)
361 len += strlen(envp[i]) + 1;
362
363 // Now build the environment block.
364 envblock = reinterpret_cast<char *>(_alloca(len+1));
365 p = envblock;
366
367 for (unsigned i = 0; envp[i]; i++) {
368 const char *ev = envp[i];
369 size_t len = strlen(ev) + 1;
370 memcpy(p, ev, len);
371 p += len;
372 }
373
374 *p = 0;
375 }
376
377 // Create a child process.
378 STARTUPINFO si;
379 memset(&si, 0, sizeof(si));
380 si.cb = sizeof(si);
381 si.hStdInput = INVALID_HANDLE_VALUE;
382 si.hStdOutput = INVALID_HANDLE_VALUE;
383 si.hStdError = INVALID_HANDLE_VALUE;
384
385 if (redirects) {
386 si.dwFlags = STARTF_USESTDHANDLES;
387
388 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
389 if (si.hStdInput == INVALID_HANDLE_VALUE) {
390 MakeErrMsg(ErrMsg, "can't redirect stdin");
391 return;
392 }
393 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
394 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
395 CloseHandle(si.hStdInput);
396 MakeErrMsg(ErrMsg, "can't redirect stdout");
397 return;
398 }
399 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
400 // If stdout and stderr should go to the same place, redirect stderr
401 // to the handle already open for stdout.
402 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
403 GetCurrentProcess(), &si.hStdError,
404 0, TRUE, DUPLICATE_SAME_ACCESS);
405 } else {
406 // Just redirect stderr
407 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
408 if (si.hStdError == INVALID_HANDLE_VALUE) {
409 CloseHandle(si.hStdInput);
410 CloseHandle(si.hStdOutput);
411 MakeErrMsg(ErrMsg, "can't redirect stderr");
412 return;
413 }
414 }
415 }
416
417 PROCESS_INFORMATION pi;
418 memset(&pi, 0, sizeof(pi));
419
420 fflush(stdout);
421 fflush(stderr);
422 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
423 envblock, NULL, &si, &pi);
424 DWORD err = GetLastError();
425
426 // Regardless of whether the process got created or not, we are done with
427 // the handles we created for it to inherit.
428 CloseHandle(si.hStdInput);
429 CloseHandle(si.hStdOutput);
430 CloseHandle(si.hStdError);
431
432 // Now return an error if the process didn't get created.
433 if (!rc)
434 {
435 SetLastError(err);
436 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
437 path.toString() + "'");
438 return;
439 }
440
441 // Make sure these get closed no matter what.
442 AutoHandle hProcess(pi.hProcess);
443 AutoHandle hThread(pi.hThread);
444
445 // Assign the process to a job if a memory limit is defined.
446 AutoHandle hJob(0);
447 if (memoryLimit != 0) {
448 hJob = CreateJobObject(0, 0);
449 bool success = false;
450 if (hJob != 0) {
451 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
452 memset(&jeli, 0, sizeof(jeli));
453 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
454 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
455 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
456 &jeli, sizeof(jeli))) {
457 if (AssignProcessToJobObject(hJob, pi.hProcess))
458 success = true;
459 }
460 }
461 if (!success) {
462 SetLastError(GetLastError());
463 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
464 TerminateProcess(pi.hProcess, 1);
465 WaitForSingleObject(pi.hProcess, INFINITE);
466 return;
467 }
468 }
469}
470
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471bool Program::ChangeStdinToBinary(){
472 int result = _setmode( _fileno(stdin), _O_BINARY );
473 return result == -1;
474}
475
476bool Program::ChangeStdoutToBinary(){
477 int result = _setmode( _fileno(stdout), _O_BINARY );
478 return result == -1;
479}
480
481}