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/Support/ConvertUTF.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/raw_ostream.h"
23 //===----------------------------------------------------------------------===//
24 //=== WARNING: Implementation here must contain only Win32 specific code
25 //=== and must not be UNIX code
26 //===----------------------------------------------------------------------===//
31 ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
33 // This function just uses the PATH environment variable to find the program.
34 std::string sys::FindProgramByName(const std::string &progName) {
35 // Check some degenerate cases
36 if (progName.length() == 0) // no program
38 std::string temp = progName;
39 // Return paths with slashes verbatim.
40 if (progName.find('\\') != std::string::npos ||
41 progName.find('/') != std::string::npos)
44 // At this point, the file name is valid and does not contain slashes.
45 // Let Windows search for it.
46 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
47 if (windows::UTF8ToUTF16(progName, progNameUnicode))
50 SmallVector<wchar_t, MAX_PATH> buffer;
54 len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
55 buffer.capacity(), buffer.data(), NULL);
57 // See if it wasn't found.
61 // Buffer was too small; grow and retry.
62 } while (len > buffer.capacity());
65 SmallVector<char, MAX_PATH> result;
66 if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
69 return std::string(result.data(), result.size());
72 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
75 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
76 GetCurrentProcess(), &h,
77 0, TRUE, DUPLICATE_SAME_ACCESS))
78 return INVALID_HANDLE_VALUE;
88 SECURITY_ATTRIBUTES sa;
89 sa.nLength = sizeof(sa);
90 sa.lpSecurityDescriptor = 0;
91 sa.bInheritHandle = TRUE;
93 SmallVector<wchar_t, 128> fnameUnicode;
94 if (windows::UTF8ToUTF16(fname, fnameUnicode))
95 return INVALID_HANDLE_VALUE;
97 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
98 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
99 FILE_ATTRIBUTE_NORMAL, NULL);
100 if (h == INVALID_HANDLE_VALUE) {
101 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
102 (fd ? "input: " : "output: "));
108 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
110 static bool ArgNeedsQuotes(const char *Str) {
111 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
114 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
115 /// in the C string Start.
116 static unsigned int CountPrecedingBackslashes(const char *Start,
118 unsigned int Count = 0;
120 while (Cur >= Start && *Cur == '\\') {
127 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
128 /// preceding Cur in the Start string. Assumes Dst has enough space.
129 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
131 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
132 while (PrecedingEscapes > 0) {
139 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
140 /// CreateProcess and returns length of quoted arg with escaped quotes
141 static unsigned int ArgLenWithQuotes(const char *Str) {
142 const char *Start = Str;
143 bool Quoted = ArgNeedsQuotes(Str);
144 unsigned int len = Quoted ? 2 : 0;
146 while (*Str != '\0') {
148 // We need to add a backslash, but ensure that it isn't escaped.
149 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
150 len += PrecedingEscapes + 1;
152 // Note that we *don't* need to escape runs of backslashes that don't
153 // precede a double quote! See MSDN:
154 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
161 // Make sure the closing quote doesn't get escaped by a trailing backslash.
162 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
163 len += PrecedingEscapes + 1;
171 static std::unique_ptr<char[]> flattenArgs(const char **args) {
172 // First, determine the length of the command line.
174 for (unsigned i = 0; args[i]; i++) {
175 len += ArgLenWithQuotes(args[i]) + 1;
178 // Now build the command line.
179 std::unique_ptr<char[]> command(new char[len+1]);
180 char *p = command.get();
182 for (unsigned i = 0; args[i]; i++) {
183 const char *arg = args[i];
184 const char *start = arg;
186 bool needsQuoting = ArgNeedsQuotes(arg);
190 while (*arg != '\0') {
192 // Escape all preceding escapes (if any), and then escape the quote.
193 p = EscapePrecedingEscapes(p, start, arg);
201 // Make sure our quote doesn't get escaped by a trailing backslash.
202 p = EscapePrecedingEscapes(p, start, arg);
212 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
213 const char **envp, const StringRef **redirects,
214 unsigned memoryLimit, std::string *ErrMsg) {
215 if (!sys::fs::can_execute(Program)) {
217 *ErrMsg = "program not executable";
221 // Windows wants a command line, not an array of args, to pass to the new
222 // process. We have to concatenate them all, while quoting the args that
223 // have embedded spaces (or are empty).
224 std::unique_ptr<char[]> command = flattenArgs(args);
226 // The pointer to the environment block for the new process.
227 std::vector<wchar_t> EnvBlock;
230 // An environment block consists of a null-terminated block of
231 // null-terminated strings. Convert the array of environment variables to
232 // an environment block by concatenating them.
233 for (unsigned i = 0; envp[i]; ++i) {
234 SmallVector<wchar_t, MAX_PATH> EnvString;
235 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
236 SetLastError(ec.value());
237 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
241 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
242 EnvBlock.push_back(0);
244 EnvBlock.push_back(0);
247 // Create a child process.
249 memset(&si, 0, sizeof(si));
251 si.hStdInput = INVALID_HANDLE_VALUE;
252 si.hStdOutput = INVALID_HANDLE_VALUE;
253 si.hStdError = INVALID_HANDLE_VALUE;
256 si.dwFlags = STARTF_USESTDHANDLES;
258 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
259 if (si.hStdInput == INVALID_HANDLE_VALUE) {
260 MakeErrMsg(ErrMsg, "can't redirect stdin");
263 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
264 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
265 CloseHandle(si.hStdInput);
266 MakeErrMsg(ErrMsg, "can't redirect stdout");
269 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
270 // If stdout and stderr should go to the same place, redirect stderr
271 // to the handle already open for stdout.
272 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
273 GetCurrentProcess(), &si.hStdError,
274 0, TRUE, DUPLICATE_SAME_ACCESS)) {
275 CloseHandle(si.hStdInput);
276 CloseHandle(si.hStdOutput);
277 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
281 // Just redirect stderr
282 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
283 if (si.hStdError == INVALID_HANDLE_VALUE) {
284 CloseHandle(si.hStdInput);
285 CloseHandle(si.hStdOutput);
286 MakeErrMsg(ErrMsg, "can't redirect stderr");
292 PROCESS_INFORMATION pi;
293 memset(&pi, 0, sizeof(pi));
298 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
299 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
300 SetLastError(ec.value());
302 std::string("Unable to convert application name to UTF-16"));
306 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
307 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
308 SetLastError(ec.value());
310 std::string("Unable to convert command-line to UTF-16"));
314 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
315 TRUE, CREATE_UNICODE_ENVIRONMENT,
316 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
318 DWORD err = GetLastError();
320 // Regardless of whether the process got created or not, we are done with
321 // the handles we created for it to inherit.
322 CloseHandle(si.hStdInput);
323 CloseHandle(si.hStdOutput);
324 CloseHandle(si.hStdError);
326 // Now return an error if the process didn't get created.
329 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
330 Program.str() + "'");
334 PI.Pid = pi.dwProcessId;
335 PI.ProcessHandle = pi.hProcess;
337 // Make sure these get closed no matter what.
338 ScopedCommonHandle hThread(pi.hThread);
340 // Assign the process to a job if a memory limit is defined.
341 ScopedJobHandle hJob;
342 if (memoryLimit != 0) {
343 hJob = CreateJobObjectW(0, 0);
344 bool success = false;
346 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
347 memset(&jeli, 0, sizeof(jeli));
348 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
349 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
350 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
351 &jeli, sizeof(jeli))) {
352 if (AssignProcessToJobObject(hJob, pi.hProcess))
357 SetLastError(GetLastError());
358 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
359 TerminateProcess(pi.hProcess, 1);
360 WaitForSingleObject(pi.hProcess, INFINITE);
369 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
370 bool WaitUntilChildTerminates, std::string *ErrMsg) {
371 assert(PI.Pid && "invalid pid to wait on, process not started?");
372 assert(PI.ProcessHandle &&
373 "invalid process handle to wait on, process not started?");
374 DWORD milliSecondsToWait = 0;
375 if (WaitUntilChildTerminates)
376 milliSecondsToWait = INFINITE;
377 else if (SecondsToWait > 0)
378 milliSecondsToWait = SecondsToWait * 1000;
380 ProcessInfo WaitResult = PI;
381 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
382 if (WaitStatus == WAIT_TIMEOUT) {
384 if (!TerminateProcess(PI.ProcessHandle, 1)) {
386 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
388 // -2 indicates a crash or timeout as opposed to failure to execute.
389 WaitResult.ReturnCode = -2;
390 CloseHandle(PI.ProcessHandle);
393 WaitForSingleObject(PI.ProcessHandle, INFINITE);
394 CloseHandle(PI.ProcessHandle);
396 // Non-blocking wait.
397 return ProcessInfo();
401 // Get its exit status.
403 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
404 DWORD err = GetLastError();
405 CloseHandle(PI.ProcessHandle);
410 MakeErrMsg(ErrMsg, "Failed getting status for program.");
412 // -2 indicates a crash or timeout as opposed to failure to execute.
413 WaitResult.ReturnCode = -2;
420 // Pass 10(Warning) and 11(Error) to the callee as negative value.
421 if ((status & 0xBFFF0000U) == 0x80000000U)
422 WaitResult.ReturnCode = static_cast<int>(status);
423 else if (status & 0xFF)
424 WaitResult.ReturnCode = status & 0x7FFFFFFF;
426 WaitResult.ReturnCode = 1;
431 std::error_code sys::ChangeStdinToBinary(){
432 int result = _setmode( _fileno(stdin), _O_BINARY );
434 return std::error_code(errno, std::generic_category());
435 return std::error_code();
438 std::error_code sys::ChangeStdoutToBinary(){
439 int result = _setmode( _fileno(stdout), _O_BINARY );
441 return std::error_code(errno, std::generic_category());
442 return std::error_code();
446 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
447 WindowsEncodingMethod Encoding) {
449 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
453 if (Encoding == WEM_UTF8) {
455 } else if (Encoding == WEM_CurrentCodePage) {
456 SmallVector<wchar_t, 1> ArgsUTF16;
457 SmallVector<char, 1> ArgsCurCP;
459 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
462 if ((EC = windows::UTF16ToCurCP(
463 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
466 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
467 } else if (Encoding == WEM_UTF16) {
468 SmallVector<wchar_t, 1> ArgsUTF16;
470 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
473 // Endianness guessing
475 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
476 memcpy(BOM, &src, 2);
478 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
480 llvm_unreachable("Unknown encoding");
484 return std::make_error_code(std::errc::io_error);
489 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
490 // The documented max length of the command line passed to CreateProcess.
491 static const size_t MaxCommandStringLength = 32768;
492 size_t ArgLength = 0;
493 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
495 // Account for the trailing space for every arg but the last one and the
496 // trailing NULL of the last argument.
497 ArgLength += ArgLenWithQuotes(*I) + 1;
498 if (ArgLength > MaxCommandStringLength) {