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 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/Support/FileSystem.h"
22 //===----------------------------------------------------------------------===//
23 //=== WARNING: Implementation here must contain only Win32 specific code
24 //=== and must not be UNIX code
25 //===----------------------------------------------------------------------===//
28 struct Win32ProcessInfo {
37 // This function just uses the PATH environment variable to find the program.
38 std::string sys::FindProgramByName(const std::string &progName) {
39 // Check some degenerate cases
40 if (progName.length() == 0) // no program
42 std::string temp = progName;
43 // Return paths with slashes verbatim.
44 if (progName.find('\\') != std::string::npos ||
45 progName.find('/') != std::string::npos)
48 // At this point, the file name is valid and does not contain slashes.
49 // Let Windows search for it.
51 buffer.resize(MAX_PATH);
53 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
56 // See if it wasn't found.
60 // See if we got the entire path.
64 // Buffer was too small; grow and retry.
67 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, &buffer[0], &dummy);
69 // It is unlikely the search failed, but it's always possible some file
70 // was added or removed since the last search, so be paranoid...
80 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
83 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
84 GetCurrentProcess(), &h,
85 0, TRUE, DUPLICATE_SAME_ACCESS);
95 SECURITY_ATTRIBUTES sa;
96 sa.nLength = sizeof(sa);
97 sa.lpSecurityDescriptor = 0;
98 sa.bInheritHandle = TRUE;
100 h = CreateFile(fname.c_str(), fd ? GENERIC_WRITE : GENERIC_READ,
101 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
102 FILE_ATTRIBUTE_NORMAL, NULL);
103 if (h == INVALID_HANDLE_VALUE) {
104 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
105 (fd ? "input: " : "output: "));
111 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
113 static bool ArgNeedsQuotes(const char *Str) {
114 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
117 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
118 /// in the C string Start.
119 static unsigned int CountPrecedingBackslashes(const char *Start,
121 unsigned int Count = 0;
123 while (Cur >= Start && *Cur == '\\') {
130 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
131 /// preceding Cur in the Start string. Assumes Dst has enough space.
132 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
134 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
135 while (PrecedingEscapes > 0) {
142 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
143 /// CreateProcess and returns length of quoted arg with escaped quotes
144 static unsigned int ArgLenWithQuotes(const char *Str) {
145 const char *Start = Str;
146 bool Quoted = ArgNeedsQuotes(Str);
147 unsigned int len = Quoted ? 2 : 0;
149 while (*Str != '\0') {
151 // We need to add a backslash, but ensure that it isn't escaped.
152 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
153 len += PrecedingEscapes + 1;
155 // Note that we *don't* need to escape runs of backslashes that don't
156 // precede a double quote! See MSDN:
157 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
164 // Make sure the closing quote doesn't get escaped by a trailing backslash.
165 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
166 len += PrecedingEscapes + 1;
174 static bool Execute(void **Data,
178 const StringRef** redirects,
179 unsigned memoryLimit,
180 std::string* ErrMsg) {
181 if (!sys::fs::can_execute(Program)) {
183 *ErrMsg = "program not executable";
187 // Windows wants a command line, not an array of args, to pass to the new
188 // process. We have to concatenate them all, while quoting the args that
189 // have embedded spaces (or are empty).
191 // First, determine the length of the command line.
193 for (unsigned i = 0; args[i]; i++) {
194 len += ArgLenWithQuotes(args[i]) + 1;
197 // Now build the command line.
198 OwningArrayPtr<char> command(new char[len+1]);
199 char *p = command.get();
201 for (unsigned i = 0; args[i]; i++) {
202 const char *arg = args[i];
203 const char *start = arg;
205 bool needsQuoting = ArgNeedsQuotes(arg);
209 while (*arg != '\0') {
211 // Escape all preceding escapes (if any), and then escape the quote.
212 p = EscapePrecedingEscapes(p, start, arg);
220 // Make sure our quote doesn't get escaped by a trailing backslash.
221 p = EscapePrecedingEscapes(p, start, arg);
229 // The pointer to the environment block for the new process.
230 OwningArrayPtr<char> envblock;
233 // An environment block consists of a null-terminated block of
234 // null-terminated strings. Convert the array of environment variables to
235 // an environment block by concatenating them.
237 // First, determine the length of the environment block.
239 for (unsigned i = 0; envp[i]; i++)
240 len += strlen(envp[i]) + 1;
242 // Now build the environment block.
243 envblock.reset(new char[len+1]);
246 for (unsigned i = 0; envp[i]; i++) {
247 const char *ev = envp[i];
248 size_t len = strlen(ev) + 1;
256 // Create a child process.
258 memset(&si, 0, sizeof(si));
260 si.hStdInput = INVALID_HANDLE_VALUE;
261 si.hStdOutput = INVALID_HANDLE_VALUE;
262 si.hStdError = INVALID_HANDLE_VALUE;
265 si.dwFlags = STARTF_USESTDHANDLES;
267 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
268 if (si.hStdInput == INVALID_HANDLE_VALUE) {
269 MakeErrMsg(ErrMsg, "can't redirect stdin");
272 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
273 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
274 CloseHandle(si.hStdInput);
275 MakeErrMsg(ErrMsg, "can't redirect stdout");
278 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
279 // If stdout and stderr should go to the same place, redirect stderr
280 // to the handle already open for stdout.
281 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
282 GetCurrentProcess(), &si.hStdError,
283 0, TRUE, DUPLICATE_SAME_ACCESS);
285 // Just redirect stderr
286 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
287 if (si.hStdError == INVALID_HANDLE_VALUE) {
288 CloseHandle(si.hStdInput);
289 CloseHandle(si.hStdOutput);
290 MakeErrMsg(ErrMsg, "can't redirect stderr");
296 PROCESS_INFORMATION pi;
297 memset(&pi, 0, sizeof(pi));
301 std::string ProgramStr = Program;
302 BOOL rc = CreateProcess(ProgramStr.c_str(), command.get(), NULL, NULL, TRUE,
303 0, envblock.get(), NULL, &si, &pi);
304 DWORD err = GetLastError();
306 // Regardless of whether the process got created or not, we are done with
307 // the handles we created for it to inherit.
308 CloseHandle(si.hStdInput);
309 CloseHandle(si.hStdOutput);
310 CloseHandle(si.hStdError);
312 // Now return an error if the process didn't get created.
315 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
320 Win32ProcessInfo* wpi = new Win32ProcessInfo;
321 wpi->hProcess = pi.hProcess;
322 wpi->dwProcessId = pi.dwProcessId;
326 // Make sure these get closed no matter what.
327 ScopedCommonHandle hThread(pi.hThread);
329 // Assign the process to a job if a memory limit is defined.
330 ScopedJobHandle hJob;
331 if (memoryLimit != 0) {
332 hJob = CreateJobObject(0, 0);
333 bool success = false;
335 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
336 memset(&jeli, 0, sizeof(jeli));
337 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
338 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
339 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
340 &jeli, sizeof(jeli))) {
341 if (AssignProcessToJobObject(hJob, pi.hProcess))
346 SetLastError(GetLastError());
347 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
348 TerminateProcess(pi.hProcess, 1);
349 WaitForSingleObject(pi.hProcess, INFINITE);
354 // Don't leak the handle if the caller doesn't want it.
356 CloseHandle(pi.hProcess);
361 static int WaitAux(Win32ProcessInfo *wpi, unsigned secondsToWait,
362 std::string *ErrMsg) {
363 // Wait for the process to terminate.
364 HANDLE hProcess = wpi->hProcess;
365 DWORD millisecondsToWait = INFINITE;
366 if (secondsToWait > 0)
367 millisecondsToWait = secondsToWait * 1000;
369 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
370 if (!TerminateProcess(hProcess, 1)) {
371 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
372 // -2 indicates a crash or timeout as opposed to failure to execute.
375 WaitForSingleObject(hProcess, INFINITE);
378 // Get its exit status.
380 BOOL rc = GetExitCodeProcess(hProcess, &status);
381 DWORD err = GetLastError();
385 MakeErrMsg(ErrMsg, "Failed getting status for program.");
386 // -2 indicates a crash or timeout as opposed to failure to execute.
393 // Pass 10(Warning) and 11(Error) to the callee as negative value.
394 if ((status & 0xBFFF0000U) == 0x80000000U)
398 return status & 0x7FFFFFFF;
403 static int Wait(void *&Data, StringRef Program, unsigned secondsToWait,
404 std::string *ErrMsg) {
405 Win32ProcessInfo *wpi = reinterpret_cast<Win32ProcessInfo *>(Data);
406 int Ret = WaitAux(wpi, secondsToWait, ErrMsg);
408 CloseHandle(wpi->hProcess);
416 error_code sys::ChangeStdinToBinary(){
417 int result = _setmode( _fileno(stdin), _O_BINARY );
419 return error_code(errno, generic_category());
420 return make_error_code(errc::success);
423 error_code sys::ChangeStdoutToBinary(){
424 int result = _setmode( _fileno(stdout), _O_BINARY );
426 return error_code(errno, generic_category());
427 return make_error_code(errc::success);
430 error_code sys::ChangeStderrToBinary(){
431 int result = _setmode( _fileno(stderr), _O_BINARY );
433 return error_code(errno, generic_category());
434 return make_error_code(errc::success);
437 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
438 // The documented max length of the command line passed to CreateProcess.
439 static const size_t MaxCommandStringLength = 32768;
440 size_t ArgLength = 0;
441 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
443 // Account for the trailing space for every arg but the last one and the
444 // trailing NULL of the last argument.
445 ArgLength += ArgLenWithQuotes(*I) + 1;
446 if (ArgLength > MaxCommandStringLength) {