OSDN Git Service

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