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