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 //===----------------------------------------------------------------------===//
26 struct Win32ProcessInfo {
35 Program::Program() : Data_(0) {}
39 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
40 CloseHandle(wpi->hProcess);
46 unsigned Program::GetPid() const {
47 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
48 return wpi->dwProcessId;
51 // This function just uses the PATH environment variable to find the program.
53 Program::FindProgramByName(const std::string& progName) {
55 // Check some degenerate cases
56 if (progName.length() == 0) // no program
59 if (!temp.set(progName)) // invalid name
61 // Return paths with slashes verbatim.
62 if (progName.find('\\') != std::string::npos ||
63 progName.find('/') != std::string::npos)
66 // At this point, the file name is valid and does not contain slashes.
67 // Let Windows search for it.
68 char buffer[MAX_PATH];
70 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
73 // See if it wasn't found.
77 // See if we got the entire path.
81 // Buffer was too small; grow and retry.
83 char *b = reinterpret_cast<char *>(_alloca(len+1));
84 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
86 // It is unlikely the search failed, but it's always possible some file
87 // was added or removed since the last search, so be paranoid...
97 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
100 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
101 GetCurrentProcess(), &h,
102 0, TRUE, DUPLICATE_SAME_ACCESS);
110 fname = path->c_str();
112 SECURITY_ATTRIBUTES sa;
113 sa.nLength = sizeof(sa);
114 sa.lpSecurityDescriptor = 0;
115 sa.bInheritHandle = TRUE;
117 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
118 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
119 FILE_ATTRIBUTE_NORMAL, NULL);
120 if (h == INVALID_HANDLE_VALUE) {
121 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
122 (fd ? "input: " : "output: "));
128 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
130 static bool ArgNeedsQuotes(const char *Str) {
131 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
135 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
136 /// CreateProcess and returns length of quoted arg with escaped quotes
137 static unsigned int ArgLenWithQuotes(const char *Str) {
138 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
140 while (*Str != '\0') {
153 Program::Execute(const Path& path,
156 const Path** redirects,
157 unsigned memoryLimit,
158 std::string* ErrMsg) {
160 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
161 CloseHandle(wpi->hProcess);
166 if (!path.canExecute()) {
168 *ErrMsg = "program not executable";
172 // Windows wants a command line, not an array of args, to pass to the new
173 // process. We have to concatenate them all, while quoting the args that
174 // have embedded spaces (or are empty).
176 // First, determine the length of the command line.
178 for (unsigned i = 0; args[i]; i++) {
179 len += ArgLenWithQuotes(args[i]) + 1;
182 // Now build the command line.
183 char *command = reinterpret_cast<char *>(_alloca(len+1));
186 for (unsigned i = 0; args[i]; i++) {
187 const char *arg = args[i];
189 bool needsQuoting = ArgNeedsQuotes(arg);
193 while (*arg != '\0') {
207 // The pointer to the environment block for the new process.
211 // An environment block consists of a null-terminated block of
212 // null-terminated strings. Convert the array of environment variables to
213 // an environment block by concatenating them.
215 // First, determine the length of the environment block.
217 for (unsigned i = 0; envp[i]; i++)
218 len += strlen(envp[i]) + 1;
220 // Now build the environment block.
221 envblock = reinterpret_cast<char *>(_alloca(len+1));
224 for (unsigned i = 0; envp[i]; i++) {
225 const char *ev = envp[i];
226 size_t len = strlen(ev) + 1;
234 // Create a child process.
236 memset(&si, 0, sizeof(si));
238 si.hStdInput = INVALID_HANDLE_VALUE;
239 si.hStdOutput = INVALID_HANDLE_VALUE;
240 si.hStdError = INVALID_HANDLE_VALUE;
243 si.dwFlags = STARTF_USESTDHANDLES;
245 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
246 if (si.hStdInput == INVALID_HANDLE_VALUE) {
247 MakeErrMsg(ErrMsg, "can't redirect stdin");
250 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
251 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
252 CloseHandle(si.hStdInput);
253 MakeErrMsg(ErrMsg, "can't redirect stdout");
256 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
257 // If stdout and stderr should go to the same place, redirect stderr
258 // to the handle already open for stdout.
259 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
260 GetCurrentProcess(), &si.hStdError,
261 0, TRUE, DUPLICATE_SAME_ACCESS);
263 // Just redirect stderr
264 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
265 if (si.hStdError == INVALID_HANDLE_VALUE) {
266 CloseHandle(si.hStdInput);
267 CloseHandle(si.hStdOutput);
268 MakeErrMsg(ErrMsg, "can't redirect stderr");
274 PROCESS_INFORMATION pi;
275 memset(&pi, 0, sizeof(pi));
279 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
280 envblock, NULL, &si, &pi);
281 DWORD err = GetLastError();
283 // Regardless of whether the process got created or not, we are done with
284 // the handles we created for it to inherit.
285 CloseHandle(si.hStdInput);
286 CloseHandle(si.hStdOutput);
287 CloseHandle(si.hStdError);
289 // Now return an error if the process didn't get created.
292 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
296 Win32ProcessInfo* wpi = new Win32ProcessInfo;
297 wpi->hProcess = pi.hProcess;
298 wpi->dwProcessId = pi.dwProcessId;
301 // Make sure these get closed no matter what.
302 AutoHandle hThread(pi.hThread);
304 // Assign the process to a job if a memory limit is defined.
306 if (memoryLimit != 0) {
307 hJob = CreateJobObject(0, 0);
308 bool success = false;
310 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
311 memset(&jeli, 0, sizeof(jeli));
312 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
313 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
314 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
315 &jeli, sizeof(jeli))) {
316 if (AssignProcessToJobObject(hJob, pi.hProcess))
321 SetLastError(GetLastError());
322 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
323 TerminateProcess(pi.hProcess, 1);
324 WaitForSingleObject(pi.hProcess, INFINITE);
333 Program::Wait(const Path &path,
334 unsigned secondsToWait,
335 std::string* ErrMsg) {
337 MakeErrMsg(ErrMsg, "Process not started!");
341 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
342 HANDLE hProcess = wpi->hProcess;
344 // Wait for the process to terminate.
345 DWORD millisecondsToWait = INFINITE;
346 if (secondsToWait > 0)
347 millisecondsToWait = secondsToWait * 1000;
349 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
350 if (!TerminateProcess(hProcess, 1)) {
351 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
352 // -2 indicates a crash or timeout as opposed to failure to execute.
355 WaitForSingleObject(hProcess, INFINITE);
358 // Get its exit status.
360 BOOL rc = GetExitCodeProcess(hProcess, &status);
361 DWORD err = GetLastError();
365 MakeErrMsg(ErrMsg, "Failed getting status for program.");
366 // -2 indicates a crash or timeout as opposed to failure to execute.
374 Program::Kill(std::string* ErrMsg) {
376 MakeErrMsg(ErrMsg, "Process not started!");
380 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
381 HANDLE hProcess = wpi->hProcess;
382 if (TerminateProcess(hProcess, 1) == 0) {
383 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
390 bool Program::ChangeStdinToBinary(){
391 int result = _setmode( _fileno(stdin), _O_BINARY );
395 bool Program::ChangeStdoutToBinary(){
396 int result = _setmode( _fileno(stdout), _O_BINARY );
400 bool Program::ChangeStderrToBinary(){
401 int result = _setmode( _fileno(stderr), _O_BINARY );