74a0066de8d0c11a4357dff3c8d28f85cdf21f7c
[oota-llvm.git] / lib / Support / Windows / Program.inc
1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the Win32 specific implementation of the Program class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "WindowsSupport.h"
15 #include "llvm/Support/FileSystem.h"
16 #include <cstdio>
17 #include <fcntl.h>
18 #include <io.h>
19 #include <malloc.h>
20
21 //===----------------------------------------------------------------------===//
22 //=== WARNING: Implementation here must contain only Win32 specific code
23 //===          and must not be UNIX code
24 //===----------------------------------------------------------------------===//
25
26 namespace llvm {
27 using namespace sys;
28
29 ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
30
31 // This function just uses the PATH environment variable to find the program.
32 std::string sys::FindProgramByName(const std::string &progName) {
33   // Check some degenerate cases
34   if (progName.length() == 0) // no program
35     return "";
36   std::string temp = progName;
37   // Return paths with slashes verbatim.
38   if (progName.find('\\') != std::string::npos ||
39       progName.find('/') != std::string::npos)
40     return temp;
41
42   // At this point, the file name is valid and does not contain slashes.
43   // Let Windows search for it.
44   SmallVector<wchar_t, MAX_PATH> progNameUnicode;
45   if (windows::UTF8ToUTF16(progName, progNameUnicode))
46     return "";
47
48   SmallVector<wchar_t, MAX_PATH> buffer;
49   DWORD len = MAX_PATH;
50   do {
51     buffer.reserve(len);
52     len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
53                         buffer.capacity(), buffer.data(), NULL);
54
55     // See if it wasn't found.
56     if (len == 0)
57       return "";
58
59     // Buffer was too small; grow and retry.
60   } while (len > buffer.capacity());
61
62   buffer.set_size(len);
63   SmallVector<char, MAX_PATH> result;
64   if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
65     return "";
66
67   return std::string(result.data(), result.size());
68 }
69
70 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
71   HANDLE h;
72   if (path == 0) {
73     if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
74                          GetCurrentProcess(), &h,
75                          0, TRUE, DUPLICATE_SAME_ACCESS))
76       return INVALID_HANDLE_VALUE;
77     return h;
78   }
79
80   std::string fname;
81   if (path->empty())
82     fname = "NUL";
83   else
84     fname = *path;
85
86   SECURITY_ATTRIBUTES sa;
87   sa.nLength = sizeof(sa);
88   sa.lpSecurityDescriptor = 0;
89   sa.bInheritHandle = TRUE;
90
91   SmallVector<wchar_t, 128> fnameUnicode;
92   if (windows::UTF8ToUTF16(fname, fnameUnicode))
93     return INVALID_HANDLE_VALUE;
94
95   h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
96                   FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
97                   FILE_ATTRIBUTE_NORMAL, NULL);
98   if (h == INVALID_HANDLE_VALUE) {
99     MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
100         (fd ? "input: " : "output: "));
101   }
102
103   return h;
104 }
105
106 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
107 /// CreateProcess.
108 static bool ArgNeedsQuotes(const char *Str) {
109   return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
110 }
111
112 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
113 /// in the C string Start.
114 static unsigned int CountPrecedingBackslashes(const char *Start,
115                                               const char *Cur) {
116   unsigned int Count = 0;
117   --Cur;
118   while (Cur >= Start && *Cur == '\\') {
119     ++Count;
120     --Cur;
121   }
122   return Count;
123 }
124
125 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
126 /// preceding Cur in the Start string.  Assumes Dst has enough space.
127 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
128                                     const char *Cur) {
129   unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
130   while (PrecedingEscapes > 0) {
131     *Dst++ = '\\';
132     --PrecedingEscapes;
133   }
134   return Dst;
135 }
136
137 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
138 /// CreateProcess and returns length of quoted arg with escaped quotes
139 static unsigned int ArgLenWithQuotes(const char *Str) {
140   const char *Start = Str;
141   bool Quoted = ArgNeedsQuotes(Str);
142   unsigned int len = Quoted ? 2 : 0;
143
144   while (*Str != '\0') {
145     if (*Str == '\"') {
146       // We need to add a backslash, but ensure that it isn't escaped.
147       unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
148       len += PrecedingEscapes + 1;
149     }
150     // Note that we *don't* need to escape runs of backslashes that don't
151     // precede a double quote!  See MSDN:
152     // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
153
154     ++len;
155     ++Str;
156   }
157
158   if (Quoted) {
159     // Make sure the closing quote doesn't get escaped by a trailing backslash.
160     unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
161     len += PrecedingEscapes + 1;
162   }
163
164   return len;
165 }
166
167 }
168
169 static std::unique_ptr<char[]> flattenArgs(const char **args) {
170   // First, determine the length of the command line.
171   unsigned len = 0;
172   for (unsigned i = 0; args[i]; i++) {
173     len += ArgLenWithQuotes(args[i]) + 1;
174   }
175
176   // Now build the command line.
177   std::unique_ptr<char[]> command(new char[len+1]);
178   char *p = command.get();
179
180   for (unsigned i = 0; args[i]; i++) {
181     const char *arg = args[i];
182     const char *start = arg;
183
184     bool needsQuoting = ArgNeedsQuotes(arg);
185     if (needsQuoting)
186       *p++ = '"';
187
188     while (*arg != '\0') {
189       if (*arg == '\"') {
190         // Escape all preceding escapes (if any), and then escape the quote.
191         p = EscapePrecedingEscapes(p, start, arg);
192         *p++ = '\\';
193       }
194
195       *p++ = *arg++;
196     }
197
198     if (needsQuoting) {
199       // Make sure our quote doesn't get escaped by a trailing backslash.
200       p = EscapePrecedingEscapes(p, start, arg);
201       *p++ = '"';
202     }
203     *p++ = ' ';
204   }
205
206   *p = 0;
207   return command;
208 }
209
210 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
211                     const char **envp, const StringRef **redirects,
212                     unsigned memoryLimit, std::string *ErrMsg) {
213   if (!sys::fs::can_execute(Program)) {
214     if (ErrMsg)
215       *ErrMsg = "program not executable";
216     return false;
217   }
218
219   // Windows wants a command line, not an array of args, to pass to the new
220   // process.  We have to concatenate them all, while quoting the args that
221   // have embedded spaces (or are empty).
222   std::unique_ptr<char[]> command = flattenArgs(args);
223
224   // The pointer to the environment block for the new process.
225   std::vector<wchar_t> EnvBlock;
226
227   if (envp) {
228     // An environment block consists of a null-terminated block of
229     // null-terminated strings. Convert the array of environment variables to
230     // an environment block by concatenating them.
231     for (unsigned i = 0; envp[i]; ++i) {
232       SmallVector<wchar_t, MAX_PATH> EnvString;
233       if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
234         SetLastError(ec.value());
235         MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
236         return false;
237       }
238
239       EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
240       EnvBlock.push_back(0);
241     }
242     EnvBlock.push_back(0);
243   }
244
245   // Create a child process.
246   STARTUPINFOW si;
247   memset(&si, 0, sizeof(si));
248   si.cb = sizeof(si);
249   si.hStdInput = INVALID_HANDLE_VALUE;
250   si.hStdOutput = INVALID_HANDLE_VALUE;
251   si.hStdError = INVALID_HANDLE_VALUE;
252
253   if (redirects) {
254     si.dwFlags = STARTF_USESTDHANDLES;
255
256     si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
257     if (si.hStdInput == INVALID_HANDLE_VALUE) {
258       MakeErrMsg(ErrMsg, "can't redirect stdin");
259       return false;
260     }
261     si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
262     if (si.hStdOutput == INVALID_HANDLE_VALUE) {
263       CloseHandle(si.hStdInput);
264       MakeErrMsg(ErrMsg, "can't redirect stdout");
265       return false;
266     }
267     if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
268       // If stdout and stderr should go to the same place, redirect stderr
269       // to the handle already open for stdout.
270       if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
271                            GetCurrentProcess(), &si.hStdError,
272                            0, TRUE, DUPLICATE_SAME_ACCESS)) {
273         CloseHandle(si.hStdInput);
274         CloseHandle(si.hStdOutput);
275         MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
276         return false;
277       }
278     } else {
279       // Just redirect stderr
280       si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
281       if (si.hStdError == INVALID_HANDLE_VALUE) {
282         CloseHandle(si.hStdInput);
283         CloseHandle(si.hStdOutput);
284         MakeErrMsg(ErrMsg, "can't redirect stderr");
285         return false;
286       }
287     }
288   }
289
290   PROCESS_INFORMATION pi;
291   memset(&pi, 0, sizeof(pi));
292
293   fflush(stdout);
294   fflush(stderr);
295
296   SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
297   if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
298     SetLastError(ec.value());
299     MakeErrMsg(ErrMsg,
300                std::string("Unable to convert application name to UTF-16"));
301     return false;
302   }
303
304   SmallVector<wchar_t, MAX_PATH> CommandUtf16;
305   if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
306     SetLastError(ec.value());
307     MakeErrMsg(ErrMsg,
308                std::string("Unable to convert command-line to UTF-16"));
309     return false;
310   }
311
312   BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
313                            TRUE, CREATE_UNICODE_ENVIRONMENT,
314                            EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
315                            &pi);
316   DWORD err = GetLastError();
317
318   // Regardless of whether the process got created or not, we are done with
319   // the handles we created for it to inherit.
320   CloseHandle(si.hStdInput);
321   CloseHandle(si.hStdOutput);
322   CloseHandle(si.hStdError);
323
324   // Now return an error if the process didn't get created.
325   if (!rc) {
326     SetLastError(err);
327     MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
328                Program.str() + "'");
329     return false;
330   }
331
332   PI.Pid = pi.dwProcessId;
333   PI.ProcessHandle = pi.hProcess;
334
335   // Make sure these get closed no matter what.
336   ScopedCommonHandle hThread(pi.hThread);
337
338   // Assign the process to a job if a memory limit is defined.
339   ScopedJobHandle hJob;
340   if (memoryLimit != 0) {
341     hJob = CreateJobObjectW(0, 0);
342     bool success = false;
343     if (hJob) {
344       JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
345       memset(&jeli, 0, sizeof(jeli));
346       jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
347       jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
348       if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
349                                   &jeli, sizeof(jeli))) {
350         if (AssignProcessToJobObject(hJob, pi.hProcess))
351           success = true;
352       }
353     }
354     if (!success) {
355       SetLastError(GetLastError());
356       MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
357       TerminateProcess(pi.hProcess, 1);
358       WaitForSingleObject(pi.hProcess, INFINITE);
359       return false;
360     }
361   }
362
363   return true;
364 }
365
366 namespace llvm {
367 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
368                       bool WaitUntilChildTerminates, std::string *ErrMsg) {
369   assert(PI.Pid && "invalid pid to wait on, process not started?");
370   assert(PI.ProcessHandle &&
371          "invalid process handle to wait on, process not started?");
372   DWORD milliSecondsToWait = 0;
373   if (WaitUntilChildTerminates)
374     milliSecondsToWait = INFINITE;
375   else if (SecondsToWait > 0)
376     milliSecondsToWait = SecondsToWait * 1000;
377
378   ProcessInfo WaitResult = PI;
379   DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
380   if (WaitStatus == WAIT_TIMEOUT) {
381     if (SecondsToWait) {
382       if (!TerminateProcess(PI.ProcessHandle, 1)) {
383         if (ErrMsg)
384           MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
385
386         // -2 indicates a crash or timeout as opposed to failure to execute.
387         WaitResult.ReturnCode = -2;
388         CloseHandle(PI.ProcessHandle);
389         return WaitResult;
390       }
391       WaitForSingleObject(PI.ProcessHandle, INFINITE);
392       CloseHandle(PI.ProcessHandle);
393     } else {
394       // Non-blocking wait.
395       return ProcessInfo();
396     }
397   }
398
399   // Get its exit status.
400   DWORD status;
401   BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
402   DWORD err = GetLastError();
403   CloseHandle(PI.ProcessHandle);
404
405   if (!rc) {
406     SetLastError(err);
407     if (ErrMsg)
408       MakeErrMsg(ErrMsg, "Failed getting status for program.");
409
410     // -2 indicates a crash or timeout as opposed to failure to execute.
411     WaitResult.ReturnCode = -2;
412     return WaitResult;
413   }
414
415   if (!status)
416     return WaitResult;
417
418   // Pass 10(Warning) and 11(Error) to the callee as negative value.
419   if ((status & 0xBFFF0000U) == 0x80000000U)
420     WaitResult.ReturnCode = static_cast<int>(status);
421   else if (status & 0xFF)
422     WaitResult.ReturnCode = status & 0x7FFFFFFF;
423   else
424     WaitResult.ReturnCode = 1;
425
426   return WaitResult;
427 }
428
429   std::error_code sys::ChangeStdinToBinary(){
430   int result = _setmode( _fileno(stdin), _O_BINARY );
431   if (result == -1)
432     return std::error_code(errno, std::generic_category());
433   return std::error_code();
434 }
435
436   std::error_code sys::ChangeStdoutToBinary(){
437   int result = _setmode( _fileno(stdout), _O_BINARY );
438   if (result == -1)
439     return std::error_code(errno, std::generic_category());
440   return std::error_code();
441 }
442
443 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
444   // The documented max length of the command line passed to CreateProcess.
445   static const size_t MaxCommandStringLength = 32768;
446   size_t ArgLength = 0;
447   for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
448        I != E; ++I) {
449     // Account for the trailing space for every arg but the last one and the
450     // trailing NULL of the last argument.
451     ArgLength += ArgLenWithQuotes(*I) + 1;
452     if (ArgLength > MaxCommandStringLength) {
453       return false;
454     }
455   }
456   return true;
457 }
458 }