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 Program::Program() : Pid_(0), Data(0) {}
32 HANDLE hProcess = (HANDLE) Data;
33 CloseHandle(hProcess);
38 // This function just uses the PATH environment variable to find the program.
40 Program::FindProgramByName(const std::string& progName) {
42 // Check some degenerate cases
43 if (progName.length() == 0) // no program
46 if (!temp.set(progName)) // invalid name
48 if (temp.canExecute()) // already executable as is
51 // At this point, the file name is valid and its not executable.
52 // Let Windows search for it.
53 char buffer[MAX_PATH];
55 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
58 // See if it wasn't found.
62 // See if we got the entire path.
66 // Buffer was too small; grow and retry.
68 char *b = reinterpret_cast<char *>(_alloca(len+1));
69 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
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...
82 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
85 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
86 GetCurrentProcess(), &h,
87 0, TRUE, DUPLICATE_SAME_ACCESS);
95 fname = path->toString().c_str();
97 SECURITY_ATTRIBUTES sa;
98 sa.nLength = sizeof(sa);
99 sa.lpSecurityDescriptor = 0;
100 sa.bInheritHandle = TRUE;
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: "));
114 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
116 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
117 JOBOBJECTINFOCLASS JobObjectInfoClass,
118 LPVOID lpJobObjectInfo,
119 DWORD cbJobObjectInfoLength);
122 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
124 static bool ArgNeedsQuotes(const char *Str) {
125 return Str[0] == '\0' || strchr(Str, ' ') != 0;
129 Program::Execute(const Path& path,
132 const Path** redirects,
133 unsigned memoryLimit,
134 std::string* ErrMsg) {
136 HANDLE hProcess = (HANDLE) Data;
141 if (!path.canExecute()) {
143 *ErrMsg = "program not executable";
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
149 // have embedded spaces (or are empty).
151 // First, determine the length of the command line.
153 for (unsigned i = 0; args[i]; i++) {
154 len += strlen(args[i]) + 1;
155 if (ArgNeedsQuotes(args[i]))
159 // Now build the command line.
160 char *command = reinterpret_cast<char *>(_alloca(len+1));
163 for (unsigned i = 0; args[i]; i++) {
164 const char *arg = args[i];
165 size_t len = strlen(arg);
166 bool needsQuoting = ArgNeedsQuotes(arg);
178 // The pointer to the environment block for the new process.
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.
186 // First, determine the length of the environment block.
188 for (unsigned i = 0; envp[i]; i++)
189 len += strlen(envp[i]) + 1;
191 // Now build the environment block.
192 envblock = reinterpret_cast<char *>(_alloca(len+1));
195 for (unsigned i = 0; envp[i]; i++) {
196 const char *ev = envp[i];
197 size_t len = strlen(ev) + 1;
205 // Create a child process.
207 memset(&si, 0, sizeof(si));
209 si.hStdInput = INVALID_HANDLE_VALUE;
210 si.hStdOutput = INVALID_HANDLE_VALUE;
211 si.hStdError = INVALID_HANDLE_VALUE;
214 si.dwFlags = STARTF_USESTDHANDLES;
216 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
217 if (si.hStdInput == INVALID_HANDLE_VALUE) {
218 MakeErrMsg(ErrMsg, "can't redirect stdin");
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");
227 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);
234 // Just redirect stderr
235 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");
245 PROCESS_INFORMATION pi;
246 memset(&pi, 0, sizeof(pi));
250 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
251 envblock, NULL, &si, &pi);
252 DWORD err = GetLastError();
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);
260 // Now return an error if the process didn't get created.
264 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
265 path.toString() + "'");
268 Pid_ = pi.dwProcessId;
271 // Make sure these get closed no matter what.
272 AutoHandle hThread(pi.hThread);
274 // Assign the process to a job if a memory limit is defined.
276 if (memoryLimit != 0) {
277 hJob = CreateJobObject(0, 0);
278 bool success = false;
280 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
281 memset(&jeli, 0, sizeof(jeli));
282 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
283 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
284 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
285 &jeli, sizeof(jeli))) {
286 if (AssignProcessToJobObject(hJob, pi.hProcess))
291 SetLastError(GetLastError());
292 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
293 TerminateProcess(pi.hProcess, 1);
294 WaitForSingleObject(pi.hProcess, INFINITE);
303 Program::Wait(unsigned secondsToWait,
304 std::string* ErrMsg) {
306 MakeErrMsg(ErrMsg, "Process not started!");
310 HANDLE hProcess = (HANDLE) Data;
312 // Wait for the process to terminate.
313 DWORD millisecondsToWait = INFINITE;
314 if (secondsToWait > 0)
315 millisecondsToWait = secondsToWait * 1000;
317 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
318 if (!TerminateProcess(hProcess, 1)) {
319 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
322 WaitForSingleObject(hProcess, INFINITE);
325 // Get its exit status.
327 BOOL rc = GetExitCodeProcess(hProcess, &status);
328 DWORD err = GetLastError();
332 MakeErrMsg(ErrMsg, "Failed getting status for program.");
339 bool Program::ChangeStdinToBinary(){
340 int result = _setmode( _fileno(stdin), _O_BINARY );
344 bool Program::ChangeStdoutToBinary(){
345 int result = _setmode( _fileno(stdout), _O_BINARY );