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 // Ancient mingw32's w32api might not have this declaration.
28 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
29 JOBOBJECTINFOCLASS JobObjectInfoClass,
30 LPVOID lpJobObjectInfo,
31 DWORD cbJobObjectInfoLength);
35 struct Win32ProcessInfo {
44 Program::Program() : Data_(0) {}
48 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
49 CloseHandle(wpi->hProcess);
55 unsigned Program::GetPid() const {
56 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
57 return wpi->dwProcessId;
60 // This function just uses the PATH environment variable to find the program.
62 Program::FindProgramByName(const std::string& progName) {
64 // Check some degenerate cases
65 if (progName.length() == 0) // no program
68 if (!temp.set(progName)) // invalid name
70 // Return paths with slashes verbatim.
71 if (progName.find('\\') != std::string::npos ||
72 progName.find('/') != std::string::npos)
75 // At this point, the file name is valid and does not contain slashes.
76 // Let Windows search for it.
77 char buffer[MAX_PATH];
79 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
82 // See if it wasn't found.
86 // See if we got the entire path.
90 // Buffer was too small; grow and retry.
92 char *b = reinterpret_cast<char *>(_alloca(len+1));
93 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
95 // It is unlikely the search failed, but it's always possible some file
96 // was added or removed since the last search, so be paranoid...
106 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
109 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
110 GetCurrentProcess(), &h,
111 0, TRUE, DUPLICATE_SAME_ACCESS);
119 fname = path->c_str();
121 SECURITY_ATTRIBUTES sa;
122 sa.nLength = sizeof(sa);
123 sa.lpSecurityDescriptor = 0;
124 sa.bInheritHandle = TRUE;
126 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
127 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
128 FILE_ATTRIBUTE_NORMAL, NULL);
129 if (h == INVALID_HANDLE_VALUE) {
130 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
131 (fd ? "input: " : "output: "));
137 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
139 static bool ArgNeedsQuotes(const char *Str) {
140 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
144 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
145 /// CreateProcess and returns length of quoted arg with escaped quotes
146 static unsigned int ArgLenWithQuotes(const char *Str) {
147 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
149 while (*Str != '\0') {
162 Program::Execute(const Path& path,
165 const Path** redirects,
166 unsigned memoryLimit,
167 std::string* ErrMsg) {
169 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
170 CloseHandle(wpi->hProcess);
175 if (!path.canExecute()) {
177 *ErrMsg = "program not executable";
181 // Windows wants a command line, not an array of args, to pass to the new
182 // process. We have to concatenate them all, while quoting the args that
183 // have embedded spaces (or are empty).
185 // First, determine the length of the command line.
187 for (unsigned i = 0; args[i]; i++) {
188 len += ArgLenWithQuotes(args[i]) + 1;
191 // Now build the command line.
192 char *command = reinterpret_cast<char *>(_alloca(len+1));
195 for (unsigned i = 0; args[i]; i++) {
196 const char *arg = args[i];
198 bool needsQuoting = ArgNeedsQuotes(arg);
202 while (*arg != '\0') {
216 // The pointer to the environment block for the new process.
220 // An environment block consists of a null-terminated block of
221 // null-terminated strings. Convert the array of environment variables to
222 // an environment block by concatenating them.
224 // First, determine the length of the environment block.
226 for (unsigned i = 0; envp[i]; i++)
227 len += strlen(envp[i]) + 1;
229 // Now build the environment block.
230 envblock = reinterpret_cast<char *>(_alloca(len+1));
233 for (unsigned i = 0; envp[i]; i++) {
234 const char *ev = envp[i];
235 size_t len = strlen(ev) + 1;
243 // Create a child process.
245 memset(&si, 0, sizeof(si));
247 si.hStdInput = INVALID_HANDLE_VALUE;
248 si.hStdOutput = INVALID_HANDLE_VALUE;
249 si.hStdError = INVALID_HANDLE_VALUE;
252 si.dwFlags = STARTF_USESTDHANDLES;
254 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
255 if (si.hStdInput == INVALID_HANDLE_VALUE) {
256 MakeErrMsg(ErrMsg, "can't redirect stdin");
259 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
260 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
261 CloseHandle(si.hStdInput);
262 MakeErrMsg(ErrMsg, "can't redirect stdout");
265 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
266 // If stdout and stderr should go to the same place, redirect stderr
267 // to the handle already open for stdout.
268 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
269 GetCurrentProcess(), &si.hStdError,
270 0, TRUE, DUPLICATE_SAME_ACCESS);
272 // Just redirect stderr
273 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
274 if (si.hStdError == INVALID_HANDLE_VALUE) {
275 CloseHandle(si.hStdInput);
276 CloseHandle(si.hStdOutput);
277 MakeErrMsg(ErrMsg, "can't redirect stderr");
283 PROCESS_INFORMATION pi;
284 memset(&pi, 0, sizeof(pi));
288 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
289 envblock, NULL, &si, &pi);
290 DWORD err = GetLastError();
292 // Regardless of whether the process got created or not, we are done with
293 // the handles we created for it to inherit.
294 CloseHandle(si.hStdInput);
295 CloseHandle(si.hStdOutput);
296 CloseHandle(si.hStdError);
298 // Now return an error if the process didn't get created.
301 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
305 Win32ProcessInfo* wpi = new Win32ProcessInfo;
306 wpi->hProcess = pi.hProcess;
307 wpi->dwProcessId = pi.dwProcessId;
310 // Make sure these get closed no matter what.
311 AutoHandle hThread(pi.hThread);
313 // Assign the process to a job if a memory limit is defined.
315 if (memoryLimit != 0) {
316 hJob = CreateJobObject(0, 0);
317 bool success = false;
319 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
320 memset(&jeli, 0, sizeof(jeli));
321 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
322 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
323 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
324 &jeli, sizeof(jeli))) {
325 if (AssignProcessToJobObject(hJob, pi.hProcess))
330 SetLastError(GetLastError());
331 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
332 TerminateProcess(pi.hProcess, 1);
333 WaitForSingleObject(pi.hProcess, INFINITE);
342 Program::Wait(const Path &path,
343 unsigned secondsToWait,
344 std::string* ErrMsg) {
346 MakeErrMsg(ErrMsg, "Process not started!");
350 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
351 HANDLE hProcess = wpi->hProcess;
353 // Wait for the process to terminate.
354 DWORD millisecondsToWait = INFINITE;
355 if (secondsToWait > 0)
356 millisecondsToWait = secondsToWait * 1000;
358 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
359 if (!TerminateProcess(hProcess, 1)) {
360 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
363 WaitForSingleObject(hProcess, INFINITE);
366 // Get its exit status.
368 BOOL rc = GetExitCodeProcess(hProcess, &status);
369 DWORD err = GetLastError();
373 MakeErrMsg(ErrMsg, "Failed getting status for program.");
381 Program::Kill(std::string* ErrMsg) {
383 MakeErrMsg(ErrMsg, "Process not started!");
387 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
388 HANDLE hProcess = wpi->hProcess;
389 if (TerminateProcess(hProcess, 1) == 0) {
390 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
397 bool Program::ChangeStdinToBinary(){
398 int result = _setmode( _fileno(stdin), _O_BINARY );
402 bool Program::ChangeStdoutToBinary(){
403 int result = _setmode( _fileno(stdout), _O_BINARY );
407 bool Program::ChangeStderrToBinary(){
408 int result = _setmode( _fileno(stderr), _O_BINARY );