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