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);
85 fname = path->c_str();
87 SECURITY_ATTRIBUTES sa;
88 sa.nLength = sizeof(sa);
89 sa.lpSecurityDescriptor = 0;
90 sa.bInheritHandle = TRUE;
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: "));
104 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
106 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
107 JOBOBJECTINFOCLASS JobObjectInfoClass,
108 LPVOID lpJobObjectInfo,
109 DWORD cbJobObjectInfoLength);
112 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
114 static bool ArgNeedsQuotes(const char *Str) {
115 return Str[0] == '\0' || strchr(Str, ' ') != 0;
119 Program::Execute(const Path& path,
122 const Path** redirects,
123 unsigned memoryLimit,
124 std::string* ErrMsg) {
126 if (!path.canExecute()) {
128 *ErrMsg = "program not executable";
132 // Windows wants a command line, not an array of args, to pass to the new
133 // process. We have to concatenate them all, while quoting the args that
134 // have embedded spaces (or are empty).
136 // First, determine the length of the command line.
138 for (unsigned i = 0; args[i]; i++) {
139 len += strlen(args[i]) + 1;
140 if (ArgNeedsQuotes(args[i]))
144 // Now build the command line.
145 char *command = reinterpret_cast<char *>(_alloca(len+1));
148 for (unsigned i = 0; args[i]; i++) {
149 const char *arg = args[i];
150 size_t len = strlen(arg);
151 bool needsQuoting = ArgNeedsQuotes(arg);
163 // The pointer to the environment block for the new process.
167 // An environment block consists of a null-terminated block of
168 // null-terminated strings. Convert the array of environment variables to
169 // an environment block by concatenating them.
171 // First, determine the length of the environment block.
173 for (unsigned i = 0; envp[i]; i++)
174 len += strlen(envp[i]) + 1;
176 // Now build the environment block.
177 envblock = reinterpret_cast<char *>(_alloca(len+1));
180 for (unsigned i = 0; envp[i]; i++) {
181 const char *ev = envp[i];
182 size_t len = strlen(ev) + 1;
190 // Create a child process.
192 memset(&si, 0, sizeof(si));
194 si.hStdInput = INVALID_HANDLE_VALUE;
195 si.hStdOutput = INVALID_HANDLE_VALUE;
196 si.hStdError = INVALID_HANDLE_VALUE;
199 si.dwFlags = STARTF_USESTDHANDLES;
201 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
202 if (si.hStdInput == INVALID_HANDLE_VALUE) {
203 MakeErrMsg(ErrMsg, "can't redirect stdin");
206 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
207 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
208 CloseHandle(si.hStdInput);
209 MakeErrMsg(ErrMsg, "can't redirect stdout");
212 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
213 // If stdout and stderr should go to the same place, redirect stderr
214 // to the handle already open for stdout.
215 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
216 GetCurrentProcess(), &si.hStdError,
217 0, TRUE, DUPLICATE_SAME_ACCESS);
219 // Just redirect stderr
220 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
221 if (si.hStdError == INVALID_HANDLE_VALUE) {
222 CloseHandle(si.hStdInput);
223 CloseHandle(si.hStdOutput);
224 MakeErrMsg(ErrMsg, "can't redirect stderr");
230 PROCESS_INFORMATION pi;
231 memset(&pi, 0, sizeof(pi));
235 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
236 envblock, NULL, &si, &pi);
237 DWORD err = GetLastError();
239 // Regardless of whether the process got created or not, we are done with
240 // the handles we created for it to inherit.
241 CloseHandle(si.hStdInput);
242 CloseHandle(si.hStdOutput);
243 CloseHandle(si.hStdError);
245 // Now return an error if the process didn't get created.
248 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
252 Pid_ = pi.dwProcessId;
254 // Make sure these get closed no matter what.
255 AutoHandle hProcess(pi.hProcess);
256 AutoHandle hThread(pi.hThread);
258 // Assign the process to a job if a memory limit is defined.
260 if (memoryLimit != 0) {
261 hJob = CreateJobObject(0, 0);
262 bool success = false;
264 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
265 memset(&jeli, 0, sizeof(jeli));
266 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
267 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
268 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
269 &jeli, sizeof(jeli))) {
270 if (AssignProcessToJobObject(hJob, pi.hProcess))
275 SetLastError(GetLastError());
276 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
277 TerminateProcess(pi.hProcess, 1);
278 WaitForSingleObject(pi.hProcess, INFINITE);
287 Program::Wait(unsigned secondsToWait,
288 std::string* ErrMsg) {
290 MakeErrMsg(ErrMsg, "Process not started!");
294 HANDLE hOpen = OpenProcess(SYNCHRONIZE, FALSE, Pid_);
296 MakeErrMsg(ErrMsg, "OpenProcess failed!");
299 AutoHandle hProcess(hOpen);
301 // Wait for the process to terminate.
302 DWORD millisecondsToWait = INFINITE;
303 if (secondsToWait > 0)
304 millisecondsToWait = secondsToWait * 1000;
306 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
307 if (!TerminateProcess(hProcess, 1)) {
308 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
311 WaitForSingleObject(hProcess, INFINITE);
314 // Get its exit status.
316 BOOL rc = GetExitCodeProcess(hProcess, &status);
317 DWORD err = GetLastError();
321 MakeErrMsg(ErrMsg, "Failed getting status for program.");
329 Program::Kill(std::string* ErrMsg) {
331 MakeErrMsg(ErrMsg, "Process not started!");
335 HANDLE hOpen = OpenProcess(PROCESS_TERMINATE, FALSE, Pid_);
337 MakeErrMsg(ErrMsg, "OpenProcess failed!");
340 AutoHandle hProcess(hOpen);
342 if (TerminateProcess(hProcess, 1) == 0) {
343 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
350 bool Program::ChangeStdinToBinary(){
351 int result = _setmode( _fileno(stdin), _O_BINARY );
355 bool Program::ChangeStdoutToBinary(){
356 int result = _setmode( _fileno(stdout), _O_BINARY );