blob: 7cc14a24d4dcc16037a5cc915da8904fe86bc5c6 [file] [log] [blame]
Reid Spencerb016a372004-09-15 05:49:50 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Reid Spencer52a7efa2004-08-29 19:20:41 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencerb016a372004-09-15 05:49:50 +00005// This file was developed by Jeff Cohen and is distributed under the
Reid Spencer52a7efa2004-08-29 19:20:41 +00006// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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//===----------------------------------------------------------------------===//
Reid Spencerb016a372004-09-15 05:49:50 +000021//=== WARNING: Implementation here must contain only Win32 specific code
22//=== 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 }
80
81 const char *fname = path->toString().c_str();
82 if (*fname == 0)
83 fname = "NUL";
84
85 SECURITY_ATTRIBUTES sa;
86 sa.nLength = sizeof(sa);
87 sa.lpSecurityDescriptor = 0;
88 sa.bInheritHandle = TRUE;
89
90 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +000091 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +000092 FILE_ATTRIBUTE_NORMAL, NULL);
93 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +000094 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen875d08e2005-02-20 02:43:04 +000095 (fd ? "input: " : "output: "));
96 }
Jeff Cohen0a182672007-03-05 05:22:08 +000097
Jeff Cohen875d08e2005-02-20 02:43:04 +000098 return h;
99}
100
Anton Korobeynikov349ec1c2007-03-09 11:53:34 +0000101#ifdef __MINGW32__
102 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
103 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
104 JOBOBJECTINFOCLASS JobObjectInfoClass,
105 LPVOID lpJobObjectInfo,
106 DWORD cbJobObjectInfoLength);
107#endif
108
Reid Spencerb016a372004-09-15 05:49:50 +0000109int
110Program::ExecuteAndWait(const Path& path,
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000111 const char** args,
112 const char** envp,
113 const Path** redirects,
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000114 unsigned secondsToWait,
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000115 unsigned memoryLimit,
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000116 std::string* ErrMsg) {
117 if (!path.canExecute()) {
118 if (ErrMsg)
119 *ErrMsg = "program not executable";
120 return -1;
121 }
Reid Spencerb016a372004-09-15 05:49:50 +0000122
123 // Windows wants a command line, not an array of args, to pass to the new
124 // process. We have to concatenate them all, while quoting the args that
125 // have embedded spaces.
126
127 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000128 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000129 for (unsigned i = 0; args[i]; i++) {
130 len += strlen(args[i]) + 1;
131 if (strchr(args[i], ' '))
Reid Spencerb016a372004-09-15 05:49:50 +0000132 len += 2;
133 }
134
135 // Now build the command line.
136 char *command = reinterpret_cast<char *>(_alloca(len));
137 char *p = command;
138
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000139 for (unsigned i = 0; args[i]; i++) {
140 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000141 size_t len = strlen(arg);
Jeff Cohene5f7e652005-02-16 04:43:45 +0000142 bool needsQuoting = strchr(arg, ' ') != 0;
Reid Spencerb016a372004-09-15 05:49:50 +0000143 if (needsQuoting)
144 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000145 memcpy(p, arg, len);
146 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000147 if (needsQuoting)
148 *p++ = '"';
149 *p++ = ' ';
150 }
151
152 *p = 0;
153
154 // Create a child process.
155 STARTUPINFO si;
156 memset(&si, 0, sizeof(si));
157 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000158 si.hStdInput = INVALID_HANDLE_VALUE;
159 si.hStdOutput = INVALID_HANDLE_VALUE;
160 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000161
Jeff Cohen875d08e2005-02-20 02:43:04 +0000162 if (redirects) {
163 si.dwFlags = STARTF_USESTDHANDLES;
164
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000165 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
166 if (si.hStdInput == INVALID_HANDLE_VALUE) {
167 MakeErrMsg(ErrMsg, "can't redirect stdin");
168 return -1;
169 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000170 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000171 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000172 CloseHandle(si.hStdInput);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000173 MakeErrMsg(ErrMsg, "can't redirect stdout");
174 return -1;
175 }
176 if (redirects[1] && redirects[2] && *(redirects[1]) != *(redirects[2])) {
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000177 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000178 if (si.hStdError == INVALID_HANDLE_VALUE) {
179 CloseHandle(si.hStdInput);
180 CloseHandle(si.hStdOutput);
181 MakeErrMsg(ErrMsg, "can't redirect stderr");
182 return -1;
183 }
184 } else {
185 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
186 GetCurrentProcess(), &si.hStdError,
187 0, TRUE, DUPLICATE_SAME_ACCESS);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000188 }
189 }
Jeff Cohen0a182672007-03-05 05:22:08 +0000190
Reid Spencerb016a372004-09-15 05:49:50 +0000191 PROCESS_INFORMATION pi;
192 memset(&pi, 0, sizeof(pi));
193
Jeff Cohen875d08e2005-02-20 02:43:04 +0000194 fflush(stdout);
195 fflush(stderr);
196 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, FALSE, 0,
197 envp, NULL, &si, &pi);
198 DWORD err = GetLastError();
199
200 // Regardless of whether the process got created or not, we are done with
201 // the handles we created for it to inherit.
202 CloseHandle(si.hStdInput);
203 CloseHandle(si.hStdOutput);
204 CloseHandle(si.hStdError);
205
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000206 // Now return an error if the process didn't get created.
Jeff Cohen875d08e2005-02-20 02:43:04 +0000207 if (!rc)
Reid Spencerb016a372004-09-15 05:49:50 +0000208 {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000209 SetLastError(err);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000210 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
Reid Spencer707a27c2004-12-11 17:37:01 +0000211 path.toString() + "'");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000212 return -1;
Reid Spencerb016a372004-09-15 05:49:50 +0000213 }
214
Jeff Cohen0a182672007-03-05 05:22:08 +0000215 // Make sure these get closed no matter what.
216 AutoHandle hProcess(pi.hProcess);
217 AutoHandle hThread(pi.hThread);
218
219 // Assign the process to a job if a memory limit is defined.
220 AutoHandle hJob(0);
221 if (memoryLimit != 0) {
222 hJob = CreateJobObject(0, 0);
223 bool success = false;
224 if (hJob != 0) {
225 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
226 memset(&jeli, 0, sizeof(jeli));
227 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen413bc822007-03-05 05:45:08 +0000228 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohen0a182672007-03-05 05:22:08 +0000229 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
230 &jeli, sizeof(jeli))) {
231 if (AssignProcessToJobObject(hJob, pi.hProcess))
232 success = true;
233 }
234 }
235 if (!success) {
236 SetLastError(GetLastError());
237 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
238 TerminateProcess(pi.hProcess, 1);
239 WaitForSingleObject(pi.hProcess, INFINITE);
240 return -1;
241 }
242 }
243
Reid Spencerb016a372004-09-15 05:49:50 +0000244 // Wait for it to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000245 DWORD millisecondsToWait = INFINITE;
246 if (secondsToWait > 0)
247 millisecondsToWait = secondsToWait * 1000;
248
249 if (WaitForSingleObject(pi.hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
250 if (!TerminateProcess(pi.hProcess, 1)) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000251 MakeErrMsg(ErrMsg, std::string("Failed to terminate timed-out program '")
252 + path.toString() + "'");
253 return -1;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000254 }
255 WaitForSingleObject(pi.hProcess, INFINITE);
256 }
Reid Spencerb016a372004-09-15 05:49:50 +0000257
258 // Get its exit status.
259 DWORD status;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000260 rc = GetExitCodeProcess(pi.hProcess, &status);
261 err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000262
Jeff Cohen875d08e2005-02-20 02:43:04 +0000263 if (!rc) {
264 SetLastError(err);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000265 MakeErrMsg(ErrMsg, std::string("Failed getting status for program '") +
Reid Spencer707a27c2004-12-11 17:37:01 +0000266 path.toString() + "'");
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000267 return -1;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000268 }
Reid Spencerb016a372004-09-15 05:49:50 +0000269
270 return status;
271}
272
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000273bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000274 int result = _setmode( _fileno(stdin), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000275 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000276}
277
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000278bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000279 int result = _setmode( _fileno(stdout), _O_BINARY );
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000280 return result == -1;
Reid Spencer32f55532006-06-07 23:18:34 +0000281}
282
Reid Spencerb016a372004-09-15 05:49:50 +0000283}