blob: 72c2a58688d6a551813f4eb32ff32dee860e3b63 [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
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%.
Michael J. Spencer65ffd922014-11-04 01:29:29 +000065 SplitString(std::getenv("PATHEXT"), PathExts, ";");
66
67 SmallVector<wchar_t, MAX_PATH> U16Result;
68 DWORD Len = MAX_PATH;
69 for (StringRef Ext : PathExts) {
70 SmallVector<wchar_t, MAX_PATH> U16Ext;
71 if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
72 return EC;
73
74 do {
75 U16Result.reserve(Len);
Reid Kleckner4a786992014-11-13 22:09:56 +000076 Len = ::SearchPathW(Path, c_str(U16Name),
Michael J. Spencer65ffd922014-11-04 01:29:29 +000077 U16Ext.empty() ? nullptr : c_str(U16Ext),
78 U16Result.capacity(), U16Result.data(), nullptr);
79 } while (Len > U16Result.capacity());
80
81 if (Len != 0)
82 break; // Found it.
83 }
84
85 if (Len == 0)
86 return mapWindowsError(::GetLastError());
87
88 U16Result.set_size(Len);
89
90 SmallVector<char, MAX_PATH> U8Result;
91 if (std::error_code EC =
92 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
93 return EC;
94
95 return std::string(U8Result.begin(), U8Result.end());
96}
97
Rafael Espindolab0a5c962013-06-14 19:38:45 +000098static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +000099 HANDLE h;
100 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000101 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
102 GetCurrentProcess(), &h,
103 0, TRUE, DUPLICATE_SAME_ACCESS))
104 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000105 return h;
106 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000107
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000108 std::string fname;
109 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +0000110 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +0000111 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000112 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000113
114 SECURITY_ATTRIBUTES sa;
115 sa.nLength = sizeof(sa);
116 sa.lpSecurityDescriptor = 0;
117 sa.bInheritHandle = TRUE;
118
David Majnemer61eae2e2013-10-07 01:00:07 +0000119 SmallVector<wchar_t, 128> fnameUnicode;
120 if (windows::UTF8ToUTF16(fname, fnameUnicode))
121 return INVALID_HANDLE_VALUE;
122
123 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
124 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
125 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000126 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000127 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000128 (fd ? "input: " : "output: "));
129 }
Jeff Cohena531d042007-03-05 05:22:08 +0000130
Jeff Cohen4220bf52005-02-20 02:43:04 +0000131 return h;
132}
133
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000134/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
135/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000136static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000137 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000138}
139
Reid Kleckner74679a92013-04-22 19:03:55 +0000140/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
141/// in the C string Start.
142static unsigned int CountPrecedingBackslashes(const char *Start,
143 const char *Cur) {
144 unsigned int Count = 0;
145 --Cur;
146 while (Cur >= Start && *Cur == '\\') {
147 ++Count;
148 --Cur;
149 }
150 return Count;
151}
152
153/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
154/// preceding Cur in the Start string. Assumes Dst has enough space.
155static char *EscapePrecedingEscapes(char *Dst, const char *Start,
156 const char *Cur) {
157 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
158 while (PrecedingEscapes > 0) {
159 *Dst++ = '\\';
160 --PrecedingEscapes;
161 }
162 return Dst;
163}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000164
165/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
166/// CreateProcess and returns length of quoted arg with escaped quotes
167static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000168 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000169 bool Quoted = ArgNeedsQuotes(Str);
170 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000171
172 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000173 if (*Str == '\"') {
174 // We need to add a backslash, but ensure that it isn't escaped.
175 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
176 len += PrecedingEscapes + 1;
177 }
178 // Note that we *don't* need to escape runs of backslashes that don't
179 // precede a double quote! See MSDN:
180 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000181
182 ++len;
183 ++Str;
184 }
185
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000186 if (Quoted) {
187 // Make sure the closing quote doesn't get escaped by a trailing backslash.
188 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
189 len += PrecedingEscapes + 1;
190 }
191
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000192 return len;
193}
194
Rafael Espindola404ae772013-06-12 21:11:50 +0000195}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000196
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000197static std::unique_ptr<char[]> flattenArgs(const char **args) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000198 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000199 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000200 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000201 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000202 }
203
204 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000205 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000206 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000207
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000208 for (unsigned i = 0; args[i]; i++) {
209 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000210 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000211
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000212 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000213 if (needsQuoting)
214 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000215
216 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000217 if (*arg == '\"') {
218 // Escape all preceding escapes (if any), and then escape the quote.
219 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000220 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000221 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000222
223 *p++ = *arg++;
224 }
225
Reid Kleckner74679a92013-04-22 19:03:55 +0000226 if (needsQuoting) {
227 // Make sure our quote doesn't get escaped by a trailing backslash.
228 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000229 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000230 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000231 *p++ = ' ';
232 }
233
234 *p = 0;
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000235 return command;
236}
237
238static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
239 const char **envp, const StringRef **redirects,
240 unsigned memoryLimit, std::string *ErrMsg) {
241 if (!sys::fs::can_execute(Program)) {
242 if (ErrMsg)
243 *ErrMsg = "program not executable";
244 return false;
245 }
246
247 // Windows wants a command line, not an array of args, to pass to the new
248 // process. We have to concatenate them all, while quoting the args that
249 // have embedded spaces (or are empty).
250 std::unique_ptr<char[]> command = flattenArgs(args);
Reid Spencerb88212e2004-09-15 05:49:50 +0000251
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000252 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000253 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000254
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000255 if (envp) {
256 // An environment block consists of a null-terminated block of
257 // null-terminated strings. Convert the array of environment variables to
258 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000259 for (unsigned i = 0; envp[i]; ++i) {
260 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000261 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000262 SetLastError(ec.value());
263 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
264 return false;
265 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000266
David Majnemer61eae2e2013-10-07 01:00:07 +0000267 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
268 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000269 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000270 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000271 }
272
Reid Spencerb88212e2004-09-15 05:49:50 +0000273 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000274 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000275 memset(&si, 0, sizeof(si));
276 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000277 si.hStdInput = INVALID_HANDLE_VALUE;
278 si.hStdOutput = INVALID_HANDLE_VALUE;
279 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000280
Jeff Cohen4220bf52005-02-20 02:43:04 +0000281 if (redirects) {
282 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000283
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000284 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
285 if (si.hStdInput == INVALID_HANDLE_VALUE) {
286 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000287 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000288 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000289 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000290 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000291 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000292 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000293 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000294 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000295 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
296 // If stdout and stderr should go to the same place, redirect stderr
297 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000298 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
299 GetCurrentProcess(), &si.hStdError,
300 0, TRUE, DUPLICATE_SAME_ACCESS)) {
301 CloseHandle(si.hStdInput);
302 CloseHandle(si.hStdOutput);
303 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
304 return false;
305 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000306 } else {
307 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000308 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000309 if (si.hStdError == INVALID_HANDLE_VALUE) {
310 CloseHandle(si.hStdInput);
311 CloseHandle(si.hStdOutput);
312 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000313 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000314 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000315 }
316 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000317
Reid Spencerb88212e2004-09-15 05:49:50 +0000318 PROCESS_INFORMATION pi;
319 memset(&pi, 0, sizeof(pi));
320
Jeff Cohen4220bf52005-02-20 02:43:04 +0000321 fflush(stdout);
322 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000323
324 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000325 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000326 SetLastError(ec.value());
327 MakeErrMsg(ErrMsg,
328 std::string("Unable to convert application name to UTF-16"));
329 return false;
330 }
331
332 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000333 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000334 SetLastError(ec.value());
335 MakeErrMsg(ErrMsg,
336 std::string("Unable to convert command-line to UTF-16"));
337 return false;
338 }
339
340 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
341 TRUE, CREATE_UNICODE_ENVIRONMENT,
342 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
343 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000344 DWORD err = GetLastError();
345
346 // Regardless of whether the process got created or not, we are done with
347 // the handles we created for it to inherit.
348 CloseHandle(si.hStdInput);
349 CloseHandle(si.hStdOutput);
350 CloseHandle(si.hStdError);
351
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000352 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000353 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000354 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000355 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000356 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000357 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000358 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000359
360 PI.Pid = pi.dwProcessId;
361 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000362
Jeff Cohena531d042007-03-05 05:22:08 +0000363 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000364 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000365
366 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000367 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000368 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000369 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000370 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000371 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000372 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
373 memset(&jeli, 0, sizeof(jeli));
374 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000375 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000376 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
377 &jeli, sizeof(jeli))) {
378 if (AssignProcessToJobObject(hJob, pi.hProcess))
379 success = true;
380 }
381 }
382 if (!success) {
383 SetLastError(GetLastError());
384 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
385 TerminateProcess(pi.hProcess, 1);
386 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000387 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000388 }
389 }
390
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000391 return true;
392}
393
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000394namespace llvm {
395ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
396 bool WaitUntilChildTerminates, std::string *ErrMsg) {
397 assert(PI.Pid && "invalid pid to wait on, process not started?");
398 assert(PI.ProcessHandle &&
399 "invalid process handle to wait on, process not started?");
400 DWORD milliSecondsToWait = 0;
401 if (WaitUntilChildTerminates)
402 milliSecondsToWait = INFINITE;
403 else if (SecondsToWait > 0)
404 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000405
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000406 ProcessInfo WaitResult = PI;
407 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
408 if (WaitStatus == WAIT_TIMEOUT) {
409 if (SecondsToWait) {
410 if (!TerminateProcess(PI.ProcessHandle, 1)) {
411 if (ErrMsg)
412 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
413
414 // -2 indicates a crash or timeout as opposed to failure to execute.
415 WaitResult.ReturnCode = -2;
416 CloseHandle(PI.ProcessHandle);
417 return WaitResult;
418 }
419 WaitForSingleObject(PI.ProcessHandle, INFINITE);
420 CloseHandle(PI.ProcessHandle);
421 } else {
422 // Non-blocking wait.
423 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000424 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000425 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000426
Reid Spencerb88212e2004-09-15 05:49:50 +0000427 // Get its exit status.
428 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000429 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000430 DWORD err = GetLastError();
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000431 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000432
Jeff Cohen4220bf52005-02-20 02:43:04 +0000433 if (!rc) {
434 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000435 if (ErrMsg)
436 MakeErrMsg(ErrMsg, "Failed getting status for program.");
437
Andrew Trickd5d07642011-05-21 00:56:46 +0000438 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000439 WaitResult.ReturnCode = -2;
440 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000441 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000442
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000443 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000444 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000445
446 // Pass 10(Warning) and 11(Error) to the callee as negative value.
447 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000448 WaitResult.ReturnCode = static_cast<int>(status);
449 else if (status & 0xFF)
450 WaitResult.ReturnCode = status & 0x7FFFFFFF;
451 else
452 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000453
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000454 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000455}
456
Yaron Kerenabce3c42014-09-26 22:27:11 +0000457std::error_code sys::ChangeStdinToBinary() {
458 int result = _setmode(_fileno(stdin), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000459 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000460 return std::error_code(errno, std::generic_category());
461 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000462}
463
Yaron Kerenabce3c42014-09-26 22:27:11 +0000464std::error_code sys::ChangeStdoutToBinary() {
465 int result = _setmode(_fileno(stdout), _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
Rafael Espindola9c359662014-09-03 20:02:00 +0000471std::error_code
472llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
473 WindowsEncodingMethod Encoding) {
474 std::error_code EC;
475 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
476 if (EC)
477 return EC;
478
479 if (Encoding == WEM_UTF8) {
480 OS << Contents;
481 } else if (Encoding == WEM_CurrentCodePage) {
482 SmallVector<wchar_t, 1> ArgsUTF16;
483 SmallVector<char, 1> ArgsCurCP;
484
485 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
486 return EC;
487
488 if ((EC = windows::UTF16ToCurCP(
489 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
490 return EC;
491
492 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
493 } else if (Encoding == WEM_UTF16) {
494 SmallVector<wchar_t, 1> ArgsUTF16;
495
496 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
497 return EC;
498
499 // Endianness guessing
500 char BOM[2];
501 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
502 memcpy(BOM, &src, 2);
503 OS.write(BOM, 2);
504 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
505 } else {
506 llvm_unreachable("Unknown encoding");
507 }
508
509 if (OS.has_error())
510 return std::make_error_code(std::errc::io_error);
511
512 return EC;
513}
514
Rafael Espindolacd848c02013-04-11 14:06:34 +0000515bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
516 // The documented max length of the command line passed to CreateProcess.
517 static const size_t MaxCommandStringLength = 32768;
518 size_t ArgLength = 0;
519 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
520 I != E; ++I) {
521 // Account for the trailing space for every arg but the last one and the
522 // trailing NULL of the last argument.
523 ArgLength += ArgLenWithQuotes(*I) + 1;
524 if (ArgLength > MaxCommandStringLength) {
525 return false;
526 }
527 }
528 return true;
529}
Reid Spencerb88212e2004-09-15 05:49:50 +0000530}