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/Path.h"
20 #include "llvm/Support/WindowsError.h"
21 #include "llvm/Support/raw_ostream.h"
28 //===----------------------------------------------------------------------===//
29 //=== WARNING: Implementation here must contain only Win32 specific code
30 //=== and must not be UNIX code
31 //===----------------------------------------------------------------------===//
35 ProcessInfo::ProcessInfo() : Pid(0), Process(0), ReturnCode(0) {}
37 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
38 ArrayRef<StringRef> Paths) {
39 assert(!Name.empty() && "Must have a name!");
41 if (Name.find_first_of("/\\") != StringRef::npos)
42 return std::string(Name);
44 const wchar_t *Path = nullptr;
45 std::wstring PathStorage;
47 PathStorage.reserve(Paths.size() * MAX_PATH);
48 for (unsigned i = 0; i < Paths.size(); ++i) {
50 PathStorage.push_back(L';');
51 StringRef P = Paths[i];
52 SmallVector<wchar_t, MAX_PATH> TmpPath;
53 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
55 PathStorage.append(TmpPath.begin(), TmpPath.end());
57 Path = PathStorage.c_str();
60 SmallVector<wchar_t, MAX_PATH> U16Name;
61 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
64 SmallVector<StringRef, 12> PathExts;
65 PathExts.push_back("");
66 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
67 if (const char *PathExtEnv = std::getenv("PATHEXT"))
68 SplitString(PathExtEnv, PathExts, ";");
70 SmallVector<wchar_t, MAX_PATH> U16Result;
72 for (StringRef Ext : PathExts) {
73 SmallVector<wchar_t, MAX_PATH> U16Ext;
74 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
78 U16Result.reserve(Len);
79 // Lets attach the extension manually. That is needed for files
80 // with a point in name like aaa.bbb. SearchPathW will not add extension
81 // from its argument to such files because it thinks they already had one.
82 SmallVector<wchar_t, MAX_PATH> U16NameExt;
83 if (std::error_code EC =
84 windows::UTF8ToUTF16(Twine(Name + Ext).str(), U16NameExt))
87 Len = ::SearchPathW(Path, c_str(U16NameExt), nullptr,
88 U16Result.capacity(), U16Result.data(), nullptr);
89 } while (Len > U16Result.capacity());
96 return mapWindowsError(::GetLastError());
98 U16Result.set_size(Len);
100 SmallVector<char, MAX_PATH> U8Result;
101 if (std::error_code EC =
102 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
105 return std::string(U8Result.begin(), U8Result.end());
108 static HANDLE RedirectIO(Optional<StringRef> Path, int fd,
109 std::string *ErrMsg) {
112 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
113 GetCurrentProcess(), &h,
114 0, TRUE, DUPLICATE_SAME_ACCESS))
115 return INVALID_HANDLE_VALUE;
125 SECURITY_ATTRIBUTES sa;
126 sa.nLength = sizeof(sa);
127 sa.lpSecurityDescriptor = 0;
128 sa.bInheritHandle = TRUE;
130 SmallVector<wchar_t, 128> fnameUnicode;
132 // Don't play long-path tricks on "NUL".
133 if (windows::UTF8ToUTF16(fname, fnameUnicode))
134 return INVALID_HANDLE_VALUE;
136 if (path::widenPath(fname, fnameUnicode))
137 return INVALID_HANDLE_VALUE;
139 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
140 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
141 FILE_ATTRIBUTE_NORMAL, NULL);
142 if (h == INVALID_HANDLE_VALUE) {
143 MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
144 (fd ? "input" : "output"));
152 static SmallVector<StringRef, 8> buildArgVector(const char **Args) {
153 SmallVector<StringRef, 8> Result;
154 for (unsigned I = 0; Args[I]; ++I)
155 Result.push_back(StringRef(Args[I]));
159 static bool Execute(ProcessInfo &PI, StringRef Program, const char **Args,
160 const char **Envp, ArrayRef<Optional<StringRef>> Redirects,
161 unsigned MemoryLimit, std::string *ErrMsg) {
162 if (!sys::fs::can_execute(Program)) {
164 *ErrMsg = "program not executable";
168 // can_execute may succeed by looking at Program + ".exe". CreateProcessW
169 // will implicitly add the .exe if we provide a command line without an
170 // executable path, but since we use an explicit executable, we have to add
172 SmallString<64> ProgramStorage;
173 if (!sys::fs::exists(Program))
174 Program = Twine(Program + ".exe").toStringRef(ProgramStorage);
176 // Windows wants a command line, not an array of args, to pass to the new
177 // process. We have to concatenate them all, while quoting the args that
178 // have embedded spaces (or are empty).
179 auto ArgVector = buildArgVector(Args);
180 std::string Command = flattenWindowsCommandLine(ArgVector);
182 // The pointer to the environment block for the new process.
183 std::vector<wchar_t> EnvBlock;
186 // An environment block consists of a null-terminated block of
187 // null-terminated strings. Convert the array of environment variables to
188 // an environment block by concatenating them.
189 for (unsigned i = 0; Envp[i]; ++i) {
190 SmallVector<wchar_t, MAX_PATH> EnvString;
191 if (std::error_code ec = windows::UTF8ToUTF16(Envp[i], EnvString)) {
192 SetLastError(ec.value());
193 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
197 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
198 EnvBlock.push_back(0);
200 EnvBlock.push_back(0);
203 // Create a child process.
205 memset(&si, 0, sizeof(si));
207 si.hStdInput = INVALID_HANDLE_VALUE;
208 si.hStdOutput = INVALID_HANDLE_VALUE;
209 si.hStdError = INVALID_HANDLE_VALUE;
211 if (!Redirects.empty()) {
212 si.dwFlags = STARTF_USESTDHANDLES;
214 si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
215 if (si.hStdInput == INVALID_HANDLE_VALUE) {
216 MakeErrMsg(ErrMsg, "can't redirect stdin");
219 si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
220 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
221 CloseHandle(si.hStdInput);
222 MakeErrMsg(ErrMsg, "can't redirect stdout");
225 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
226 // If stdout and stderr should go to the same place, redirect stderr
227 // to the handle already open for stdout.
228 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
229 GetCurrentProcess(), &si.hStdError,
230 0, TRUE, DUPLICATE_SAME_ACCESS)) {
231 CloseHandle(si.hStdInput);
232 CloseHandle(si.hStdOutput);
233 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
237 // Just redirect stderr
238 si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
239 if (si.hStdError == INVALID_HANDLE_VALUE) {
240 CloseHandle(si.hStdInput);
241 CloseHandle(si.hStdOutput);
242 MakeErrMsg(ErrMsg, "can't redirect stderr");
248 PROCESS_INFORMATION pi;
249 memset(&pi, 0, sizeof(pi));
254 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
255 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
256 SetLastError(ec.value());
258 std::string("Unable to convert application name to UTF-16"));
262 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
263 if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
264 SetLastError(ec.value());
266 std::string("Unable to convert command-line to UTF-16"));
270 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
271 TRUE, CREATE_UNICODE_ENVIRONMENT,
272 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
274 DWORD err = GetLastError();
276 // Regardless of whether the process got created or not, we are done with
277 // the handles we created for it to inherit.
278 CloseHandle(si.hStdInput);
279 CloseHandle(si.hStdOutput);
280 CloseHandle(si.hStdError);
282 // Now return an error if the process didn't get created.
285 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
286 Program.str() + "'");
290 PI.Pid = pi.dwProcessId;
291 PI.Process = pi.hProcess;
293 // Make sure these get closed no matter what.
294 ScopedCommonHandle hThread(pi.hThread);
296 // Assign the process to a job if a memory limit is defined.
297 ScopedJobHandle hJob;
298 if (MemoryLimit != 0) {
299 hJob = CreateJobObjectW(0, 0);
300 bool success = false;
302 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
303 memset(&jeli, 0, sizeof(jeli));
304 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
305 jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
306 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
307 &jeli, sizeof(jeli))) {
308 if (AssignProcessToJobObject(hJob, pi.hProcess))
313 SetLastError(GetLastError());
314 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
315 TerminateProcess(pi.hProcess, 1);
316 WaitForSingleObject(pi.hProcess, INFINITE);
324 static bool argNeedsQuotes(StringRef Arg) {
327 return StringRef::npos != Arg.find_first_of(" \t\n\v\"");
330 static std::string quoteSingleArg(StringRef Arg) {
332 Result.push_back('"');
334 while (!Arg.empty()) {
335 size_t FirstNonBackslash = Arg.find_first_not_of('\\');
336 size_t BackslashCount = FirstNonBackslash;
337 if (FirstNonBackslash == StringRef::npos) {
338 // The entire remainder of the argument is backslashes. Escape all of
339 // them and just early out.
340 BackslashCount = Arg.size();
341 Result.append(BackslashCount * 2, '\\');
345 if (Arg[FirstNonBackslash] == '\"') {
346 // This is an embedded quote. Escape all preceding backslashes, then
347 // add one additional backslash to escape the quote.
348 Result.append(BackslashCount * 2 + 1, '\\');
349 Result.push_back('\"');
351 // This is just a normal character. Don't escape any of the preceding
352 // backslashes, just append them as they are and then append the
354 Result.append(BackslashCount, '\\');
355 Result.push_back(Arg[FirstNonBackslash]);
358 // Drop all the backslashes, plus the following character.
359 Arg = Arg.drop_front(FirstNonBackslash + 1);
362 Result.push_back('"');
367 std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
369 for (StringRef Arg : Args) {
370 if (argNeedsQuotes(Arg))
371 Command += quoteSingleArg(Arg);
375 Command.push_back(' ');
381 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
382 bool WaitUntilChildTerminates, std::string *ErrMsg) {
383 assert(PI.Pid && "invalid pid to wait on, process not started?");
384 assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
385 "invalid process handle to wait on, process not started?");
386 DWORD milliSecondsToWait = 0;
387 if (WaitUntilChildTerminates)
388 milliSecondsToWait = INFINITE;
389 else if (SecondsToWait > 0)
390 milliSecondsToWait = SecondsToWait * 1000;
392 ProcessInfo WaitResult = PI;
393 DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
394 if (WaitStatus == WAIT_TIMEOUT) {
396 if (!TerminateProcess(PI.Process, 1)) {
398 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program");
400 // -2 indicates a crash or timeout as opposed to failure to execute.
401 WaitResult.ReturnCode = -2;
402 CloseHandle(PI.Process);
405 WaitForSingleObject(PI.Process, INFINITE);
406 CloseHandle(PI.Process);
408 // Non-blocking wait.
409 return ProcessInfo();
413 // Get its exit status.
415 BOOL rc = GetExitCodeProcess(PI.Process, &status);
416 DWORD err = GetLastError();
417 if (err != ERROR_INVALID_HANDLE)
418 CloseHandle(PI.Process);
423 MakeErrMsg(ErrMsg, "Failed getting status for program");
425 // -2 indicates a crash or timeout as opposed to failure to execute.
426 WaitResult.ReturnCode = -2;
433 // Pass 10(Warning) and 11(Error) to the callee as negative value.
434 if ((status & 0xBFFF0000U) == 0x80000000U)
435 WaitResult.ReturnCode = static_cast<int>(status);
436 else if (status & 0xFF)
437 WaitResult.ReturnCode = status & 0x7FFFFFFF;
439 WaitResult.ReturnCode = 1;
444 std::error_code sys::ChangeStdinToBinary() {
445 int result = _setmode(_fileno(stdin), _O_BINARY);
447 return std::error_code(errno, std::generic_category());
448 return std::error_code();
451 std::error_code sys::ChangeStdoutToBinary() {
452 int result = _setmode(_fileno(stdout), _O_BINARY);
454 return std::error_code(errno, std::generic_category());
455 return std::error_code();
459 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
460 WindowsEncodingMethod Encoding) {
462 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::F_Text);
466 if (Encoding == WEM_UTF8) {
468 } else if (Encoding == WEM_CurrentCodePage) {
469 SmallVector<wchar_t, 1> ArgsUTF16;
470 SmallVector<char, 1> ArgsCurCP;
472 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
475 if ((EC = windows::UTF16ToCurCP(
476 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
479 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
480 } else if (Encoding == WEM_UTF16) {
481 SmallVector<wchar_t, 1> ArgsUTF16;
483 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
486 // Endianness guessing
488 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
489 memcpy(BOM, &src, 2);
491 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
493 llvm_unreachable("Unknown encoding");
497 return make_error_code(errc::io_error);
502 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
503 ArrayRef<StringRef> Args) {
504 // The documented max length of the command line passed to CreateProcess.
505 static const size_t MaxCommandStringLength = 32768;
506 SmallVector<StringRef, 8> FullArgs;
507 FullArgs.push_back(Program);
508 FullArgs.append(Args.begin(), Args.end());
509 std::string Result = flattenWindowsCommandLine(FullArgs);
510 return (Result.size() + 1) <= MaxCommandStringLength;