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() : Data_(0) {}
32 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
33 CloseHandle(hProcess);
38 unsigned Program::GetPid() const {
39 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
40 return GetProcessId(hProcess);
43 // This function just uses the PATH environment variable to find the program.
45 Program::FindProgramByName(const std::string& progName) {
47 // Check some degenerate cases
48 if (progName.length() == 0) // no program
51 if (!temp.set(progName)) // invalid name
53 if (temp.canExecute()) // already executable as is
56 // At this point, the file name is valid and its not executable.
57 // Let Windows search for it.
58 char buffer[MAX_PATH];
60 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
63 // See if it wasn't found.
67 // See if we got the entire path.
71 // Buffer was too small; grow and retry.
73 char *b = reinterpret_cast<char *>(_alloca(len+1));
74 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
76 // It is unlikely the search failed, but it's always possible some file
77 // was added or removed since the last search, so be paranoid...
87 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
90 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
91 GetCurrentProcess(), &h,
92 0, TRUE, DUPLICATE_SAME_ACCESS);
100 fname = path->c_str();
102 SECURITY_ATTRIBUTES sa;
103 sa.nLength = sizeof(sa);
104 sa.lpSecurityDescriptor = 0;
105 sa.bInheritHandle = TRUE;
107 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
108 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
109 FILE_ATTRIBUTE_NORMAL, NULL);
110 if (h == INVALID_HANDLE_VALUE) {
111 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
112 (fd ? "input: " : "output: "));
119 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
121 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
122 JOBOBJECTINFOCLASS JobObjectInfoClass,
123 LPVOID lpJobObjectInfo,
124 DWORD cbJobObjectInfoLength);
127 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
129 static bool ArgNeedsQuotes(const char *Str) {
130 return Str[0] == '\0' || strchr(Str, ' ') != 0;
134 Program::Execute(const Path& path,
137 const Path** redirects,
138 unsigned memoryLimit,
139 std::string* ErrMsg) {
141 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
146 if (!path.canExecute()) {
148 *ErrMsg = "program not executable";
152 // Windows wants a command line, not an array of args, to pass to the new
153 // process. We have to concatenate them all, while quoting the args that
154 // have embedded spaces (or are empty).
156 // First, determine the length of the command line.
158 for (unsigned i = 0; args[i]; i++) {
159 len += strlen(args[i]) + 1;
160 if (ArgNeedsQuotes(args[i]))
164 // Now build the command line.
165 char *command = reinterpret_cast<char *>(_alloca(len+1));
168 for (unsigned i = 0; args[i]; i++) {
169 const char *arg = args[i];
170 size_t len = strlen(arg);
171 bool needsQuoting = ArgNeedsQuotes(arg);
183 // The pointer to the environment block for the new process.
187 // An environment block consists of a null-terminated block of
188 // null-terminated strings. Convert the array of environment variables to
189 // an environment block by concatenating them.
191 // First, determine the length of the environment block.
193 for (unsigned i = 0; envp[i]; i++)
194 len += strlen(envp[i]) + 1;
196 // Now build the environment block.
197 envblock = reinterpret_cast<char *>(_alloca(len+1));
200 for (unsigned i = 0; envp[i]; i++) {
201 const char *ev = envp[i];
202 size_t len = strlen(ev) + 1;
210 // Create a child process.
212 memset(&si, 0, sizeof(si));
214 si.hStdInput = INVALID_HANDLE_VALUE;
215 si.hStdOutput = INVALID_HANDLE_VALUE;
216 si.hStdError = INVALID_HANDLE_VALUE;
219 si.dwFlags = STARTF_USESTDHANDLES;
221 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
222 if (si.hStdInput == INVALID_HANDLE_VALUE) {
223 MakeErrMsg(ErrMsg, "can't redirect stdin");
226 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
227 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
228 CloseHandle(si.hStdInput);
229 MakeErrMsg(ErrMsg, "can't redirect stdout");
232 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
233 // If stdout and stderr should go to the same place, redirect stderr
234 // to the handle already open for stdout.
235 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
236 GetCurrentProcess(), &si.hStdError,
237 0, TRUE, DUPLICATE_SAME_ACCESS);
239 // Just redirect stderr
240 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
241 if (si.hStdError == INVALID_HANDLE_VALUE) {
242 CloseHandle(si.hStdInput);
243 CloseHandle(si.hStdOutput);
244 MakeErrMsg(ErrMsg, "can't redirect stderr");
250 PROCESS_INFORMATION pi;
251 memset(&pi, 0, sizeof(pi));
255 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
256 envblock, NULL, &si, &pi);
257 DWORD err = GetLastError();
259 // Regardless of whether the process got created or not, we are done with
260 // the handles we created for it to inherit.
261 CloseHandle(si.hStdInput);
262 CloseHandle(si.hStdOutput);
263 CloseHandle(si.hStdError);
265 // Now return an error if the process didn't get created.
268 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
272 Data_ = reinterpret_cast<void*>(pi.hProcess);
274 // Make sure these get closed no matter what.
275 AutoHandle hThread(pi.hThread);
277 // Assign the process to a job if a memory limit is defined.
279 if (memoryLimit != 0) {
280 hJob = CreateJobObject(0, 0);
281 bool success = false;
283 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
284 memset(&jeli, 0, sizeof(jeli));
285 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
286 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
287 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
288 &jeli, sizeof(jeli))) {
289 if (AssignProcessToJobObject(hJob, pi.hProcess))
294 SetLastError(GetLastError());
295 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
296 TerminateProcess(pi.hProcess, 1);
297 WaitForSingleObject(pi.hProcess, INFINITE);
306 Program::Wait(unsigned secondsToWait,
307 std::string* ErrMsg) {
309 MakeErrMsg(ErrMsg, "Process not started!");
313 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
315 // Wait for the process to terminate.
316 DWORD millisecondsToWait = INFINITE;
317 if (secondsToWait > 0)
318 millisecondsToWait = secondsToWait * 1000;
320 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
321 if (!TerminateProcess(hProcess, 1)) {
322 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
325 WaitForSingleObject(hProcess, INFINITE);
328 // Get its exit status.
330 BOOL rc = GetExitCodeProcess(hProcess, &status);
331 DWORD err = GetLastError();
335 MakeErrMsg(ErrMsg, "Failed getting status for program.");
343 Program::Kill(std::string* ErrMsg) {
345 MakeErrMsg(ErrMsg, "Process not started!");
349 HANDLE hProcess = reinterpret_cast<HANDLE>(Data_);
350 if (TerminateProcess(hProcess, 1) == 0) {
351 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
358 bool Program::ChangeStdinToBinary(){
359 int result = _setmode( _fileno(stdin), _O_BINARY );
363 bool Program::ChangeStdoutToBinary(){
364 int result = _setmode( _fileno(stdout), _O_BINARY );