blob: 78fc538bd9bfbf5466de40c0959f081747c90249 [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 Espindola74f29322015-06-13 17:23:04 +000017#include "llvm/Support/Errc.h"
Rafael Espindolab0a5c962013-06-14 19:38:45 +000018#include "llvm/Support/FileSystem.h"
Michael J. Spencer65ffd922014-11-04 01:29:29 +000019#include "llvm/Support/WindowsError.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/Support/raw_ostream.h"
Reid Spencerab97f222006-06-07 23:18:34 +000021#include <cstdio>
Reid Spencerab97f222006-06-07 23:18:34 +000022#include <fcntl.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include <io.h>
24#include <malloc.h>
Reid Spencerb88212e2004-09-15 05:49:50 +000025
Reid Spencer76b83a12004-08-29 19:20:41 +000026//===----------------------------------------------------------------------===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000027//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb88212e2004-09-15 05:49:50 +000028//=== and must not be UNIX code
Reid Spencer76b83a12004-08-29 19:20:41 +000029//===----------------------------------------------------------------------===//
30
Reid Spencerb88212e2004-09-15 05:49:50 +000031namespace llvm {
32using namespace sys;
33
Alp Toker153675b2013-10-18 07:09:58 +000034ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
Tareq A. Sirajd88b9832013-10-01 14:28:18 +000035
Michael J. Spencer65ffd922014-11-04 01:29:29 +000036ErrorOr<std::string> sys::findProgramByName(StringRef Name,
37 ArrayRef<StringRef> Paths) {
38 assert(!Name.empty() && "Must have a name!");
39
40 if (Name.find_first_of("/\\") != StringRef::npos)
41 return std::string(Name);
42
Reid Kleckner4a786992014-11-13 22:09:56 +000043 const wchar_t *Path = nullptr;
44 std::wstring PathStorage;
Michael J. Spencer65ffd922014-11-04 01:29:29 +000045 if (!Paths.empty()) {
46 PathStorage.reserve(Paths.size() * MAX_PATH);
Yaron Kerenec69a4e2014-11-04 09:22:41 +000047 for (unsigned i = 0; i < Paths.size(); ++i) {
Michael J. Spencer65ffd922014-11-04 01:29:29 +000048 if (i)
Reid Kleckner4a786992014-11-13 22:09:56 +000049 PathStorage.push_back(L';');
Michael J. Spencer65ffd922014-11-04 01:29:29 +000050 StringRef P = Paths[i];
51 SmallVector<wchar_t, MAX_PATH> TmpPath;
52 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
53 return EC;
54 PathStorage.append(TmpPath.begin(), TmpPath.end());
55 }
56 Path = PathStorage.c_str();
57 }
58
59 SmallVector<wchar_t, MAX_PATH> U16Name;
60 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
61 return EC;
62
63 SmallVector<StringRef, 12> PathExts;
64 PathExts.push_back("");
NAKAMURA Takumi72e626e2014-11-04 08:17:15 +000065 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
Chandler Carruthec8406d2014-12-02 00:52:01 +000066 if (const char *PathExtEnv = std::getenv("PATHEXT"))
67 SplitString(PathExtEnv, PathExts, ";");
Michael J. Spencer65ffd922014-11-04 01:29:29 +000068
69 SmallVector<wchar_t, MAX_PATH> U16Result;
70 DWORD Len = MAX_PATH;
71 for (StringRef Ext : PathExts) {
72 SmallVector<wchar_t, MAX_PATH> U16Ext;
73 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
74 return EC;
75
76 do {
77 U16Result.reserve(Len);
George Rimar87780302015-10-08 16:03:19 +000078 // Lets attach the extension manually. That is needed for files
79 // with a point in name like aaa.bbb. SearchPathW will not add extension
80 // from its argument to such files because it thinks they already had one.
81 SmallVector<wchar_t, MAX_PATH> U16NameExt;
82 if (std::error_code EC =
83 windows::UTF8ToUTF16(Twine(Name + Ext).str(), U16NameExt))
84 return EC;
85
86 Len = ::SearchPathW(Path, c_str(U16NameExt), nullptr,
Michael J. Spencer65ffd922014-11-04 01:29:29 +000087 U16Result.capacity(), U16Result.data(), nullptr);
88 } while (Len > U16Result.capacity());
89
90 if (Len != 0)
91 break; // Found it.
92 }
93
94 if (Len == 0)
95 return mapWindowsError(::GetLastError());
96
97 U16Result.set_size(Len);
98
99 SmallVector<char, MAX_PATH> U8Result;
100 if (std::error_code EC =
101 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
102 return EC;
103
104 return std::string(U8Result.begin(), U8Result.end());
105}
106
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000107static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000108 HANDLE h;
109 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000110 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
111 GetCurrentProcess(), &h,
112 0, TRUE, DUPLICATE_SAME_ACCESS))
113 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000114 return h;
115 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000116
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000117 std::string fname;
118 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +0000119 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000120 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000121 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000122
123 SECURITY_ATTRIBUTES sa;
124 sa.nLength = sizeof(sa);
125 sa.lpSecurityDescriptor = 0;
126 sa.bInheritHandle = TRUE;
127
David Majnemer61eae2e2013-10-07 01:00:07 +0000128 SmallVector<wchar_t, 128> fnameUnicode;
Paul Robinsonc38deee2014-11-24 18:05:29 +0000129 if (path->empty()) {
130 // Don't play long-path tricks on "NUL".
131 if (windows::UTF8ToUTF16(fname, fnameUnicode))
132 return INVALID_HANDLE_VALUE;
133 } else {
134 if (path::widenPath(fname, fnameUnicode))
135 return INVALID_HANDLE_VALUE;
136 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000137 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
138 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
139 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000140 if (h == INVALID_HANDLE_VALUE) {
Paul Robinsonc38deee2014-11-24 18:05:29 +0000141 MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
Paul Robinsonaf19bc32015-11-23 17:34:20 +0000142 (fd ? "input" : "output"));
Jeff Cohen4220bf52005-02-20 02:43:04 +0000143 }
Jeff Cohena531d042007-03-05 05:22:08 +0000144
Jeff Cohen4220bf52005-02-20 02:43:04 +0000145 return h;
146}
147
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000148/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
149/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000150static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000151 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000152}
153
Reid Kleckner74679a92013-04-22 19:03:55 +0000154/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
155/// in the C string Start.
156static unsigned int CountPrecedingBackslashes(const char *Start,
157 const char *Cur) {
158 unsigned int Count = 0;
159 --Cur;
160 while (Cur >= Start && *Cur == '\\') {
161 ++Count;
162 --Cur;
163 }
164 return Count;
165}
166
167/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
168/// preceding Cur in the Start string. Assumes Dst has enough space.
169static char *EscapePrecedingEscapes(char *Dst, const char *Start,
170 const char *Cur) {
171 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
172 while (PrecedingEscapes > 0) {
173 *Dst++ = '\\';
174 --PrecedingEscapes;
175 }
176 return Dst;
177}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000178
179/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
180/// CreateProcess and returns length of quoted arg with escaped quotes
181static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000182 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000183 bool Quoted = ArgNeedsQuotes(Str);
184 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000185
186 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000187 if (*Str == '\"') {
188 // We need to add a backslash, but ensure that it isn't escaped.
189 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
190 len += PrecedingEscapes + 1;
191 }
192 // Note that we *don't* need to escape runs of backslashes that don't
193 // precede a double quote! See MSDN:
194 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000195
196 ++len;
197 ++Str;
198 }
199
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000200 if (Quoted) {
201 // Make sure the closing quote doesn't get escaped by a trailing backslash.
202 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
203 len += PrecedingEscapes + 1;
204 }
205
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000206 return len;
207}
208
Rafael Espindola404ae772013-06-12 21:11:50 +0000209}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000210
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000211static std::unique_ptr<char[]> flattenArgs(const char **args) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000212 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000213 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000214 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000215 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000216 }
217
218 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000219 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000220 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000221
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000222 for (unsigned i = 0; args[i]; i++) {
223 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000224 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000225
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000226 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000227 if (needsQuoting)
228 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000229
230 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000231 if (*arg == '\"') {
232 // Escape all preceding escapes (if any), and then escape the quote.
233 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000234 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000235 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000236
237 *p++ = *arg++;
238 }
239
Reid Kleckner74679a92013-04-22 19:03:55 +0000240 if (needsQuoting) {
241 // Make sure our quote doesn't get escaped by a trailing backslash.
242 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000243 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000244 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000245 *p++ = ' ';
246 }
247
248 *p = 0;
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000249 return command;
250}
251
252static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
253 const char **envp, const StringRef **redirects,
254 unsigned memoryLimit, std::string *ErrMsg) {
255 if (!sys::fs::can_execute(Program)) {
256 if (ErrMsg)
257 *ErrMsg = "program not executable";
258 return false;
259 }
260
Reid Kleckner95ce1df2015-09-10 23:59:45 +0000261 // can_execute may succeed by looking at Program + ".exe". CreateProcessW
262 // will implicitly add the .exe if we provide a command line without an
263 // executable path, but since we use an explicit executable, we have to add
264 // ".exe" ourselves.
265 SmallString<64> ProgramStorage;
266 if (!sys::fs::exists(Program))
267 Program = Twine(Program + ".exe").toStringRef(ProgramStorage);
268
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000269 // Windows wants a command line, not an array of args, to pass to the new
270 // process. We have to concatenate them all, while quoting the args that
271 // have embedded spaces (or are empty).
272 std::unique_ptr<char[]> command = flattenArgs(args);
Reid Spencerb88212e2004-09-15 05:49:50 +0000273
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000274 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000275 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000276
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000277 if (envp) {
278 // An environment block consists of a null-terminated block of
279 // null-terminated strings. Convert the array of environment variables to
280 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000281 for (unsigned i = 0; envp[i]; ++i) {
282 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000283 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000284 SetLastError(ec.value());
285 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
286 return false;
287 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000288
David Majnemer61eae2e2013-10-07 01:00:07 +0000289 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
290 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000291 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000292 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000293 }
294
Reid Spencerb88212e2004-09-15 05:49:50 +0000295 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000296 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000297 memset(&si, 0, sizeof(si));
298 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000299 si.hStdInput = INVALID_HANDLE_VALUE;
300 si.hStdOutput = INVALID_HANDLE_VALUE;
301 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000302
Jeff Cohen4220bf52005-02-20 02:43:04 +0000303 if (redirects) {
304 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000305
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000306 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
307 if (si.hStdInput == INVALID_HANDLE_VALUE) {
308 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000309 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000310 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000311 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000312 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000313 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000314 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000315 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000316 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000317 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
318 // If stdout and stderr should go to the same place, redirect stderr
319 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000320 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
321 GetCurrentProcess(), &si.hStdError,
322 0, TRUE, DUPLICATE_SAME_ACCESS)) {
323 CloseHandle(si.hStdInput);
324 CloseHandle(si.hStdOutput);
325 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
326 return false;
327 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000328 } else {
329 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000330 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000331 if (si.hStdError == INVALID_HANDLE_VALUE) {
332 CloseHandle(si.hStdInput);
333 CloseHandle(si.hStdOutput);
334 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000335 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000336 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000337 }
338 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000339
Reid Spencerb88212e2004-09-15 05:49:50 +0000340 PROCESS_INFORMATION pi;
341 memset(&pi, 0, sizeof(pi));
342
Jeff Cohen4220bf52005-02-20 02:43:04 +0000343 fflush(stdout);
344 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000345
346 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Paul Robinsonc38deee2014-11-24 18:05:29 +0000347 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000348 SetLastError(ec.value());
349 MakeErrMsg(ErrMsg,
350 std::string("Unable to convert application name to UTF-16"));
351 return false;
352 }
353
354 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000355 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000356 SetLastError(ec.value());
357 MakeErrMsg(ErrMsg,
358 std::string("Unable to convert command-line to UTF-16"));
359 return false;
360 }
361
362 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
363 TRUE, CREATE_UNICODE_ENVIRONMENT,
364 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
365 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000366 DWORD err = GetLastError();
367
368 // Regardless of whether the process got created or not, we are done with
369 // the handles we created for it to inherit.
370 CloseHandle(si.hStdInput);
371 CloseHandle(si.hStdOutput);
372 CloseHandle(si.hStdError);
373
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000374 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000375 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000376 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000377 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000378 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000379 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000380 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000381
382 PI.Pid = pi.dwProcessId;
383 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000384
Jeff Cohena531d042007-03-05 05:22:08 +0000385 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000386 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000387
388 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000389 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000390 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000391 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000392 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000393 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000394 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
395 memset(&jeli, 0, sizeof(jeli));
396 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000397 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000398 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
399 &jeli, sizeof(jeli))) {
400 if (AssignProcessToJobObject(hJob, pi.hProcess))
401 success = true;
402 }
403 }
404 if (!success) {
405 SetLastError(GetLastError());
406 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
407 TerminateProcess(pi.hProcess, 1);
408 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000409 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000410 }
411 }
412
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000413 return true;
414}
415
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000416namespace llvm {
417ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
418 bool WaitUntilChildTerminates, std::string *ErrMsg) {
419 assert(PI.Pid && "invalid pid to wait on, process not started?");
420 assert(PI.ProcessHandle &&
421 "invalid process handle to wait on, process not started?");
422 DWORD milliSecondsToWait = 0;
423 if (WaitUntilChildTerminates)
424 milliSecondsToWait = INFINITE;
425 else if (SecondsToWait > 0)
426 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000427
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000428 ProcessInfo WaitResult = PI;
429 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
430 if (WaitStatus == WAIT_TIMEOUT) {
431 if (SecondsToWait) {
432 if (!TerminateProcess(PI.ProcessHandle, 1)) {
433 if (ErrMsg)
Paul Robinsonaf19bc32015-11-23 17:34:20 +0000434 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program");
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000435
436 // -2 indicates a crash or timeout as opposed to failure to execute.
437 WaitResult.ReturnCode = -2;
438 CloseHandle(PI.ProcessHandle);
439 return WaitResult;
440 }
441 WaitForSingleObject(PI.ProcessHandle, INFINITE);
Yaron Keren97de5732015-04-17 12:11:15 +0000442 CloseHandle(PI.ProcessHandle);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000443 } else {
444 // Non-blocking wait.
445 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000446 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000447 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000448
Reid Spencerb88212e2004-09-15 05:49:50 +0000449 // Get its exit status.
450 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000451 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000452 DWORD err = GetLastError();
Yaron Keren97de5732015-04-17 12:11:15 +0000453 if (err != ERROR_INVALID_HANDLE)
454 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000455
Jeff Cohen4220bf52005-02-20 02:43:04 +0000456 if (!rc) {
457 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000458 if (ErrMsg)
Paul Robinsonaf19bc32015-11-23 17:34:20 +0000459 MakeErrMsg(ErrMsg, "Failed getting status for program");
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000460
Andrew Trickd5d07642011-05-21 00:56:46 +0000461 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000462 WaitResult.ReturnCode = -2;
463 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000464 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000465
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000466 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000467 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000468
469 // Pass 10(Warning) and 11(Error) to the callee as negative value.
470 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000471 WaitResult.ReturnCode = static_cast<int>(status);
472 else if (status & 0xFF)
473 WaitResult.ReturnCode = status & 0x7FFFFFFF;
474 else
475 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000476
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000477 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000478}
479
Yaron Kerenabce3c42014-09-26 22:27:11 +0000480std::error_code sys::ChangeStdinToBinary() {
481 int result = _setmode(_fileno(stdin), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000482 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000483 return std::error_code(errno, std::generic_category());
484 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000485}
486
Yaron Kerenabce3c42014-09-26 22:27:11 +0000487std::error_code sys::ChangeStdoutToBinary() {
488 int result = _setmode(_fileno(stdout), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000489 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000490 return std::error_code(errno, std::generic_category());
491 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000492}
493
Rafael Espindola9c359662014-09-03 20:02:00 +0000494std::error_code
495llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
496 WindowsEncodingMethod Encoding) {
497 std::error_code EC;
498 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
499 if (EC)
500 return EC;
501
502 if (Encoding == WEM_UTF8) {
503 OS << Contents;
504 } else if (Encoding == WEM_CurrentCodePage) {
505 SmallVector<wchar_t, 1> ArgsUTF16;
506 SmallVector<char, 1> ArgsCurCP;
507
508 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
509 return EC;
510
511 if ((EC = windows::UTF16ToCurCP(
512 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
513 return EC;
514
515 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
516 } else if (Encoding == WEM_UTF16) {
517 SmallVector<wchar_t, 1> ArgsUTF16;
518
519 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
520 return EC;
521
522 // Endianness guessing
523 char BOM[2];
524 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
525 memcpy(BOM, &src, 2);
526 OS.write(BOM, 2);
527 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
528 } else {
529 llvm_unreachable("Unknown encoding");
530 }
531
532 if (OS.has_error())
Rafael Espindola74f29322015-06-13 17:23:04 +0000533 return make_error_code(errc::io_error);
Rafael Espindola9c359662014-09-03 20:02:00 +0000534
535 return EC;
536}
537
Oleg Ranevskyy2e837902016-01-05 19:56:12 +0000538bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef<const char*> Args) {
Rafael Espindolacd848c02013-04-11 14:06:34 +0000539 // The documented max length of the command line passed to CreateProcess.
540 static const size_t MaxCommandStringLength = 32768;
Oleg Ranevskyy2e837902016-01-05 19:56:12 +0000541 // Account for the trailing space for the program path and the
542 // trailing NULL of the last argument.
543 size_t ArgLength = ArgLenWithQuotes(Program.str().c_str()) + 2;
Rafael Espindolacd848c02013-04-11 14:06:34 +0000544 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
545 I != E; ++I) {
Oleg Ranevskyy2e837902016-01-05 19:56:12 +0000546 // Account for the trailing space for every arg
Rafael Espindolacd848c02013-04-11 14:06:34 +0000547 ArgLength += ArgLenWithQuotes(*I) + 1;
548 if (ArgLength > MaxCommandStringLength) {
549 return false;
550 }
551 }
552 return true;
553}
Reid Spencerb88212e2004-09-15 05:49:50 +0000554}