1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Jeff Cohen and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Program class.
12 //===----------------------------------------------------------------------===//
20 //===----------------------------------------------------------------------===//
21 //=== WARNING: Implementation here must contain only Win32 specific code
22 //=== and must not be UNIX code
23 //===----------------------------------------------------------------------===//
28 // This function just uses the PATH environment variable to find the program.
30 Program::FindProgramByName(const std::string& progName) {
32 // Check some degenerate cases
33 if (progName.length() == 0) // no program
36 if (!temp.set(progName)) // invalid name
38 if (temp.canExecute()) // already executable as is
41 // At this point, the file name is valid and its not executable.
42 // Let Windows search for it.
43 char buffer[MAX_PATH];
45 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
48 // See if it wasn't found.
52 // See if we got the entire path.
56 // Buffer was too small; grow and retry.
58 char *b = reinterpret_cast<char *>(_alloca(len+1));
59 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
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...
72 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
75 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
76 GetCurrentProcess(), &h,
77 0, TRUE, DUPLICATE_SAME_ACCESS);
81 const char *fname = path->toString().c_str();
85 SECURITY_ATTRIBUTES sa;
86 sa.nLength = sizeof(sa);
87 sa.lpSecurityDescriptor = 0;
88 sa.bInheritHandle = TRUE;
90 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
91 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
92 FILE_ATTRIBUTE_NORMAL, NULL);
93 if (h == INVALID_HANDLE_VALUE) {
94 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
95 (fd ? "input: " : "output: "));
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);
110 Program::ExecuteAndWait(const Path& path,
113 const Path** redirects,
114 unsigned secondsToWait,
115 unsigned memoryLimit,
116 std::string* ErrMsg) {
117 if (!path.canExecute()) {
119 *ErrMsg = "program not executable";
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.
127 // First, determine the length of the command line.
129 for (unsigned i = 0; args[i]; i++) {
130 len += strlen(args[i]) + 1;
131 if (strchr(args[i], ' '))
135 // Now build the command line.
136 char *command = reinterpret_cast<char *>(_alloca(len));
139 for (unsigned i = 0; args[i]; i++) {
140 const char *arg = args[i];
141 size_t len = strlen(arg);
142 bool needsQuoting = strchr(arg, ' ') != 0;
154 // Create a child process.
156 memset(&si, 0, sizeof(si));
158 si.hStdInput = INVALID_HANDLE_VALUE;
159 si.hStdOutput = INVALID_HANDLE_VALUE;
160 si.hStdError = INVALID_HANDLE_VALUE;
163 si.dwFlags = STARTF_USESTDHANDLES;
165 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
166 if (si.hStdInput == INVALID_HANDLE_VALUE) {
167 MakeErrMsg(ErrMsg, "can't redirect stdin");
170 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
171 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
172 CloseHandle(si.hStdInput);
173 MakeErrMsg(ErrMsg, "can't redirect stdout");
176 if (redirects[1] && redirects[2] && *(redirects[1]) != *(redirects[2])) {
177 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
178 if (si.hStdError == INVALID_HANDLE_VALUE) {
179 CloseHandle(si.hStdInput);
180 CloseHandle(si.hStdOutput);
181 MakeErrMsg(ErrMsg, "can't redirect stderr");
185 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
186 GetCurrentProcess(), &si.hStdError,
187 0, TRUE, DUPLICATE_SAME_ACCESS);
191 PROCESS_INFORMATION pi;
192 memset(&pi, 0, sizeof(pi));
196 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, FALSE, 0,
197 envp, NULL, &si, &pi);
198 DWORD err = GetLastError();
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);
206 // Now return an error if the process didn't get created.
210 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
211 path.toString() + "'");
215 // Make sure these get closed no matter what.
216 AutoHandle hProcess(pi.hProcess);
217 AutoHandle hThread(pi.hThread);
219 // Assign the process to a job if a memory limit is defined.
221 if (memoryLimit != 0) {
222 hJob = CreateJobObject(0, 0);
223 bool success = false;
225 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
226 memset(&jeli, 0, sizeof(jeli));
227 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
228 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
229 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
230 &jeli, sizeof(jeli))) {
231 if (AssignProcessToJobObject(hJob, pi.hProcess))
236 SetLastError(GetLastError());
237 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
238 TerminateProcess(pi.hProcess, 1);
239 WaitForSingleObject(pi.hProcess, INFINITE);
244 // Wait for it to terminate.
245 DWORD millisecondsToWait = INFINITE;
246 if (secondsToWait > 0)
247 millisecondsToWait = secondsToWait * 1000;
249 if (WaitForSingleObject(pi.hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
250 if (!TerminateProcess(pi.hProcess, 1)) {
251 MakeErrMsg(ErrMsg, std::string("Failed to terminate timed-out program '")
252 + path.toString() + "'");
255 WaitForSingleObject(pi.hProcess, INFINITE);
258 // Get its exit status.
260 rc = GetExitCodeProcess(pi.hProcess, &status);
261 err = GetLastError();
265 MakeErrMsg(ErrMsg, std::string("Failed getting status for program '") +
266 path.toString() + "'");
273 bool Program::ChangeStdinToBinary(){
274 int result = _setmode( _fileno(stdin), _O_BINARY );
278 bool Program::ChangeStdoutToBinary(){
279 int result = _setmode( _fileno(stdout), _O_BINARY );