blob: 5755b0ad035b18fc3ab3241d24647b3842ad888e [file] [log] [blame]
Reid Spencerb88212e2004-09-15 05:49:50 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +00002//
Reid Spencer76b83a12004-08-29 19:20:41 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +00007//
Reid Spencer76b83a12004-08-29 19:20:41 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000014#include "WindowsSupport.h"
Michael J. Spencer65ffd922014-11-04 01:29:29 +000015#include "llvm/ADT/StringExtras.h"
Rafael Espindola9c359662014-09-03 20:02:00 +000016#include "llvm/Support/ConvertUTF.h"
Rafael Espindolab0a5c962013-06-14 19:38:45 +000017#include "llvm/Support/FileSystem.h"
Rafael Espindola9c359662014-09-03 20:02:00 +000018#include "llvm/Support/raw_ostream.h"
Michael J. Spencer65ffd922014-11-04 01:29:29 +000019#include "llvm/Support/WindowsError.h"
Reid Spencerab97f222006-06-07 23:18:34 +000020#include <cstdio>
Reid Spencerab97f222006-06-07 23:18:34 +000021#include <fcntl.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include <io.h>
23#include <malloc.h>
Reid Spencerb88212e2004-09-15 05:49:50 +000024
Reid Spencer76b83a12004-08-29 19:20:41 +000025//===----------------------------------------------------------------------===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000026//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb88212e2004-09-15 05:49:50 +000027//=== and must not be UNIX code
Reid Spencer76b83a12004-08-29 19:20:41 +000028//===----------------------------------------------------------------------===//
29
Reid Spencerb88212e2004-09-15 05:49:50 +000030namespace llvm {
31using namespace sys;
32
Alp Toker153675b2013-10-18 07:09:58 +000033ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
Tareq A. Sirajd88b9832013-10-01 14:28:18 +000034
Reid Spencerb88212e2004-09-15 05:49:50 +000035// This function just uses the PATH environment variable to find the program.
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000036std::string sys::FindProgramByName(const std::string &progName) {
Reid Spencerb88212e2004-09-15 05:49:50 +000037 // Check some degenerate cases
38 if (progName.length() == 0) // no program
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000039 return "";
Rafael Espindolab0a5c962013-06-14 19:38:45 +000040 std::string temp = progName;
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000041 // Return paths with slashes verbatim.
42 if (progName.find('\\') != std::string::npos ||
43 progName.find('/') != std::string::npos)
Rafael Espindolab0a5c962013-06-14 19:38:45 +000044 return temp;
Reid Spencerb88212e2004-09-15 05:49:50 +000045
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000046 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb88212e2004-09-15 05:49:50 +000047 // Let Windows search for it.
David Majnemer61eae2e2013-10-07 01:00:07 +000048 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
49 if (windows::UTF8ToUTF16(progName, progNameUnicode))
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000050 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000051
David Majnemer61eae2e2013-10-07 01:00:07 +000052 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);
Reid Spencerb88212e2004-09-15 05:49:50 +000058
David Majnemer61eae2e2013-10-07 01:00:07 +000059 // See if it wasn't found.
60 if (len == 0)
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000061 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000062
David Majnemer61eae2e2013-10-07 01:00:07 +000063 // 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());
Reid Spencerb88212e2004-09-15 05:49:50 +000072}
73
Michael J. Spencer65ffd922014-11-04 01:29:29 +000074ErrorOr<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 (int 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 SplitString(std::getenv("PATHEXT"), PathExts, ";");
104
105 SmallVector<wchar_t, MAX_PATH> U16Result;
106 DWORD Len = MAX_PATH;
107 for (StringRef Ext : PathExts) {
108 SmallVector<wchar_t, MAX_PATH> U16Ext;
109 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
110 return EC;
111
112 do {
113 U16Result.reserve(Len);
114 Len = ::SearchPathW((const wchar_t *)Path, c_str(U16Name),
115 U16Ext.empty() ? nullptr : c_str(U16Ext),
116 U16Result.capacity(), U16Result.data(), nullptr);
117 } while (Len > U16Result.capacity());
118
119 if (Len != 0)
120 break; // Found it.
121 }
122
123 if (Len == 0)
124 return mapWindowsError(::GetLastError());
125
126 U16Result.set_size(Len);
127
128 SmallVector<char, MAX_PATH> U8Result;
129 if (std::error_code EC =
130 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
131 return EC;
132
133 return std::string(U8Result.begin(), U8Result.end());
134}
135
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000136static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000137 HANDLE h;
138 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000139 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
140 GetCurrentProcess(), &h,
141 0, TRUE, DUPLICATE_SAME_ACCESS))
142 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000143 return h;
144 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000145
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000146 std::string fname;
147 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +0000148 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000149 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000150 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000151
152 SECURITY_ATTRIBUTES sa;
153 sa.nLength = sizeof(sa);
154 sa.lpSecurityDescriptor = 0;
155 sa.bInheritHandle = TRUE;
156
David Majnemer61eae2e2013-10-07 01:00:07 +0000157 SmallVector<wchar_t, 128> fnameUnicode;
158 if (windows::UTF8ToUTF16(fname, fnameUnicode))
159 return INVALID_HANDLE_VALUE;
160
161 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
162 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
163 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000164 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000165 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000166 (fd ? "input: " : "output: "));
167 }
Jeff Cohena531d042007-03-05 05:22:08 +0000168
Jeff Cohen4220bf52005-02-20 02:43:04 +0000169 return h;
170}
171
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000172/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
173/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000174static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000175 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000176}
177
Reid Kleckner74679a92013-04-22 19:03:55 +0000178/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
179/// in the C string Start.
180static unsigned int CountPrecedingBackslashes(const char *Start,
181 const char *Cur) {
182 unsigned int Count = 0;
183 --Cur;
184 while (Cur >= Start && *Cur == '\\') {
185 ++Count;
186 --Cur;
187 }
188 return Count;
189}
190
191/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
192/// preceding Cur in the Start string. Assumes Dst has enough space.
193static char *EscapePrecedingEscapes(char *Dst, const char *Start,
194 const char *Cur) {
195 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
196 while (PrecedingEscapes > 0) {
197 *Dst++ = '\\';
198 --PrecedingEscapes;
199 }
200 return Dst;
201}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000202
203/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
204/// CreateProcess and returns length of quoted arg with escaped quotes
205static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000206 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000207 bool Quoted = ArgNeedsQuotes(Str);
208 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000209
210 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000211 if (*Str == '\"') {
212 // We need to add a backslash, but ensure that it isn't escaped.
213 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
214 len += PrecedingEscapes + 1;
215 }
216 // Note that we *don't* need to escape runs of backslashes that don't
217 // precede a double quote! See MSDN:
218 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000219
220 ++len;
221 ++Str;
222 }
223
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000224 if (Quoted) {
225 // Make sure the closing quote doesn't get escaped by a trailing backslash.
226 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
227 len += PrecedingEscapes + 1;
228 }
229
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000230 return len;
231}
232
Rafael Espindola404ae772013-06-12 21:11:50 +0000233}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000234
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000235static std::unique_ptr<char[]> flattenArgs(const char **args) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000236 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000237 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000238 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000239 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000240 }
241
242 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000243 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000244 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000245
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000246 for (unsigned i = 0; args[i]; i++) {
247 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000248 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000249
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000250 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000251 if (needsQuoting)
252 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000253
254 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000255 if (*arg == '\"') {
256 // Escape all preceding escapes (if any), and then escape the quote.
257 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000258 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000259 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000260
261 *p++ = *arg++;
262 }
263
Reid Kleckner74679a92013-04-22 19:03:55 +0000264 if (needsQuoting) {
265 // Make sure our quote doesn't get escaped by a trailing backslash.
266 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000267 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000268 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000269 *p++ = ' ';
270 }
271
272 *p = 0;
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000273 return command;
274}
275
276static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
277 const char **envp, const StringRef **redirects,
278 unsigned memoryLimit, std::string *ErrMsg) {
279 if (!sys::fs::can_execute(Program)) {
280 if (ErrMsg)
281 *ErrMsg = "program not executable";
282 return false;
283 }
284
285 // Windows wants a command line, not an array of args, to pass to the new
286 // process. We have to concatenate them all, while quoting the args that
287 // have embedded spaces (or are empty).
288 std::unique_ptr<char[]> command = flattenArgs(args);
Reid Spencerb88212e2004-09-15 05:49:50 +0000289
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000290 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000291 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000292
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000293 if (envp) {
294 // An environment block consists of a null-terminated block of
295 // null-terminated strings. Convert the array of environment variables to
296 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000297 for (unsigned i = 0; envp[i]; ++i) {
298 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000299 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000300 SetLastError(ec.value());
301 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
302 return false;
303 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000304
David Majnemer61eae2e2013-10-07 01:00:07 +0000305 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
306 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000307 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000308 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000309 }
310
Reid Spencerb88212e2004-09-15 05:49:50 +0000311 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000312 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000313 memset(&si, 0, sizeof(si));
314 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000315 si.hStdInput = INVALID_HANDLE_VALUE;
316 si.hStdOutput = INVALID_HANDLE_VALUE;
317 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000318
Jeff Cohen4220bf52005-02-20 02:43:04 +0000319 if (redirects) {
320 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000321
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000322 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
323 if (si.hStdInput == INVALID_HANDLE_VALUE) {
324 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000325 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000326 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000327 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000328 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000329 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000330 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000331 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000332 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000333 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
334 // If stdout and stderr should go to the same place, redirect stderr
335 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000336 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
337 GetCurrentProcess(), &si.hStdError,
338 0, TRUE, DUPLICATE_SAME_ACCESS)) {
339 CloseHandle(si.hStdInput);
340 CloseHandle(si.hStdOutput);
341 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
342 return false;
343 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000344 } else {
345 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000346 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000347 if (si.hStdError == INVALID_HANDLE_VALUE) {
348 CloseHandle(si.hStdInput);
349 CloseHandle(si.hStdOutput);
350 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000351 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000352 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000353 }
354 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000355
Reid Spencerb88212e2004-09-15 05:49:50 +0000356 PROCESS_INFORMATION pi;
357 memset(&pi, 0, sizeof(pi));
358
Jeff Cohen4220bf52005-02-20 02:43:04 +0000359 fflush(stdout);
360 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000361
362 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000363 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000364 SetLastError(ec.value());
365 MakeErrMsg(ErrMsg,
366 std::string("Unable to convert application name to UTF-16"));
367 return false;
368 }
369
370 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000371 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000372 SetLastError(ec.value());
373 MakeErrMsg(ErrMsg,
374 std::string("Unable to convert command-line to UTF-16"));
375 return false;
376 }
377
378 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
379 TRUE, CREATE_UNICODE_ENVIRONMENT,
380 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
381 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000382 DWORD err = GetLastError();
383
384 // Regardless of whether the process got created or not, we are done with
385 // the handles we created for it to inherit.
386 CloseHandle(si.hStdInput);
387 CloseHandle(si.hStdOutput);
388 CloseHandle(si.hStdError);
389
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000390 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000391 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000392 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000393 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000394 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000395 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000396 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000397
398 PI.Pid = pi.dwProcessId;
399 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000400
Jeff Cohena531d042007-03-05 05:22:08 +0000401 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000402 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000403
404 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000405 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000406 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000407 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000408 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000409 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000410 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
411 memset(&jeli, 0, sizeof(jeli));
412 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000413 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000414 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
415 &jeli, sizeof(jeli))) {
416 if (AssignProcessToJobObject(hJob, pi.hProcess))
417 success = true;
418 }
419 }
420 if (!success) {
421 SetLastError(GetLastError());
422 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
423 TerminateProcess(pi.hProcess, 1);
424 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000425 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000426 }
427 }
428
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000429 return true;
430}
431
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000432namespace llvm {
433ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
434 bool WaitUntilChildTerminates, std::string *ErrMsg) {
435 assert(PI.Pid && "invalid pid to wait on, process not started?");
436 assert(PI.ProcessHandle &&
437 "invalid process handle to wait on, process not started?");
438 DWORD milliSecondsToWait = 0;
439 if (WaitUntilChildTerminates)
440 milliSecondsToWait = INFINITE;
441 else if (SecondsToWait > 0)
442 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000443
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000444 ProcessInfo WaitResult = PI;
445 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
446 if (WaitStatus == WAIT_TIMEOUT) {
447 if (SecondsToWait) {
448 if (!TerminateProcess(PI.ProcessHandle, 1)) {
449 if (ErrMsg)
450 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
451
452 // -2 indicates a crash or timeout as opposed to failure to execute.
453 WaitResult.ReturnCode = -2;
454 CloseHandle(PI.ProcessHandle);
455 return WaitResult;
456 }
457 WaitForSingleObject(PI.ProcessHandle, INFINITE);
458 CloseHandle(PI.ProcessHandle);
459 } else {
460 // Non-blocking wait.
461 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000462 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000463 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000464
Reid Spencerb88212e2004-09-15 05:49:50 +0000465 // Get its exit status.
466 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000467 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000468 DWORD err = GetLastError();
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000469 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000470
Jeff Cohen4220bf52005-02-20 02:43:04 +0000471 if (!rc) {
472 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000473 if (ErrMsg)
474 MakeErrMsg(ErrMsg, "Failed getting status for program.");
475
Andrew Trickd5d07642011-05-21 00:56:46 +0000476 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000477 WaitResult.ReturnCode = -2;
478 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000479 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000480
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000481 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000482 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000483
484 // Pass 10(Warning) and 11(Error) to the callee as negative value.
485 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000486 WaitResult.ReturnCode = static_cast<int>(status);
487 else if (status & 0xFF)
488 WaitResult.ReturnCode = status & 0x7FFFFFFF;
489 else
490 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000491
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000492 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000493}
494
Yaron Kerenabce3c42014-09-26 22:27:11 +0000495std::error_code sys::ChangeStdinToBinary() {
496 int result = _setmode(_fileno(stdin), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000497 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000498 return std::error_code(errno, std::generic_category());
499 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000500}
501
Yaron Kerenabce3c42014-09-26 22:27:11 +0000502std::error_code sys::ChangeStdoutToBinary() {
503 int result = _setmode(_fileno(stdout), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000504 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000505 return std::error_code(errno, std::generic_category());
506 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000507}
508
Rafael Espindola9c359662014-09-03 20:02:00 +0000509std::error_code
510llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
511 WindowsEncodingMethod Encoding) {
512 std::error_code EC;
513 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
514 if (EC)
515 return EC;
516
517 if (Encoding == WEM_UTF8) {
518 OS << Contents;
519 } else if (Encoding == WEM_CurrentCodePage) {
520 SmallVector<wchar_t, 1> ArgsUTF16;
521 SmallVector<char, 1> ArgsCurCP;
522
523 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
524 return EC;
525
526 if ((EC = windows::UTF16ToCurCP(
527 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
528 return EC;
529
530 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
531 } else if (Encoding == WEM_UTF16) {
532 SmallVector<wchar_t, 1> ArgsUTF16;
533
534 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
535 return EC;
536
537 // Endianness guessing
538 char BOM[2];
539 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
540 memcpy(BOM, &src, 2);
541 OS.write(BOM, 2);
542 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
543 } else {
544 llvm_unreachable("Unknown encoding");
545 }
546
547 if (OS.has_error())
548 return std::make_error_code(std::errc::io_error);
549
550 return EC;
551}
552
Rafael Espindolacd848c02013-04-11 14:06:34 +0000553bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
554 // The documented max length of the command line passed to CreateProcess.
555 static const size_t MaxCommandStringLength = 32768;
556 size_t ArgLength = 0;
557 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
558 I != E; ++I) {
559 // Account for the trailing space for every arg but the last one and the
560 // trailing NULL of the last argument.
561 ArgLength += ArgLenWithQuotes(*I) + 1;
562 if (ArgLength > MaxCommandStringLength) {
563 return false;
564 }
565 }
566 return true;
567}
Reid Spencerb88212e2004-09-15 05:49:50 +0000568}