1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides the Win32 specific implementation of the Program class.
11 //===----------------------------------------------------------------------===//
13 #include "WindowsSupport.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/Support/ConvertUTF.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/WindowsError.h"
20 #include "llvm/Support/raw_ostream.h"
27 //===----------------------------------------------------------------------===//
28 //=== WARNING: Implementation here must contain only Win32 specific code
29 //=== and must not be UNIX code
30 //===----------------------------------------------------------------------===//
34 ProcessInfo::ProcessInfo() : Pid(0), Process(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 // Lets attach the extension manually. That is needed for files
79 // with a point in name like aaa.bbb. SearchPathW will not add extension
80 // from its argument to such files because it thinks they already had one.
81 SmallVector<wchar_t, MAX_PATH> U16NameExt;
82 if (std::error_code EC =
83 windows::UTF8ToUTF16(Twine(Name + Ext).str(), U16NameExt))
86 Len = ::SearchPathW(Path, c_str(U16NameExt), nullptr,
87 U16Result.capacity(), U16Result.data(), nullptr);
88 } while (Len > U16Result.capacity());
95 return mapWindowsError(::GetLastError());
97 U16Result.set_size(Len);
99 SmallVector<char, MAX_PATH> U8Result;
100 if (std::error_code EC =
101 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
104 return std::string(U8Result.begin(), U8Result.end());
107 bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix) {
111 DWORD LastError = GetLastError();
112 DWORD R = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
113 FORMAT_MESSAGE_FROM_SYSTEM |
114 FORMAT_MESSAGE_MAX_WIDTH_MASK,
115 NULL, LastError, 0, (LPSTR)&buffer, 1, NULL);
117 *ErrMsg = prefix + ": " + buffer;
119 *ErrMsg = prefix + ": Unknown error";
120 *ErrMsg += " (0x" + llvm::utohexstr(LastError) + ")";
126 static HANDLE RedirectIO(Optional<StringRef> Path, int fd,
127 std::string *ErrMsg) {
130 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
131 GetCurrentProcess(), &h,
132 0, TRUE, DUPLICATE_SAME_ACCESS))
133 return INVALID_HANDLE_VALUE;
143 SECURITY_ATTRIBUTES sa;
144 sa.nLength = sizeof(sa);
145 sa.lpSecurityDescriptor = 0;
146 sa.bInheritHandle = TRUE;
148 SmallVector<wchar_t, 128> fnameUnicode;
150 // Don't play long-path tricks on "NUL".
151 if (windows::UTF8ToUTF16(fname, fnameUnicode))
152 return INVALID_HANDLE_VALUE;
154 if (path::widenPath(fname, fnameUnicode))
155 return INVALID_HANDLE_VALUE;
157 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
158 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
159 FILE_ATTRIBUTE_NORMAL, NULL);
160 if (h == INVALID_HANDLE_VALUE) {
161 MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
162 (fd ? "input" : "output"));
170 static bool Execute(ProcessInfo &PI, StringRef Program,
171 ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
172 ArrayRef<Optional<StringRef>> Redirects,
173 unsigned MemoryLimit, std::string *ErrMsg) {
174 if (!sys::fs::can_execute(Program)) {
176 *ErrMsg = "program not executable";
180 // can_execute may succeed by looking at Program + ".exe". CreateProcessW
181 // will implicitly add the .exe if we provide a command line without an
182 // executable path, but since we use an explicit executable, we have to add
184 SmallString<64> ProgramStorage;
185 if (!sys::fs::exists(Program))
186 Program = Twine(Program + ".exe").toStringRef(ProgramStorage);
188 // Windows wants a command line, not an array of args, to pass to the new
189 // process. We have to concatenate them all, while quoting the args that
190 // have embedded spaces (or are empty).
191 std::string Command = flattenWindowsCommandLine(Args);
193 // The pointer to the environment block for the new process.
194 std::vector<wchar_t> EnvBlock;
197 // An environment block consists of a null-terminated block of
198 // null-terminated strings. Convert the array of environment variables to
199 // an environment block by concatenating them.
200 for (const auto E : *Env) {
201 SmallVector<wchar_t, MAX_PATH> EnvString;
202 if (std::error_code ec = windows::UTF8ToUTF16(E, EnvString)) {
203 SetLastError(ec.value());
204 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
208 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
209 EnvBlock.push_back(0);
211 EnvBlock.push_back(0);
214 // Create a child process.
216 memset(&si, 0, sizeof(si));
218 si.hStdInput = INVALID_HANDLE_VALUE;
219 si.hStdOutput = INVALID_HANDLE_VALUE;
220 si.hStdError = INVALID_HANDLE_VALUE;
222 if (!Redirects.empty()) {
223 si.dwFlags = STARTF_USESTDHANDLES;
225 si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
226 if (si.hStdInput == INVALID_HANDLE_VALUE) {
227 MakeErrMsg(ErrMsg, "can't redirect stdin");
230 si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
231 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
232 CloseHandle(si.hStdInput);
233 MakeErrMsg(ErrMsg, "can't redirect stdout");
236 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
237 // If stdout and stderr should go to the same place, redirect stderr
238 // to the handle already open for stdout.
239 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
240 GetCurrentProcess(), &si.hStdError,
241 0, TRUE, DUPLICATE_SAME_ACCESS)) {
242 CloseHandle(si.hStdInput);
243 CloseHandle(si.hStdOutput);
244 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
248 // Just redirect stderr
249 si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
250 if (si.hStdError == INVALID_HANDLE_VALUE) {
251 CloseHandle(si.hStdInput);
252 CloseHandle(si.hStdOutput);
253 MakeErrMsg(ErrMsg, "can't redirect stderr");
259 PROCESS_INFORMATION pi;
260 memset(&pi, 0, sizeof(pi));
265 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
266 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
267 SetLastError(ec.value());
269 std::string("Unable to convert application name to UTF-16"));
273 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
274 if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
275 SetLastError(ec.value());
277 std::string("Unable to convert command-line to UTF-16"));
281 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
282 TRUE, CREATE_UNICODE_ENVIRONMENT,
283 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
285 DWORD err = GetLastError();
287 // Regardless of whether the process got created or not, we are done with
288 // the handles we created for it to inherit.
289 CloseHandle(si.hStdInput);
290 CloseHandle(si.hStdOutput);
291 CloseHandle(si.hStdError);
293 // Now return an error if the process didn't get created.
296 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
297 Program.str() + "'");
301 PI.Pid = pi.dwProcessId;
302 PI.Process = pi.hProcess;
304 // Make sure these get closed no matter what.
305 ScopedCommonHandle hThread(pi.hThread);
307 // Assign the process to a job if a memory limit is defined.
308 ScopedJobHandle hJob;
309 if (MemoryLimit != 0) {
310 hJob = CreateJobObjectW(0, 0);
311 bool success = false;
313 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
314 memset(&jeli, 0, sizeof(jeli));
315 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
316 jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
317 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
318 &jeli, sizeof(jeli))) {
319 if (AssignProcessToJobObject(hJob, pi.hProcess))
324 SetLastError(GetLastError());
325 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
326 TerminateProcess(pi.hProcess, 1);
327 WaitForSingleObject(pi.hProcess, INFINITE);
335 static bool argNeedsQuotes(StringRef Arg) {
338 return StringRef::npos != Arg.find_first_of("\t \"&\'()*<>\\`^|\n");
341 static std::string quoteSingleArg(StringRef Arg) {
343 Result.push_back('"');
345 while (!Arg.empty()) {
346 size_t FirstNonBackslash = Arg.find_first_not_of('\\');
347 size_t BackslashCount = FirstNonBackslash;
348 if (FirstNonBackslash == StringRef::npos) {
349 // The entire remainder of the argument is backslashes. Escape all of
350 // them and just early out.
351 BackslashCount = Arg.size();
352 Result.append(BackslashCount * 2, '\\');
356 if (Arg[FirstNonBackslash] == '\"') {
357 // This is an embedded quote. Escape all preceding backslashes, then
358 // add one additional backslash to escape the quote.
359 Result.append(BackslashCount * 2 + 1, '\\');
360 Result.push_back('\"');
362 // This is just a normal character. Don't escape any of the preceding
363 // backslashes, just append them as they are and then append the
365 Result.append(BackslashCount, '\\');
366 Result.push_back(Arg[FirstNonBackslash]);
369 // Drop all the backslashes, plus the following character.
370 Arg = Arg.drop_front(FirstNonBackslash + 1);
373 Result.push_back('"');
378 std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
380 for (StringRef Arg : Args) {
381 if (argNeedsQuotes(Arg))
382 Command += quoteSingleArg(Arg);
386 Command.push_back(' ');
392 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
393 bool WaitUntilChildTerminates, std::string *ErrMsg) {
394 assert(PI.Pid && "invalid pid to wait on, process not started?");
395 assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
396 "invalid process handle to wait on, process not started?");
397 DWORD milliSecondsToWait = 0;
398 if (WaitUntilChildTerminates)
399 milliSecondsToWait = INFINITE;
400 else if (SecondsToWait > 0)
401 milliSecondsToWait = SecondsToWait * 1000;
403 ProcessInfo WaitResult = PI;
404 DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
405 if (WaitStatus == WAIT_TIMEOUT) {
407 if (!TerminateProcess(PI.Process, 1)) {
409 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program");
411 // -2 indicates a crash or timeout as opposed to failure to execute.
412 WaitResult.ReturnCode = -2;
413 CloseHandle(PI.Process);
416 WaitForSingleObject(PI.Process, INFINITE);
417 CloseHandle(PI.Process);
419 // Non-blocking wait.
420 return ProcessInfo();
424 // Get its exit status.
426 BOOL rc = GetExitCodeProcess(PI.Process, &status);
427 DWORD err = GetLastError();
428 if (err != ERROR_INVALID_HANDLE)
429 CloseHandle(PI.Process);
434 MakeErrMsg(ErrMsg, "Failed getting status for program");
436 // -2 indicates a crash or timeout as opposed to failure to execute.
437 WaitResult.ReturnCode = -2;
444 // Pass 10(Warning) and 11(Error) to the callee as negative value.
445 if ((status & 0xBFFF0000U) == 0x80000000U)
446 WaitResult.ReturnCode = static_cast<int>(status);
447 else if (status & 0xFF)
448 WaitResult.ReturnCode = status & 0x7FFFFFFF;
450 WaitResult.ReturnCode = 1;
455 std::error_code sys::ChangeStdinToBinary() {
456 int result = _setmode(_fileno(stdin), _O_BINARY);
458 return std::error_code(errno, std::generic_category());
459 return std::error_code();
462 std::error_code sys::ChangeStdoutToBinary() {
463 int result = _setmode(_fileno(stdout), _O_BINARY);
465 return std::error_code(errno, std::generic_category());
466 return std::error_code();
470 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
471 WindowsEncodingMethod Encoding) {
473 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OF_Text);
477 if (Encoding == WEM_UTF8) {
479 } else if (Encoding == WEM_CurrentCodePage) {
480 SmallVector<wchar_t, 1> ArgsUTF16;
481 SmallVector<char, 1> ArgsCurCP;
483 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
486 if ((EC = windows::UTF16ToCurCP(
487 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
490 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
491 } else if (Encoding == WEM_UTF16) {
492 SmallVector<wchar_t, 1> ArgsUTF16;
494 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
497 // Endianness guessing
499 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
500 memcpy(BOM, &src, 2);
502 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
504 llvm_unreachable("Unknown encoding");
508 return make_error_code(errc::io_error);
513 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
514 ArrayRef<StringRef> Args) {
515 // The documented max length of the command line passed to CreateProcess.
516 static const size_t MaxCommandStringLength = 32768;
517 SmallVector<StringRef, 8> FullArgs;
518 FullArgs.push_back(Program);
519 FullArgs.append(Args.begin(), Args.end());
520 std::string Result = flattenWindowsCommandLine(FullArgs);
521 return (Result.size() + 1) <= MaxCommandStringLength;