blob: 75685de4554768de9d0e0a150ef66d17a1943d8b [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"
Michael J. Spencer65ffd922014-11-04 01:29:29 +000018#include "llvm/Support/WindowsError.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "llvm/Support/raw_ostream.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
Michael J. Spencer65ffd922014-11-04 01:29:29 +000035ErrorOr<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
Reid Kleckner4a786992014-11-13 22:09:56 +000042 const wchar_t *Path = nullptr;
43 std::wstring PathStorage;
Michael J. Spencer65ffd922014-11-04 01:29:29 +000044 if (!Paths.empty()) {
45 PathStorage.reserve(Paths.size() * MAX_PATH);
Yaron Kerenec69a4e2014-11-04 09:22:41 +000046 for (unsigned i = 0; i < Paths.size(); ++i) {
Michael J. Spencer65ffd922014-11-04 01:29:29 +000047 if (i)
Reid Kleckner4a786992014-11-13 22:09:56 +000048 PathStorage.push_back(L';');
Michael J. Spencer65ffd922014-11-04 01:29:29 +000049 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("");
NAKAMURA Takumi72e626e2014-11-04 08:17:15 +000064 PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
Chandler Carruthec8406d2014-12-02 00:52:01 +000065 if (const char *PathExtEnv = std::getenv("PATHEXT"))
66 SplitString(PathExtEnv, PathExts, ";");
Michael J. Spencer65ffd922014-11-04 01:29:29 +000067
68 SmallVector<wchar_t, MAX_PATH> U16Result;
69 DWORD Len = MAX_PATH;
70 for (StringRef Ext : PathExts) {
71 SmallVector<wchar_t, MAX_PATH> U16Ext;
72 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
73 return EC;
74
75 do {
76 U16Result.reserve(Len);
Reid Kleckner4a786992014-11-13 22:09:56 +000077 Len = ::SearchPathW(Path, c_str(U16Name),
Michael J. Spencer65ffd922014-11-04 01:29:29 +000078 U16Ext.empty() ? nullptr : c_str(U16Ext),
79 U16Result.capacity(), U16Result.data(), nullptr);
80 } while (Len > U16Result.capacity());
81
82 if (Len != 0)
83 break; // Found it.
84 }
85
86 if (Len == 0)
87 return mapWindowsError(::GetLastError());
88
89 U16Result.set_size(Len);
90
91 SmallVector<char, MAX_PATH> U8Result;
92 if (std::error_code EC =
93 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
94 return EC;
95
96 return std::string(U8Result.begin(), U8Result.end());
97}
98
Rafael Espindolab0a5c962013-06-14 19:38:45 +000099static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000100 HANDLE h;
101 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000102 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
103 GetCurrentProcess(), &h,
104 0, TRUE, DUPLICATE_SAME_ACCESS))
105 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000106 return h;
107 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000108
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000109 std::string fname;
110 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +0000111 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000112 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000113 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000114
115 SECURITY_ATTRIBUTES sa;
116 sa.nLength = sizeof(sa);
117 sa.lpSecurityDescriptor = 0;
118 sa.bInheritHandle = TRUE;
119
David Majnemer61eae2e2013-10-07 01:00:07 +0000120 SmallVector<wchar_t, 128> fnameUnicode;
Paul Robinsonc38deee2014-11-24 18:05:29 +0000121 if (path->empty()) {
122 // Don't play long-path tricks on "NUL".
123 if (windows::UTF8ToUTF16(fname, fnameUnicode))
124 return INVALID_HANDLE_VALUE;
125 } else {
126 if (path::widenPath(fname, fnameUnicode))
127 return INVALID_HANDLE_VALUE;
128 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000129 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
130 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
131 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000132 if (h == INVALID_HANDLE_VALUE) {
Paul Robinsonc38deee2014-11-24 18:05:29 +0000133 MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000134 (fd ? "input: " : "output: "));
135 }
Jeff Cohena531d042007-03-05 05:22:08 +0000136
Jeff Cohen4220bf52005-02-20 02:43:04 +0000137 return h;
138}
139
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000140/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
141/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000142static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000143 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000144}
145
Reid Kleckner74679a92013-04-22 19:03:55 +0000146/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
147/// in the C string Start.
148static unsigned int CountPrecedingBackslashes(const char *Start,
149 const char *Cur) {
150 unsigned int Count = 0;
151 --Cur;
152 while (Cur >= Start && *Cur == '\\') {
153 ++Count;
154 --Cur;
155 }
156 return Count;
157}
158
159/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
160/// preceding Cur in the Start string. Assumes Dst has enough space.
161static char *EscapePrecedingEscapes(char *Dst, const char *Start,
162 const char *Cur) {
163 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
164 while (PrecedingEscapes > 0) {
165 *Dst++ = '\\';
166 --PrecedingEscapes;
167 }
168 return Dst;
169}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000170
171/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
172/// CreateProcess and returns length of quoted arg with escaped quotes
173static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000174 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000175 bool Quoted = ArgNeedsQuotes(Str);
176 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000177
178 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000179 if (*Str == '\"') {
180 // We need to add a backslash, but ensure that it isn't escaped.
181 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
182 len += PrecedingEscapes + 1;
183 }
184 // Note that we *don't* need to escape runs of backslashes that don't
185 // precede a double quote! See MSDN:
186 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000187
188 ++len;
189 ++Str;
190 }
191
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000192 if (Quoted) {
193 // Make sure the closing quote doesn't get escaped by a trailing backslash.
194 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
195 len += PrecedingEscapes + 1;
196 }
197
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000198 return len;
199}
200
Rafael Espindola404ae772013-06-12 21:11:50 +0000201}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000202
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000203static std::unique_ptr<char[]> flattenArgs(const char **args) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000204 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000205 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000206 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000207 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000208 }
209
210 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000211 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000212 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000213
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000214 for (unsigned i = 0; args[i]; i++) {
215 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000216 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000217
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000218 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000219 if (needsQuoting)
220 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000221
222 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000223 if (*arg == '\"') {
224 // Escape all preceding escapes (if any), and then escape the quote.
225 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000226 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000227 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000228
229 *p++ = *arg++;
230 }
231
Reid Kleckner74679a92013-04-22 19:03:55 +0000232 if (needsQuoting) {
233 // Make sure our quote doesn't get escaped by a trailing backslash.
234 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000235 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000236 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000237 *p++ = ' ';
238 }
239
240 *p = 0;
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000241 return command;
242}
243
244static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
245 const char **envp, const StringRef **redirects,
246 unsigned memoryLimit, std::string *ErrMsg) {
247 if (!sys::fs::can_execute(Program)) {
248 if (ErrMsg)
249 *ErrMsg = "program not executable";
250 return false;
251 }
252
253 // Windows wants a command line, not an array of args, to pass to the new
254 // process. We have to concatenate them all, while quoting the args that
255 // have embedded spaces (or are empty).
256 std::unique_ptr<char[]> command = flattenArgs(args);
Reid Spencerb88212e2004-09-15 05:49:50 +0000257
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000258 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000259 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000260
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000261 if (envp) {
262 // An environment block consists of a null-terminated block of
263 // null-terminated strings. Convert the array of environment variables to
264 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000265 for (unsigned i = 0; envp[i]; ++i) {
266 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000267 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000268 SetLastError(ec.value());
269 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
270 return false;
271 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000272
David Majnemer61eae2e2013-10-07 01:00:07 +0000273 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
274 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000275 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000276 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000277 }
278
Reid Spencerb88212e2004-09-15 05:49:50 +0000279 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000280 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000281 memset(&si, 0, sizeof(si));
282 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000283 si.hStdInput = INVALID_HANDLE_VALUE;
284 si.hStdOutput = INVALID_HANDLE_VALUE;
285 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000286
Jeff Cohen4220bf52005-02-20 02:43:04 +0000287 if (redirects) {
288 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000289
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000290 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
291 if (si.hStdInput == INVALID_HANDLE_VALUE) {
292 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000293 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000294 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000295 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000296 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000297 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000298 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000299 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000300 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000301 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
302 // If stdout and stderr should go to the same place, redirect stderr
303 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000304 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
305 GetCurrentProcess(), &si.hStdError,
306 0, TRUE, DUPLICATE_SAME_ACCESS)) {
307 CloseHandle(si.hStdInput);
308 CloseHandle(si.hStdOutput);
309 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
310 return false;
311 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000312 } else {
313 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000314 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000315 if (si.hStdError == INVALID_HANDLE_VALUE) {
316 CloseHandle(si.hStdInput);
317 CloseHandle(si.hStdOutput);
318 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000319 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000320 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000321 }
322 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000323
Reid Spencerb88212e2004-09-15 05:49:50 +0000324 PROCESS_INFORMATION pi;
325 memset(&pi, 0, sizeof(pi));
326
Jeff Cohen4220bf52005-02-20 02:43:04 +0000327 fflush(stdout);
328 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000329
330 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Paul Robinsonc38deee2014-11-24 18:05:29 +0000331 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000332 SetLastError(ec.value());
333 MakeErrMsg(ErrMsg,
334 std::string("Unable to convert application name to UTF-16"));
335 return false;
336 }
337
338 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000339 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000340 SetLastError(ec.value());
341 MakeErrMsg(ErrMsg,
342 std::string("Unable to convert command-line to UTF-16"));
343 return false;
344 }
345
346 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
347 TRUE, CREATE_UNICODE_ENVIRONMENT,
348 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
349 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000350 DWORD err = GetLastError();
351
352 // Regardless of whether the process got created or not, we are done with
353 // the handles we created for it to inherit.
354 CloseHandle(si.hStdInput);
355 CloseHandle(si.hStdOutput);
356 CloseHandle(si.hStdError);
357
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000358 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000359 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000360 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000361 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000362 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000363 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000364 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000365
366 PI.Pid = pi.dwProcessId;
367 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000368
Jeff Cohena531d042007-03-05 05:22:08 +0000369 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000370 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000371
372 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000373 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000374 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000375 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000376 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000377 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000378 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
379 memset(&jeli, 0, sizeof(jeli));
380 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000381 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000382 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
383 &jeli, sizeof(jeli))) {
384 if (AssignProcessToJobObject(hJob, pi.hProcess))
385 success = true;
386 }
387 }
388 if (!success) {
389 SetLastError(GetLastError());
390 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
391 TerminateProcess(pi.hProcess, 1);
392 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000393 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000394 }
395 }
396
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000397 return true;
398}
399
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000400namespace llvm {
401ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
402 bool WaitUntilChildTerminates, std::string *ErrMsg) {
403 assert(PI.Pid && "invalid pid to wait on, process not started?");
404 assert(PI.ProcessHandle &&
405 "invalid process handle to wait on, process not started?");
406 DWORD milliSecondsToWait = 0;
407 if (WaitUntilChildTerminates)
408 milliSecondsToWait = INFINITE;
409 else if (SecondsToWait > 0)
410 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000411
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000412 ProcessInfo WaitResult = PI;
413 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
414 if (WaitStatus == WAIT_TIMEOUT) {
415 if (SecondsToWait) {
416 if (!TerminateProcess(PI.ProcessHandle, 1)) {
417 if (ErrMsg)
418 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
419
420 // -2 indicates a crash or timeout as opposed to failure to execute.
421 WaitResult.ReturnCode = -2;
422 CloseHandle(PI.ProcessHandle);
423 return WaitResult;
424 }
425 WaitForSingleObject(PI.ProcessHandle, INFINITE);
Yaron Keren97de5732015-04-17 12:11:15 +0000426 CloseHandle(PI.ProcessHandle);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000427 } else {
428 // Non-blocking wait.
429 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000430 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000431 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000432
Reid Spencerb88212e2004-09-15 05:49:50 +0000433 // Get its exit status.
434 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000435 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000436 DWORD err = GetLastError();
Yaron Keren97de5732015-04-17 12:11:15 +0000437 if (err != ERROR_INVALID_HANDLE)
438 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000439
Jeff Cohen4220bf52005-02-20 02:43:04 +0000440 if (!rc) {
441 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000442 if (ErrMsg)
443 MakeErrMsg(ErrMsg, "Failed getting status for program.");
444
Andrew Trickd5d07642011-05-21 00:56:46 +0000445 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000446 WaitResult.ReturnCode = -2;
447 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000448 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000449
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000450 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000451 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000452
453 // Pass 10(Warning) and 11(Error) to the callee as negative value.
454 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000455 WaitResult.ReturnCode = static_cast<int>(status);
456 else if (status & 0xFF)
457 WaitResult.ReturnCode = status & 0x7FFFFFFF;
458 else
459 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000460
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000461 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000462}
463
Yaron Kerenabce3c42014-09-26 22:27:11 +0000464std::error_code sys::ChangeStdinToBinary() {
465 int result = _setmode(_fileno(stdin), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000466 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000467 return std::error_code(errno, std::generic_category());
468 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000469}
470
Yaron Kerenabce3c42014-09-26 22:27:11 +0000471std::error_code sys::ChangeStdoutToBinary() {
472 int result = _setmode(_fileno(stdout), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000473 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000474 return std::error_code(errno, std::generic_category());
475 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000476}
477
Rafael Espindola9c359662014-09-03 20:02:00 +0000478std::error_code
479llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
480 WindowsEncodingMethod Encoding) {
481 std::error_code EC;
482 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
483 if (EC)
484 return EC;
485
486 if (Encoding == WEM_UTF8) {
487 OS << Contents;
488 } else if (Encoding == WEM_CurrentCodePage) {
489 SmallVector<wchar_t, 1> ArgsUTF16;
490 SmallVector<char, 1> ArgsCurCP;
491
492 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
493 return EC;
494
495 if ((EC = windows::UTF16ToCurCP(
496 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
497 return EC;
498
499 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
500 } else if (Encoding == WEM_UTF16) {
501 SmallVector<wchar_t, 1> ArgsUTF16;
502
503 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
504 return EC;
505
506 // Endianness guessing
507 char BOM[2];
508 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
509 memcpy(BOM, &src, 2);
510 OS.write(BOM, 2);
511 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
512 } else {
513 llvm_unreachable("Unknown encoding");
514 }
515
516 if (OS.has_error())
517 return std::make_error_code(std::errc::io_error);
518
519 return EC;
520}
521
Rafael Espindolacd848c02013-04-11 14:06:34 +0000522bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
523 // The documented max length of the command line passed to CreateProcess.
524 static const size_t MaxCommandStringLength = 32768;
525 size_t ArgLength = 0;
526 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
527 I != E; ++I) {
528 // Account for the trailing space for every arg but the last one and the
529 // trailing NULL of the last argument.
530 ArgLength += ArgLenWithQuotes(*I) + 1;
531 if (ArgLength > MaxCommandStringLength) {
532 return false;
533 }
534 }
535 return true;
536}
Reid Spencerb88212e2004-09-15 05:49:50 +0000537}