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/StringExtras.h"
16 #include "llvm/Support/ConvertUTF.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/WindowsError.h"
25 //===----------------------------------------------------------------------===//
26 //=== WARNING: Implementation here must contain only Win32 specific code
27 //=== and must not be UNIX code
28 //===----------------------------------------------------------------------===//
33 ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
35 // This function just uses the PATH environment variable to find the program.
36 std::string sys::FindProgramByName(const std::string &progName) {
37 // Check some degenerate cases
38 if (progName.length() == 0) // no program
40 std::string temp = progName;
41 // Return paths with slashes verbatim.
42 if (progName.find('\\') != std::string::npos ||
43 progName.find('/') != std::string::npos)
46 // At this point, the file name is valid and does not contain slashes.
47 // Let Windows search for it.
48 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
49 if (windows::UTF8ToUTF16(progName, progNameUnicode))
52 SmallVector<wchar_t, MAX_PATH> buffer;
56 len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
57 buffer.capacity(), buffer.data(), NULL);
59 // See if it wasn't found.
63 // Buffer was too small; grow and retry.
64 } while (len > buffer.capacity());
67 SmallVector<char, MAX_PATH> result;
68 if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
71 return std::string(result.data(), result.size());
74 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
75 ArrayRef<StringRef> Paths) {
76 assert(!Name.empty() && "Must have a name!");
78 if (Name.find_first_of("/\\") != StringRef::npos)
79 return std::string(Name);
81 const char16_t *Path = nullptr;
82 std::u16string PathStorage;
84 PathStorage.reserve(Paths.size() * MAX_PATH);
85 for (unsigned i = 0; i < Paths.size(); ++i) {
87 PathStorage.push_back(';');
88 StringRef P = Paths[i];
89 SmallVector<wchar_t, MAX_PATH> TmpPath;
90 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
92 PathStorage.append(TmpPath.begin(), TmpPath.end());
94 Path = PathStorage.c_str();
97 SmallVector<wchar_t, MAX_PATH> U16Name;
98 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
101 SmallVector<StringRef, 12> PathExts;
102 PathExts.push_back("");
103 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
104 SplitString(std::getenv("PATHEXT"), PathExts, ";");
106 SmallVector<wchar_t, MAX_PATH> U16Result;
107 DWORD Len = MAX_PATH;
108 for (StringRef Ext : PathExts) {
109 SmallVector<wchar_t, MAX_PATH> U16Ext;
110 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
114 U16Result.reserve(Len);
115 Len = ::SearchPathW((const wchar_t *)Path, c_str(U16Name),
116 U16Ext.empty() ? nullptr : c_str(U16Ext),
117 U16Result.capacity(), U16Result.data(), nullptr);
118 } while (Len > U16Result.capacity());
125 return mapWindowsError(::GetLastError());
127 U16Result.set_size(Len);
129 SmallVector<char, MAX_PATH> U8Result;
130 if (std::error_code EC =
131 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
134 return std::string(U8Result.begin(), U8Result.end());
137 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
140 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
141 GetCurrentProcess(), &h,
142 0, TRUE, DUPLICATE_SAME_ACCESS))
143 return INVALID_HANDLE_VALUE;
153 SECURITY_ATTRIBUTES sa;
154 sa.nLength = sizeof(sa);
155 sa.lpSecurityDescriptor = 0;
156 sa.bInheritHandle = TRUE;
158 SmallVector<wchar_t, 128> fnameUnicode;
159 if (windows::UTF8ToUTF16(fname, fnameUnicode))
160 return INVALID_HANDLE_VALUE;
162 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
163 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
164 FILE_ATTRIBUTE_NORMAL, NULL);
165 if (h == INVALID_HANDLE_VALUE) {
166 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
167 (fd ? "input: " : "output: "));
173 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
175 static bool ArgNeedsQuotes(const char *Str) {
176 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
179 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
180 /// in the C string Start.
181 static unsigned int CountPrecedingBackslashes(const char *Start,
183 unsigned int Count = 0;
185 while (Cur >= Start && *Cur == '\\') {
192 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
193 /// preceding Cur in the Start string. Assumes Dst has enough space.
194 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
196 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
197 while (PrecedingEscapes > 0) {
204 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
205 /// CreateProcess and returns length of quoted arg with escaped quotes
206 static unsigned int ArgLenWithQuotes(const char *Str) {
207 const char *Start = Str;
208 bool Quoted = ArgNeedsQuotes(Str);
209 unsigned int len = Quoted ? 2 : 0;
211 while (*Str != '\0') {
213 // We need to add a backslash, but ensure that it isn't escaped.
214 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
215 len += PrecedingEscapes + 1;
217 // Note that we *don't* need to escape runs of backslashes that don't
218 // precede a double quote! See MSDN:
219 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
226 // Make sure the closing quote doesn't get escaped by a trailing backslash.
227 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
228 len += PrecedingEscapes + 1;
236 static std::unique_ptr<char[]> flattenArgs(const char **args) {
237 // First, determine the length of the command line.
239 for (unsigned i = 0; args[i]; i++) {
240 len += ArgLenWithQuotes(args[i]) + 1;
243 // Now build the command line.
244 std::unique_ptr<char[]> command(new char[len+1]);
245 char *p = command.get();
247 for (unsigned i = 0; args[i]; i++) {
248 const char *arg = args[i];
249 const char *start = arg;
251 bool needsQuoting = ArgNeedsQuotes(arg);
255 while (*arg != '\0') {
257 // Escape all preceding escapes (if any), and then escape the quote.
258 p = EscapePrecedingEscapes(p, start, arg);
266 // Make sure our quote doesn't get escaped by a trailing backslash.
267 p = EscapePrecedingEscapes(p, start, arg);
277 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
278 const char **envp, const StringRef **redirects,
279 unsigned memoryLimit, std::string *ErrMsg) {
280 if (!sys::fs::can_execute(Program)) {
282 *ErrMsg = "program not executable";
286 // Windows wants a command line, not an array of args, to pass to the new
287 // process. We have to concatenate them all, while quoting the args that
288 // have embedded spaces (or are empty).
289 std::unique_ptr<char[]> command = flattenArgs(args);
291 // The pointer to the environment block for the new process.
292 std::vector<wchar_t> EnvBlock;
295 // An environment block consists of a null-terminated block of
296 // null-terminated strings. Convert the array of environment variables to
297 // an environment block by concatenating them.
298 for (unsigned i = 0; envp[i]; ++i) {
299 SmallVector<wchar_t, MAX_PATH> EnvString;
300 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
301 SetLastError(ec.value());
302 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
306 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
307 EnvBlock.push_back(0);
309 EnvBlock.push_back(0);
312 // Create a child process.
314 memset(&si, 0, sizeof(si));
316 si.hStdInput = INVALID_HANDLE_VALUE;
317 si.hStdOutput = INVALID_HANDLE_VALUE;
318 si.hStdError = INVALID_HANDLE_VALUE;
321 si.dwFlags = STARTF_USESTDHANDLES;
323 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
324 if (si.hStdInput == INVALID_HANDLE_VALUE) {
325 MakeErrMsg(ErrMsg, "can't redirect stdin");
328 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
329 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
330 CloseHandle(si.hStdInput);
331 MakeErrMsg(ErrMsg, "can't redirect stdout");
334 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
335 // If stdout and stderr should go to the same place, redirect stderr
336 // to the handle already open for stdout.
337 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
338 GetCurrentProcess(), &si.hStdError,
339 0, TRUE, DUPLICATE_SAME_ACCESS)) {
340 CloseHandle(si.hStdInput);
341 CloseHandle(si.hStdOutput);
342 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
346 // Just redirect stderr
347 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
348 if (si.hStdError == INVALID_HANDLE_VALUE) {
349 CloseHandle(si.hStdInput);
350 CloseHandle(si.hStdOutput);
351 MakeErrMsg(ErrMsg, "can't redirect stderr");
357 PROCESS_INFORMATION pi;
358 memset(&pi, 0, sizeof(pi));
363 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
364 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
365 SetLastError(ec.value());
367 std::string("Unable to convert application name to UTF-16"));
371 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
372 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
373 SetLastError(ec.value());
375 std::string("Unable to convert command-line to UTF-16"));
379 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
380 TRUE, CREATE_UNICODE_ENVIRONMENT,
381 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
383 DWORD err = GetLastError();
385 // Regardless of whether the process got created or not, we are done with
386 // the handles we created for it to inherit.
387 CloseHandle(si.hStdInput);
388 CloseHandle(si.hStdOutput);
389 CloseHandle(si.hStdError);
391 // Now return an error if the process didn't get created.
394 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
395 Program.str() + "'");
399 PI.Pid = pi.dwProcessId;
400 PI.ProcessHandle = pi.hProcess;
402 // Make sure these get closed no matter what.
403 ScopedCommonHandle hThread(pi.hThread);
405 // Assign the process to a job if a memory limit is defined.
406 ScopedJobHandle hJob;
407 if (memoryLimit != 0) {
408 hJob = CreateJobObjectW(0, 0);
409 bool success = false;
411 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
412 memset(&jeli, 0, sizeof(jeli));
413 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
414 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
415 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
416 &jeli, sizeof(jeli))) {
417 if (AssignProcessToJobObject(hJob, pi.hProcess))
422 SetLastError(GetLastError());
423 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
424 TerminateProcess(pi.hProcess, 1);
425 WaitForSingleObject(pi.hProcess, INFINITE);
434 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
435 bool WaitUntilChildTerminates, std::string *ErrMsg) {
436 assert(PI.Pid && "invalid pid to wait on, process not started?");
437 assert(PI.ProcessHandle &&
438 "invalid process handle to wait on, process not started?");
439 DWORD milliSecondsToWait = 0;
440 if (WaitUntilChildTerminates)
441 milliSecondsToWait = INFINITE;
442 else if (SecondsToWait > 0)
443 milliSecondsToWait = SecondsToWait * 1000;
445 ProcessInfo WaitResult = PI;
446 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
447 if (WaitStatus == WAIT_TIMEOUT) {
449 if (!TerminateProcess(PI.ProcessHandle, 1)) {
451 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
453 // -2 indicates a crash or timeout as opposed to failure to execute.
454 WaitResult.ReturnCode = -2;
455 CloseHandle(PI.ProcessHandle);
458 WaitForSingleObject(PI.ProcessHandle, INFINITE);
459 CloseHandle(PI.ProcessHandle);
461 // Non-blocking wait.
462 return ProcessInfo();
466 // Get its exit status.
468 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
469 DWORD err = GetLastError();
470 CloseHandle(PI.ProcessHandle);
475 MakeErrMsg(ErrMsg, "Failed getting status for program.");
477 // -2 indicates a crash or timeout as opposed to failure to execute.
478 WaitResult.ReturnCode = -2;
485 // Pass 10(Warning) and 11(Error) to the callee as negative value.
486 if ((status & 0xBFFF0000U) == 0x80000000U)
487 WaitResult.ReturnCode = static_cast<int>(status);
488 else if (status & 0xFF)
489 WaitResult.ReturnCode = status & 0x7FFFFFFF;
491 WaitResult.ReturnCode = 1;
496 std::error_code sys::ChangeStdinToBinary() {
497 int result = _setmode(_fileno(stdin), _O_BINARY);
499 return std::error_code(errno, std::generic_category());
500 return std::error_code();
503 std::error_code sys::ChangeStdoutToBinary() {
504 int result = _setmode(_fileno(stdout), _O_BINARY);
506 return std::error_code(errno, std::generic_category());
507 return std::error_code();
511 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
512 WindowsEncodingMethod Encoding) {
514 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
518 if (Encoding == WEM_UTF8) {
520 } else if (Encoding == WEM_CurrentCodePage) {
521 SmallVector<wchar_t, 1> ArgsUTF16;
522 SmallVector<char, 1> ArgsCurCP;
524 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
527 if ((EC = windows::UTF16ToCurCP(
528 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
531 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
532 } else if (Encoding == WEM_UTF16) {
533 SmallVector<wchar_t, 1> ArgsUTF16;
535 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
538 // Endianness guessing
540 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
541 memcpy(BOM, &src, 2);
543 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
545 llvm_unreachable("Unknown encoding");
549 return std::make_error_code(std::errc::io_error);
554 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
555 // The documented max length of the command line passed to CreateProcess.
556 static const size_t MaxCommandStringLength = 32768;
557 size_t ArgLength = 0;
558 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
560 // Account for the trailing space for every arg but the last one and the
561 // trailing NULL of the last argument.
562 ArgLength += ArgLenWithQuotes(*I) + 1;
563 if (ArgLength > MaxCommandStringLength) {