1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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.
104 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
105 JOBOBJECTINFOCLASS JobObjectInfoClass,
106 LPVOID lpJobObjectInfo,
107 DWORD cbJobObjectInfoLength);
111 Program::ExecuteAndWait(const Path& path,
114 const Path** redirects,
115 unsigned secondsToWait,
116 unsigned memoryLimit,
117 std::string* ErrMsg) {
118 if (!path.canExecute()) {
120 *ErrMsg = "program not executable";
124 // Windows wants a command line, not an array of args, to pass to the new
125 // process. We have to concatenate them all, while quoting the args that
126 // have embedded spaces.
128 // First, determine the length of the command line.
130 for (unsigned i = 0; args[i]; i++) {
131 len += strlen(args[i]) + 1;
132 if (strchr(args[i], ' '))
136 // Now build the command line.
137 char *command = reinterpret_cast<char *>(_alloca(len+1));
140 for (unsigned i = 0; args[i]; i++) {
141 const char *arg = args[i];
142 size_t len = strlen(arg);
143 bool needsQuoting = strchr(arg, ' ') != 0;
155 // Create a child process.
157 memset(&si, 0, sizeof(si));
159 si.hStdInput = INVALID_HANDLE_VALUE;
160 si.hStdOutput = INVALID_HANDLE_VALUE;
161 si.hStdError = INVALID_HANDLE_VALUE;
164 si.dwFlags = STARTF_USESTDHANDLES;
166 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
167 if (si.hStdInput == INVALID_HANDLE_VALUE) {
168 MakeErrMsg(ErrMsg, "can't redirect stdin");
171 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
172 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
173 CloseHandle(si.hStdInput);
174 MakeErrMsg(ErrMsg, "can't redirect stdout");
177 if (redirects[1] && redirects[2] && *(redirects[1]) != *(redirects[2])) {
178 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
179 if (si.hStdError == INVALID_HANDLE_VALUE) {
180 CloseHandle(si.hStdInput);
181 CloseHandle(si.hStdOutput);
182 MakeErrMsg(ErrMsg, "can't redirect stderr");
186 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
187 GetCurrentProcess(), &si.hStdError,
188 0, TRUE, DUPLICATE_SAME_ACCESS);
192 PROCESS_INFORMATION pi;
193 memset(&pi, 0, sizeof(pi));
197 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, FALSE, 0,
198 envp, NULL, &si, &pi);
199 DWORD err = GetLastError();
201 // Regardless of whether the process got created or not, we are done with
202 // the handles we created for it to inherit.
203 CloseHandle(si.hStdInput);
204 CloseHandle(si.hStdOutput);
205 CloseHandle(si.hStdError);
207 // Now return an error if the process didn't get created.
211 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
212 path.toString() + "'");
216 // Make sure these get closed no matter what.
217 AutoHandle hProcess(pi.hProcess);
218 AutoHandle hThread(pi.hThread);
220 // Assign the process to a job if a memory limit is defined.
222 if (memoryLimit != 0) {
223 hJob = CreateJobObject(0, 0);
224 bool success = false;
226 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
227 memset(&jeli, 0, sizeof(jeli));
228 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
229 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
230 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
231 &jeli, sizeof(jeli))) {
232 if (AssignProcessToJobObject(hJob, pi.hProcess))
237 SetLastError(GetLastError());
238 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
239 TerminateProcess(pi.hProcess, 1);
240 WaitForSingleObject(pi.hProcess, INFINITE);
245 // Wait for it to terminate.
246 DWORD millisecondsToWait = INFINITE;
247 if (secondsToWait > 0)
248 millisecondsToWait = secondsToWait * 1000;
250 if (WaitForSingleObject(pi.hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
251 if (!TerminateProcess(pi.hProcess, 1)) {
252 MakeErrMsg(ErrMsg, std::string("Failed to terminate timed-out program '")
253 + path.toString() + "'");
256 WaitForSingleObject(pi.hProcess, INFINITE);
259 // Get its exit status.
261 rc = GetExitCodeProcess(pi.hProcess, &status);
262 err = GetLastError();
266 MakeErrMsg(ErrMsg, std::string("Failed getting status for program '") +
267 path.toString() + "'");
274 bool Program::ChangeStdinToBinary(){
275 int result = _setmode( _fileno(stdin), _O_BINARY );
279 bool Program::ChangeStdoutToBinary(){
280 int result = _setmode( _fileno(stdout), _O_BINARY );