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 //===----------------------------------------------------------------------===//
14 #include "WindowsSupport.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/Support/FileSystem.h"
22 //===----------------------------------------------------------------------===//
23 //=== WARNING: Implementation here must contain only Win32 specific code
24 //=== and must not be UNIX code
25 //===----------------------------------------------------------------------===//
30 ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
32 // This function just uses the PATH environment variable to find the program.
33 std::string sys::FindProgramByName(const std::string &progName) {
34 // Check some degenerate cases
35 if (progName.length() == 0) // no program
37 std::string temp = progName;
38 // Return paths with slashes verbatim.
39 if (progName.find('\\') != std::string::npos ||
40 progName.find('/') != std::string::npos)
43 // At this point, the file name is valid and does not contain slashes.
44 // Let Windows search for it.
45 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
46 if (windows::UTF8ToUTF16(progName, progNameUnicode))
49 SmallVector<wchar_t, MAX_PATH> buffer;
53 len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
54 buffer.capacity(), buffer.data(), NULL);
56 // See if it wasn't found.
60 // Buffer was too small; grow and retry.
61 } while (len > buffer.capacity());
64 SmallVector<char, MAX_PATH> result;
65 if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
68 return std::string(result.data(), result.size());
71 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
74 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
75 GetCurrentProcess(), &h,
76 0, TRUE, DUPLICATE_SAME_ACCESS))
77 return INVALID_HANDLE_VALUE;
87 SECURITY_ATTRIBUTES sa;
88 sa.nLength = sizeof(sa);
89 sa.lpSecurityDescriptor = 0;
90 sa.bInheritHandle = TRUE;
92 SmallVector<wchar_t, 128> fnameUnicode;
93 if (windows::UTF8ToUTF16(fname, fnameUnicode))
94 return INVALID_HANDLE_VALUE;
96 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
97 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
98 FILE_ATTRIBUTE_NORMAL, NULL);
99 if (h == INVALID_HANDLE_VALUE) {
100 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
101 (fd ? "input: " : "output: "));
107 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
109 static bool ArgNeedsQuotes(const char *Str) {
110 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
113 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
114 /// in the C string Start.
115 static unsigned int CountPrecedingBackslashes(const char *Start,
117 unsigned int Count = 0;
119 while (Cur >= Start && *Cur == '\\') {
126 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
127 /// preceding Cur in the Start string. Assumes Dst has enough space.
128 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
130 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
131 while (PrecedingEscapes > 0) {
138 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
139 /// CreateProcess and returns length of quoted arg with escaped quotes
140 static unsigned int ArgLenWithQuotes(const char *Str) {
141 const char *Start = Str;
142 bool Quoted = ArgNeedsQuotes(Str);
143 unsigned int len = Quoted ? 2 : 0;
145 while (*Str != '\0') {
147 // We need to add a backslash, but ensure that it isn't escaped.
148 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
149 len += PrecedingEscapes + 1;
151 // Note that we *don't* need to escape runs of backslashes that don't
152 // precede a double quote! See MSDN:
153 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
160 // Make sure the closing quote doesn't get escaped by a trailing backslash.
161 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
162 len += PrecedingEscapes + 1;
170 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
171 const char **envp, const StringRef **redirects,
172 unsigned memoryLimit, std::string *ErrMsg) {
173 if (!sys::fs::can_execute(Program)) {
175 *ErrMsg = "program not executable";
179 // Windows wants a command line, not an array of args, to pass to the new
180 // process. We have to concatenate them all, while quoting the args that
181 // have embedded spaces (or are empty).
183 // First, determine the length of the command line.
185 for (unsigned i = 0; args[i]; i++) {
186 len += ArgLenWithQuotes(args[i]) + 1;
189 // Now build the command line.
190 OwningArrayPtr<char> command(new char[len+1]);
191 char *p = command.get();
193 for (unsigned i = 0; args[i]; i++) {
194 const char *arg = args[i];
195 const char *start = arg;
197 bool needsQuoting = ArgNeedsQuotes(arg);
201 while (*arg != '\0') {
203 // Escape all preceding escapes (if any), and then escape the quote.
204 p = EscapePrecedingEscapes(p, start, arg);
212 // Make sure our quote doesn't get escaped by a trailing backslash.
213 p = EscapePrecedingEscapes(p, start, arg);
221 // The pointer to the environment block for the new process.
222 std::vector<wchar_t> EnvBlock;
225 // An environment block consists of a null-terminated block of
226 // null-terminated strings. Convert the array of environment variables to
227 // an environment block by concatenating them.
228 for (unsigned i = 0; envp[i]; ++i) {
229 SmallVector<wchar_t, MAX_PATH> EnvString;
230 if (error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
231 SetLastError(ec.value());
232 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
236 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
237 EnvBlock.push_back(0);
239 EnvBlock.push_back(0);
242 // Create a child process.
244 memset(&si, 0, sizeof(si));
246 si.hStdInput = INVALID_HANDLE_VALUE;
247 si.hStdOutput = INVALID_HANDLE_VALUE;
248 si.hStdError = INVALID_HANDLE_VALUE;
251 si.dwFlags = STARTF_USESTDHANDLES;
253 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
254 if (si.hStdInput == INVALID_HANDLE_VALUE) {
255 MakeErrMsg(ErrMsg, "can't redirect stdin");
258 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
259 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
260 CloseHandle(si.hStdInput);
261 MakeErrMsg(ErrMsg, "can't redirect stdout");
264 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
265 // If stdout and stderr should go to the same place, redirect stderr
266 // to the handle already open for stdout.
267 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
268 GetCurrentProcess(), &si.hStdError,
269 0, TRUE, DUPLICATE_SAME_ACCESS)) {
270 CloseHandle(si.hStdInput);
271 CloseHandle(si.hStdOutput);
272 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
276 // Just redirect stderr
277 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
278 if (si.hStdError == INVALID_HANDLE_VALUE) {
279 CloseHandle(si.hStdInput);
280 CloseHandle(si.hStdOutput);
281 MakeErrMsg(ErrMsg, "can't redirect stderr");
287 PROCESS_INFORMATION pi;
288 memset(&pi, 0, sizeof(pi));
293 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
294 if (error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
295 SetLastError(ec.value());
297 std::string("Unable to convert application name to UTF-16"));
301 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
302 if (error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
303 SetLastError(ec.value());
305 std::string("Unable to convert command-line to UTF-16"));
309 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
310 TRUE, CREATE_UNICODE_ENVIRONMENT,
311 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
313 DWORD err = GetLastError();
315 // Regardless of whether the process got created or not, we are done with
316 // the handles we created for it to inherit.
317 CloseHandle(si.hStdInput);
318 CloseHandle(si.hStdOutput);
319 CloseHandle(si.hStdError);
321 // Now return an error if the process didn't get created.
324 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
325 Program.str() + "'");
329 PI.Pid = pi.dwProcessId;
330 PI.ProcessHandle = pi.hProcess;
332 // Make sure these get closed no matter what.
333 ScopedCommonHandle hThread(pi.hThread);
335 // Assign the process to a job if a memory limit is defined.
336 ScopedJobHandle hJob;
337 if (memoryLimit != 0) {
338 hJob = CreateJobObjectW(0, 0);
339 bool success = false;
341 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
342 memset(&jeli, 0, sizeof(jeli));
343 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
344 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
345 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
346 &jeli, sizeof(jeli))) {
347 if (AssignProcessToJobObject(hJob, pi.hProcess))
352 SetLastError(GetLastError());
353 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
354 TerminateProcess(pi.hProcess, 1);
355 WaitForSingleObject(pi.hProcess, INFINITE);
364 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
365 bool WaitUntilChildTerminates, std::string *ErrMsg) {
366 assert(PI.Pid && "invalid pid to wait on, process not started?");
367 assert(PI.ProcessHandle &&
368 "invalid process handle to wait on, process not started?");
369 DWORD milliSecondsToWait = 0;
370 if (WaitUntilChildTerminates)
371 milliSecondsToWait = INFINITE;
372 else if (SecondsToWait > 0)
373 milliSecondsToWait = SecondsToWait * 1000;
375 ProcessInfo WaitResult = PI;
376 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
377 if (WaitStatus == WAIT_TIMEOUT) {
379 if (!TerminateProcess(PI.ProcessHandle, 1)) {
381 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
383 // -2 indicates a crash or timeout as opposed to failure to execute.
384 WaitResult.ReturnCode = -2;
385 CloseHandle(PI.ProcessHandle);
388 WaitForSingleObject(PI.ProcessHandle, INFINITE);
389 CloseHandle(PI.ProcessHandle);
391 // Non-blocking wait.
392 return ProcessInfo();
396 // Get its exit status.
398 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
399 DWORD err = GetLastError();
400 CloseHandle(PI.ProcessHandle);
405 MakeErrMsg(ErrMsg, "Failed getting status for program.");
407 // -2 indicates a crash or timeout as opposed to failure to execute.
408 WaitResult.ReturnCode = -2;
415 // Pass 10(Warning) and 11(Error) to the callee as negative value.
416 if ((status & 0xBFFF0000U) == 0x80000000U)
417 WaitResult.ReturnCode = static_cast<int>(status);
418 else if (status & 0xFF)
419 WaitResult.ReturnCode = status & 0x7FFFFFFF;
421 WaitResult.ReturnCode = 1;
426 error_code sys::ChangeStdinToBinary(){
427 int result = _setmode( _fileno(stdin), _O_BINARY );
429 return error_code(errno, generic_category());
430 return make_error_code(errc::success);
433 error_code sys::ChangeStdoutToBinary(){
434 int result = _setmode( _fileno(stdout), _O_BINARY );
436 return error_code(errno, generic_category());
437 return make_error_code(errc::success);
440 error_code sys::ChangeStderrToBinary(){
441 int result = _setmode( _fileno(stderr), _O_BINARY );
443 return error_code(errno, generic_category());
444 return make_error_code(errc::success);
447 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
448 // The documented max length of the command line passed to CreateProcess.
449 static const size_t MaxCommandStringLength = 32768;
450 size_t ArgLength = 0;
451 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
453 // Account for the trailing space for every arg but the last one and the
454 // trailing NULL of the last argument.
455 ArgLength += ArgLenWithQuotes(*I) + 1;
456 if (ArgLength > MaxCommandStringLength) {