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 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
36 ArrayRef<StringRef> Paths) {
37 assert(!Name.empty() && "Must have a name!");
39 if (Name.find_first_of("/\\") != StringRef::npos)
40 return std::string(Name);
42 const wchar_t *Path = nullptr;
43 std::wstring PathStorage;
45 PathStorage.reserve(Paths.size() * MAX_PATH);
46 for (unsigned i = 0; i < Paths.size(); ++i) {
48 PathStorage.push_back(L';');
49 StringRef P = Paths[i];
50 SmallVector<wchar_t, MAX_PATH> TmpPath;
51 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
53 PathStorage.append(TmpPath.begin(), TmpPath.end());
55 Path = PathStorage.c_str();
58 SmallVector<wchar_t, MAX_PATH> U16Name;
59 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
62 SmallVector<StringRef, 12> PathExts;
63 PathExts.push_back("");
64 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
65 SplitString(std::getenv("PATHEXT"), PathExts, ";");
67 SmallVector<wchar_t, MAX_PATH> U16Result;
69 for (StringRef Ext : PathExts) {
70 SmallVector<wchar_t, MAX_PATH> U16Ext;
71 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
75 U16Result.reserve(Len);
76 Len = ::SearchPathW(Path, c_str(U16Name),
77 U16Ext.empty() ? nullptr : c_str(U16Ext),
78 U16Result.capacity(), U16Result.data(), nullptr);
79 } while (Len > U16Result.capacity());
86 return mapWindowsError(::GetLastError());
88 U16Result.set_size(Len);
90 SmallVector<char, MAX_PATH> U8Result;
91 if (std::error_code EC =
92 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
95 return std::string(U8Result.begin(), U8Result.end());
98 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
101 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
102 GetCurrentProcess(), &h,
103 0, TRUE, DUPLICATE_SAME_ACCESS))
104 return INVALID_HANDLE_VALUE;
114 SECURITY_ATTRIBUTES sa;
115 sa.nLength = sizeof(sa);
116 sa.lpSecurityDescriptor = 0;
117 sa.bInheritHandle = TRUE;
119 SmallVector<wchar_t, 128> fnameUnicode;
120 if (windows::UTF8ToUTF16(fname, fnameUnicode))
121 return INVALID_HANDLE_VALUE;
123 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
124 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
125 FILE_ATTRIBUTE_NORMAL, NULL);
126 if (h == INVALID_HANDLE_VALUE) {
127 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
128 (fd ? "input: " : "output: "));
134 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
136 static bool ArgNeedsQuotes(const char *Str) {
137 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
140 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
141 /// in the C string Start.
142 static unsigned int CountPrecedingBackslashes(const char *Start,
144 unsigned int Count = 0;
146 while (Cur >= Start && *Cur == '\\') {
153 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
154 /// preceding Cur in the Start string. Assumes Dst has enough space.
155 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
157 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
158 while (PrecedingEscapes > 0) {
165 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
166 /// CreateProcess and returns length of quoted arg with escaped quotes
167 static unsigned int ArgLenWithQuotes(const char *Str) {
168 const char *Start = Str;
169 bool Quoted = ArgNeedsQuotes(Str);
170 unsigned int len = Quoted ? 2 : 0;
172 while (*Str != '\0') {
174 // We need to add a backslash, but ensure that it isn't escaped.
175 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
176 len += PrecedingEscapes + 1;
178 // Note that we *don't* need to escape runs of backslashes that don't
179 // precede a double quote! See MSDN:
180 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
187 // Make sure the closing quote doesn't get escaped by a trailing backslash.
188 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
189 len += PrecedingEscapes + 1;
197 static std::unique_ptr<char[]> flattenArgs(const char **args) {
198 // First, determine the length of the command line.
200 for (unsigned i = 0; args[i]; i++) {
201 len += ArgLenWithQuotes(args[i]) + 1;
204 // Now build the command line.
205 std::unique_ptr<char[]> command(new char[len+1]);
206 char *p = command.get();
208 for (unsigned i = 0; args[i]; i++) {
209 const char *arg = args[i];
210 const char *start = arg;
212 bool needsQuoting = ArgNeedsQuotes(arg);
216 while (*arg != '\0') {
218 // Escape all preceding escapes (if any), and then escape the quote.
219 p = EscapePrecedingEscapes(p, start, arg);
227 // Make sure our quote doesn't get escaped by a trailing backslash.
228 p = EscapePrecedingEscapes(p, start, arg);
238 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
239 const char **envp, const StringRef **redirects,
240 unsigned memoryLimit, std::string *ErrMsg) {
241 if (!sys::fs::can_execute(Program)) {
243 *ErrMsg = "program not executable";
247 // Windows wants a command line, not an array of args, to pass to the new
248 // process. We have to concatenate them all, while quoting the args that
249 // have embedded spaces (or are empty).
250 std::unique_ptr<char[]> command = flattenArgs(args);
252 // The pointer to the environment block for the new process.
253 std::vector<wchar_t> EnvBlock;
256 // An environment block consists of a null-terminated block of
257 // null-terminated strings. Convert the array of environment variables to
258 // an environment block by concatenating them.
259 for (unsigned i = 0; envp[i]; ++i) {
260 SmallVector<wchar_t, MAX_PATH> EnvString;
261 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
262 SetLastError(ec.value());
263 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
267 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
268 EnvBlock.push_back(0);
270 EnvBlock.push_back(0);
273 // Create a child process.
275 memset(&si, 0, sizeof(si));
277 si.hStdInput = INVALID_HANDLE_VALUE;
278 si.hStdOutput = INVALID_HANDLE_VALUE;
279 si.hStdError = INVALID_HANDLE_VALUE;
282 si.dwFlags = STARTF_USESTDHANDLES;
284 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
285 if (si.hStdInput == INVALID_HANDLE_VALUE) {
286 MakeErrMsg(ErrMsg, "can't redirect stdin");
289 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
290 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
291 CloseHandle(si.hStdInput);
292 MakeErrMsg(ErrMsg, "can't redirect stdout");
295 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
296 // If stdout and stderr should go to the same place, redirect stderr
297 // to the handle already open for stdout.
298 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
299 GetCurrentProcess(), &si.hStdError,
300 0, TRUE, DUPLICATE_SAME_ACCESS)) {
301 CloseHandle(si.hStdInput);
302 CloseHandle(si.hStdOutput);
303 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
307 // Just redirect stderr
308 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
309 if (si.hStdError == INVALID_HANDLE_VALUE) {
310 CloseHandle(si.hStdInput);
311 CloseHandle(si.hStdOutput);
312 MakeErrMsg(ErrMsg, "can't redirect stderr");
318 PROCESS_INFORMATION pi;
319 memset(&pi, 0, sizeof(pi));
324 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
325 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
326 SetLastError(ec.value());
328 std::string("Unable to convert application name to UTF-16"));
332 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
333 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
334 SetLastError(ec.value());
336 std::string("Unable to convert command-line to UTF-16"));
340 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
341 TRUE, CREATE_UNICODE_ENVIRONMENT,
342 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
344 DWORD err = GetLastError();
346 // Regardless of whether the process got created or not, we are done with
347 // the handles we created for it to inherit.
348 CloseHandle(si.hStdInput);
349 CloseHandle(si.hStdOutput);
350 CloseHandle(si.hStdError);
352 // Now return an error if the process didn't get created.
355 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
356 Program.str() + "'");
360 PI.Pid = pi.dwProcessId;
361 PI.ProcessHandle = pi.hProcess;
363 // Make sure these get closed no matter what.
364 ScopedCommonHandle hThread(pi.hThread);
366 // Assign the process to a job if a memory limit is defined.
367 ScopedJobHandle hJob;
368 if (memoryLimit != 0) {
369 hJob = CreateJobObjectW(0, 0);
370 bool success = false;
372 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
373 memset(&jeli, 0, sizeof(jeli));
374 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
375 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
376 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
377 &jeli, sizeof(jeli))) {
378 if (AssignProcessToJobObject(hJob, pi.hProcess))
383 SetLastError(GetLastError());
384 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
385 TerminateProcess(pi.hProcess, 1);
386 WaitForSingleObject(pi.hProcess, INFINITE);
395 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
396 bool WaitUntilChildTerminates, std::string *ErrMsg) {
397 assert(PI.Pid && "invalid pid to wait on, process not started?");
398 assert(PI.ProcessHandle &&
399 "invalid process handle to wait on, process not started?");
400 DWORD milliSecondsToWait = 0;
401 if (WaitUntilChildTerminates)
402 milliSecondsToWait = INFINITE;
403 else if (SecondsToWait > 0)
404 milliSecondsToWait = SecondsToWait * 1000;
406 ProcessInfo WaitResult = PI;
407 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
408 if (WaitStatus == WAIT_TIMEOUT) {
410 if (!TerminateProcess(PI.ProcessHandle, 1)) {
412 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
414 // -2 indicates a crash or timeout as opposed to failure to execute.
415 WaitResult.ReturnCode = -2;
416 CloseHandle(PI.ProcessHandle);
419 WaitForSingleObject(PI.ProcessHandle, INFINITE);
420 CloseHandle(PI.ProcessHandle);
422 // Non-blocking wait.
423 return ProcessInfo();
427 // Get its exit status.
429 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
430 DWORD err = GetLastError();
431 CloseHandle(PI.ProcessHandle);
436 MakeErrMsg(ErrMsg, "Failed getting status for program.");
438 // -2 indicates a crash or timeout as opposed to failure to execute.
439 WaitResult.ReturnCode = -2;
446 // Pass 10(Warning) and 11(Error) to the callee as negative value.
447 if ((status & 0xBFFF0000U) == 0x80000000U)
448 WaitResult.ReturnCode = static_cast<int>(status);
449 else if (status & 0xFF)
450 WaitResult.ReturnCode = status & 0x7FFFFFFF;
452 WaitResult.ReturnCode = 1;
457 std::error_code sys::ChangeStdinToBinary() {
458 int result = _setmode(_fileno(stdin), _O_BINARY);
460 return std::error_code(errno, std::generic_category());
461 return std::error_code();
464 std::error_code sys::ChangeStdoutToBinary() {
465 int result = _setmode(_fileno(stdout), _O_BINARY);
467 return std::error_code(errno, std::generic_category());
468 return std::error_code();
472 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
473 WindowsEncodingMethod Encoding) {
475 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
479 if (Encoding == WEM_UTF8) {
481 } else if (Encoding == WEM_CurrentCodePage) {
482 SmallVector<wchar_t, 1> ArgsUTF16;
483 SmallVector<char, 1> ArgsCurCP;
485 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
488 if ((EC = windows::UTF16ToCurCP(
489 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
492 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
493 } else if (Encoding == WEM_UTF16) {
494 SmallVector<wchar_t, 1> ArgsUTF16;
496 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
499 // Endianness guessing
501 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
502 memcpy(BOM, &src, 2);
504 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
506 llvm_unreachable("Unknown encoding");
510 return std::make_error_code(std::errc::io_error);
515 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
516 // The documented max length of the command line passed to CreateProcess.
517 static const size_t MaxCommandStringLength = 32768;
518 size_t ArgLength = 0;
519 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
521 // Account for the trailing space for every arg but the last one and the
522 // trailing NULL of the last argument.
523 ArgLength += ArgLenWithQuotes(*I) + 1;
524 if (ArgLength > MaxCommandStringLength) {