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/Errc.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/WindowsError.h"
20 #include "llvm/Support/raw_ostream.h"
26 //===----------------------------------------------------------------------===//
27 //=== WARNING: Implementation here must contain only Win32 specific code
28 //=== and must not be UNIX code
29 //===----------------------------------------------------------------------===//
34 ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
36 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
37 ArrayRef<StringRef> Paths) {
38 assert(!Name.empty() && "Must have a name!");
40 if (Name.find_first_of("/\\") != StringRef::npos)
41 return std::string(Name);
43 const wchar_t *Path = nullptr;
44 std::wstring PathStorage;
46 PathStorage.reserve(Paths.size() * MAX_PATH);
47 for (unsigned i = 0; i < Paths.size(); ++i) {
49 PathStorage.push_back(L';');
50 StringRef P = Paths[i];
51 SmallVector<wchar_t, MAX_PATH> TmpPath;
52 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
54 PathStorage.append(TmpPath.begin(), TmpPath.end());
56 Path = PathStorage.c_str();
59 SmallVector<wchar_t, MAX_PATH> U16Name;
60 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
63 SmallVector<StringRef, 12> PathExts;
64 PathExts.push_back("");
65 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
66 if (const char *PathExtEnv = std::getenv("PATHEXT"))
67 SplitString(PathExtEnv, PathExts, ";");
69 SmallVector<wchar_t, MAX_PATH> U16Result;
71 for (StringRef Ext : PathExts) {
72 SmallVector<wchar_t, MAX_PATH> U16Ext;
73 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
77 U16Result.reserve(Len);
78 Len = ::SearchPathW(Path, c_str(U16Name),
79 U16Ext.empty() ? nullptr : c_str(U16Ext),
80 U16Result.capacity(), U16Result.data(), nullptr);
81 } while (Len > U16Result.capacity());
88 return mapWindowsError(::GetLastError());
90 U16Result.set_size(Len);
92 SmallVector<char, MAX_PATH> U8Result;
93 if (std::error_code EC =
94 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
97 return std::string(U8Result.begin(), U8Result.end());
100 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
103 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
104 GetCurrentProcess(), &h,
105 0, TRUE, DUPLICATE_SAME_ACCESS))
106 return INVALID_HANDLE_VALUE;
116 SECURITY_ATTRIBUTES sa;
117 sa.nLength = sizeof(sa);
118 sa.lpSecurityDescriptor = 0;
119 sa.bInheritHandle = TRUE;
121 SmallVector<wchar_t, 128> fnameUnicode;
123 // Don't play long-path tricks on "NUL".
124 if (windows::UTF8ToUTF16(fname, fnameUnicode))
125 return INVALID_HANDLE_VALUE;
127 if (path::widenPath(fname, fnameUnicode))
128 return INVALID_HANDLE_VALUE;
130 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
131 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
132 FILE_ATTRIBUTE_NORMAL, NULL);
133 if (h == INVALID_HANDLE_VALUE) {
134 MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
135 (fd ? "input: " : "output: "));
141 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
143 static bool ArgNeedsQuotes(const char *Str) {
144 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
147 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
148 /// in the C string Start.
149 static unsigned int CountPrecedingBackslashes(const char *Start,
151 unsigned int Count = 0;
153 while (Cur >= Start && *Cur == '\\') {
160 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
161 /// preceding Cur in the Start string. Assumes Dst has enough space.
162 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
164 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
165 while (PrecedingEscapes > 0) {
172 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
173 /// CreateProcess and returns length of quoted arg with escaped quotes
174 static unsigned int ArgLenWithQuotes(const char *Str) {
175 const char *Start = Str;
176 bool Quoted = ArgNeedsQuotes(Str);
177 unsigned int len = Quoted ? 2 : 0;
179 while (*Str != '\0') {
181 // We need to add a backslash, but ensure that it isn't escaped.
182 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
183 len += PrecedingEscapes + 1;
185 // Note that we *don't* need to escape runs of backslashes that don't
186 // precede a double quote! See MSDN:
187 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
194 // Make sure the closing quote doesn't get escaped by a trailing backslash.
195 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
196 len += PrecedingEscapes + 1;
204 static std::unique_ptr<char[]> flattenArgs(const char **args) {
205 // First, determine the length of the command line.
207 for (unsigned i = 0; args[i]; i++) {
208 len += ArgLenWithQuotes(args[i]) + 1;
211 // Now build the command line.
212 std::unique_ptr<char[]> command(new char[len+1]);
213 char *p = command.get();
215 for (unsigned i = 0; args[i]; i++) {
216 const char *arg = args[i];
217 const char *start = arg;
219 bool needsQuoting = ArgNeedsQuotes(arg);
223 while (*arg != '\0') {
225 // Escape all preceding escapes (if any), and then escape the quote.
226 p = EscapePrecedingEscapes(p, start, arg);
234 // Make sure our quote doesn't get escaped by a trailing backslash.
235 p = EscapePrecedingEscapes(p, start, arg);
245 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
246 const char **envp, const StringRef **redirects,
247 unsigned memoryLimit, std::string *ErrMsg) {
248 if (!sys::fs::can_execute(Program)) {
250 *ErrMsg = "program not executable";
254 // Windows wants a command line, not an array of args, to pass to the new
255 // process. We have to concatenate them all, while quoting the args that
256 // have embedded spaces (or are empty).
257 std::unique_ptr<char[]> command = flattenArgs(args);
259 // The pointer to the environment block for the new process.
260 std::vector<wchar_t> EnvBlock;
263 // An environment block consists of a null-terminated block of
264 // null-terminated strings. Convert the array of environment variables to
265 // an environment block by concatenating them.
266 for (unsigned i = 0; envp[i]; ++i) {
267 SmallVector<wchar_t, MAX_PATH> EnvString;
268 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
269 SetLastError(ec.value());
270 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
274 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
275 EnvBlock.push_back(0);
277 EnvBlock.push_back(0);
280 // Create a child process.
282 memset(&si, 0, sizeof(si));
284 si.hStdInput = INVALID_HANDLE_VALUE;
285 si.hStdOutput = INVALID_HANDLE_VALUE;
286 si.hStdError = INVALID_HANDLE_VALUE;
289 si.dwFlags = STARTF_USESTDHANDLES;
291 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
292 if (si.hStdInput == INVALID_HANDLE_VALUE) {
293 MakeErrMsg(ErrMsg, "can't redirect stdin");
296 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
297 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
298 CloseHandle(si.hStdInput);
299 MakeErrMsg(ErrMsg, "can't redirect stdout");
302 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
303 // If stdout and stderr should go to the same place, redirect stderr
304 // to the handle already open for stdout.
305 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
306 GetCurrentProcess(), &si.hStdError,
307 0, TRUE, DUPLICATE_SAME_ACCESS)) {
308 CloseHandle(si.hStdInput);
309 CloseHandle(si.hStdOutput);
310 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
314 // Just redirect stderr
315 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
316 if (si.hStdError == INVALID_HANDLE_VALUE) {
317 CloseHandle(si.hStdInput);
318 CloseHandle(si.hStdOutput);
319 MakeErrMsg(ErrMsg, "can't redirect stderr");
325 PROCESS_INFORMATION pi;
326 memset(&pi, 0, sizeof(pi));
331 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
332 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
333 SetLastError(ec.value());
335 std::string("Unable to convert application name to UTF-16"));
339 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
340 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
341 SetLastError(ec.value());
343 std::string("Unable to convert command-line to UTF-16"));
347 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
348 TRUE, CREATE_UNICODE_ENVIRONMENT,
349 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
351 DWORD err = GetLastError();
353 // Regardless of whether the process got created or not, we are done with
354 // the handles we created for it to inherit.
355 CloseHandle(si.hStdInput);
356 CloseHandle(si.hStdOutput);
357 CloseHandle(si.hStdError);
359 // Now return an error if the process didn't get created.
362 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
363 Program.str() + "'");
367 PI.Pid = pi.dwProcessId;
368 PI.ProcessHandle = pi.hProcess;
370 // Make sure these get closed no matter what.
371 ScopedCommonHandle hThread(pi.hThread);
373 // Assign the process to a job if a memory limit is defined.
374 ScopedJobHandle hJob;
375 if (memoryLimit != 0) {
376 hJob = CreateJobObjectW(0, 0);
377 bool success = false;
379 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
380 memset(&jeli, 0, sizeof(jeli));
381 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
382 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
383 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
384 &jeli, sizeof(jeli))) {
385 if (AssignProcessToJobObject(hJob, pi.hProcess))
390 SetLastError(GetLastError());
391 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
392 TerminateProcess(pi.hProcess, 1);
393 WaitForSingleObject(pi.hProcess, INFINITE);
402 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
403 bool WaitUntilChildTerminates, std::string *ErrMsg) {
404 assert(PI.Pid && "invalid pid to wait on, process not started?");
405 assert(PI.ProcessHandle &&
406 "invalid process handle to wait on, process not started?");
407 DWORD milliSecondsToWait = 0;
408 if (WaitUntilChildTerminates)
409 milliSecondsToWait = INFINITE;
410 else if (SecondsToWait > 0)
411 milliSecondsToWait = SecondsToWait * 1000;
413 ProcessInfo WaitResult = PI;
414 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
415 if (WaitStatus == WAIT_TIMEOUT) {
417 if (!TerminateProcess(PI.ProcessHandle, 1)) {
419 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
421 // -2 indicates a crash or timeout as opposed to failure to execute.
422 WaitResult.ReturnCode = -2;
423 CloseHandle(PI.ProcessHandle);
426 WaitForSingleObject(PI.ProcessHandle, INFINITE);
427 CloseHandle(PI.ProcessHandle);
429 // Non-blocking wait.
430 return ProcessInfo();
434 // Get its exit status.
436 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
437 DWORD err = GetLastError();
438 if (err != ERROR_INVALID_HANDLE)
439 CloseHandle(PI.ProcessHandle);
444 MakeErrMsg(ErrMsg, "Failed getting status for program.");
446 // -2 indicates a crash or timeout as opposed to failure to execute.
447 WaitResult.ReturnCode = -2;
454 // Pass 10(Warning) and 11(Error) to the callee as negative value.
455 if ((status & 0xBFFF0000U) == 0x80000000U)
456 WaitResult.ReturnCode = static_cast<int>(status);
457 else if (status & 0xFF)
458 WaitResult.ReturnCode = status & 0x7FFFFFFF;
460 WaitResult.ReturnCode = 1;
465 std::error_code sys::ChangeStdinToBinary() {
466 int result = _setmode(_fileno(stdin), _O_BINARY);
468 return std::error_code(errno, std::generic_category());
469 return std::error_code();
472 std::error_code sys::ChangeStdoutToBinary() {
473 int result = _setmode(_fileno(stdout), _O_BINARY);
475 return std::error_code(errno, std::generic_category());
476 return std::error_code();
480 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
481 WindowsEncodingMethod Encoding) {
483 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
487 if (Encoding == WEM_UTF8) {
489 } else if (Encoding == WEM_CurrentCodePage) {
490 SmallVector<wchar_t, 1> ArgsUTF16;
491 SmallVector<char, 1> ArgsCurCP;
493 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
496 if ((EC = windows::UTF16ToCurCP(
497 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
500 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
501 } else if (Encoding == WEM_UTF16) {
502 SmallVector<wchar_t, 1> ArgsUTF16;
504 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
507 // Endianness guessing
509 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
510 memcpy(BOM, &src, 2);
512 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
514 llvm_unreachable("Unknown encoding");
518 return make_error_code(errc::io_error);
523 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
524 // The documented max length of the command line passed to CreateProcess.
525 static const size_t MaxCommandStringLength = 32768;
526 size_t ArgLength = 0;
527 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
529 // Account for the trailing space for every arg but the last one and the
530 // trailing NULL of the last argument.
531 ArgLength += ArgLenWithQuotes(*I) + 1;
532 if (ArgLength > MaxCommandStringLength) {