blob: 995c9fedb96a8f77d3742acb104e713d27046041 [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"
Rafael Espindola9c359662014-09-03 20:02:00 +000015#include "llvm/Support/ConvertUTF.h"
Rafael Espindolab0a5c962013-06-14 19:38:45 +000016#include "llvm/Support/FileSystem.h"
Rafael Espindola9c359662014-09-03 20:02:00 +000017#include "llvm/Support/raw_ostream.h"
Reid Spencerab97f222006-06-07 23:18:34 +000018#include <cstdio>
Reid Spencerab97f222006-06-07 23:18:34 +000019#include <fcntl.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include <io.h>
21#include <malloc.h>
Reid Spencerb88212e2004-09-15 05:49:50 +000022
Reid Spencer76b83a12004-08-29 19:20:41 +000023//===----------------------------------------------------------------------===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000024//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb88212e2004-09-15 05:49:50 +000025//=== and must not be UNIX code
Reid Spencer76b83a12004-08-29 19:20:41 +000026//===----------------------------------------------------------------------===//
27
Reid Spencerb88212e2004-09-15 05:49:50 +000028namespace llvm {
29using namespace sys;
30
Alp Toker153675b2013-10-18 07:09:58 +000031ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
Tareq A. Sirajd88b9832013-10-01 14:28:18 +000032
Reid Spencerb88212e2004-09-15 05:49:50 +000033// This function just uses the PATH environment variable to find the program.
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000034std::string sys::FindProgramByName(const std::string &progName) {
Reid Spencerb88212e2004-09-15 05:49:50 +000035 // Check some degenerate cases
36 if (progName.length() == 0) // no program
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000037 return "";
Rafael Espindolab0a5c962013-06-14 19:38:45 +000038 std::string temp = progName;
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000039 // Return paths with slashes verbatim.
40 if (progName.find('\\') != std::string::npos ||
41 progName.find('/') != std::string::npos)
Rafael Espindolab0a5c962013-06-14 19:38:45 +000042 return temp;
Reid Spencerb88212e2004-09-15 05:49:50 +000043
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000044 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb88212e2004-09-15 05:49:50 +000045 // Let Windows search for it.
David Majnemer61eae2e2013-10-07 01:00:07 +000046 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
47 if (windows::UTF8ToUTF16(progName, progNameUnicode))
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000048 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000049
David Majnemer61eae2e2013-10-07 01:00:07 +000050 SmallVector<wchar_t, MAX_PATH> buffer;
51 DWORD len = MAX_PATH;
52 do {
53 buffer.reserve(len);
54 len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
55 buffer.capacity(), buffer.data(), NULL);
Reid Spencerb88212e2004-09-15 05:49:50 +000056
David Majnemer61eae2e2013-10-07 01:00:07 +000057 // See if it wasn't found.
58 if (len == 0)
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000059 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000060
David Majnemer61eae2e2013-10-07 01:00:07 +000061 // Buffer was too small; grow and retry.
62 } while (len > buffer.capacity());
63
64 buffer.set_size(len);
65 SmallVector<char, MAX_PATH> result;
66 if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
67 return "";
68
69 return std::string(result.data(), result.size());
Reid Spencerb88212e2004-09-15 05:49:50 +000070}
71
Rafael Espindolab0a5c962013-06-14 19:38:45 +000072static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +000073 HANDLE h;
74 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +000075 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
76 GetCurrentProcess(), &h,
77 0, TRUE, DUPLICATE_SAME_ACCESS))
78 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +000079 return h;
80 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000081
Rafael Espindolab0a5c962013-06-14 19:38:45 +000082 std::string fname;
83 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +000084 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +000085 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +000086 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +000087
88 SECURITY_ATTRIBUTES sa;
89 sa.nLength = sizeof(sa);
90 sa.lpSecurityDescriptor = 0;
91 sa.bInheritHandle = TRUE;
92
David Majnemer61eae2e2013-10-07 01:00:07 +000093 SmallVector<wchar_t, 128> fnameUnicode;
94 if (windows::UTF8ToUTF16(fname, fnameUnicode))
95 return INVALID_HANDLE_VALUE;
96
97 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
98 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
99 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000100 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000101 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000102 (fd ? "input: " : "output: "));
103 }
Jeff Cohena531d042007-03-05 05:22:08 +0000104
Jeff Cohen4220bf52005-02-20 02:43:04 +0000105 return h;
106}
107
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000108/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
109/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000110static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000111 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000112}
113
Reid Kleckner74679a92013-04-22 19:03:55 +0000114/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
115/// in the C string Start.
116static unsigned int CountPrecedingBackslashes(const char *Start,
117 const char *Cur) {
118 unsigned int Count = 0;
119 --Cur;
120 while (Cur >= Start && *Cur == '\\') {
121 ++Count;
122 --Cur;
123 }
124 return Count;
125}
126
127/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
128/// preceding Cur in the Start string. Assumes Dst has enough space.
129static char *EscapePrecedingEscapes(char *Dst, const char *Start,
130 const char *Cur) {
131 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
132 while (PrecedingEscapes > 0) {
133 *Dst++ = '\\';
134 --PrecedingEscapes;
135 }
136 return Dst;
137}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000138
139/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
140/// CreateProcess and returns length of quoted arg with escaped quotes
141static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000142 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000143 bool Quoted = ArgNeedsQuotes(Str);
144 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000145
146 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000147 if (*Str == '\"') {
148 // We need to add a backslash, but ensure that it isn't escaped.
149 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
150 len += PrecedingEscapes + 1;
151 }
152 // Note that we *don't* need to escape runs of backslashes that don't
153 // precede a double quote! See MSDN:
154 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000155
156 ++len;
157 ++Str;
158 }
159
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000160 if (Quoted) {
161 // Make sure the closing quote doesn't get escaped by a trailing backslash.
162 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
163 len += PrecedingEscapes + 1;
164 }
165
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000166 return len;
167}
168
Rafael Espindola404ae772013-06-12 21:11:50 +0000169}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000170
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000171static std::unique_ptr<char[]> flattenArgs(const char **args) {
Reid Spencerb88212e2004-09-15 05:49:50 +0000172 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000173 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000174 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000175 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000176 }
177
178 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000179 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000180 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000181
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000182 for (unsigned i = 0; args[i]; i++) {
183 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000184 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000185
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000186 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000187 if (needsQuoting)
188 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000189
190 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000191 if (*arg == '\"') {
192 // Escape all preceding escapes (if any), and then escape the quote.
193 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000194 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000195 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000196
197 *p++ = *arg++;
198 }
199
Reid Kleckner74679a92013-04-22 19:03:55 +0000200 if (needsQuoting) {
201 // Make sure our quote doesn't get escaped by a trailing backslash.
202 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000203 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000204 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000205 *p++ = ' ';
206 }
207
208 *p = 0;
Rafael Espindolaf7c3a1d2014-08-25 22:15:06 +0000209 return command;
210}
211
212static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
213 const char **envp, const StringRef **redirects,
214 unsigned memoryLimit, std::string *ErrMsg) {
215 if (!sys::fs::can_execute(Program)) {
216 if (ErrMsg)
217 *ErrMsg = "program not executable";
218 return false;
219 }
220
221 // Windows wants a command line, not an array of args, to pass to the new
222 // process. We have to concatenate them all, while quoting the args that
223 // have embedded spaces (or are empty).
224 std::unique_ptr<char[]> command = flattenArgs(args);
Reid Spencerb88212e2004-09-15 05:49:50 +0000225
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000226 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000227 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000228
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000229 if (envp) {
230 // An environment block consists of a null-terminated block of
231 // null-terminated strings. Convert the array of environment variables to
232 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000233 for (unsigned i = 0; envp[i]; ++i) {
234 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000235 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000236 SetLastError(ec.value());
237 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
238 return false;
239 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000240
David Majnemer61eae2e2013-10-07 01:00:07 +0000241 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
242 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000243 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000244 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000245 }
246
Reid Spencerb88212e2004-09-15 05:49:50 +0000247 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000248 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000249 memset(&si, 0, sizeof(si));
250 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000251 si.hStdInput = INVALID_HANDLE_VALUE;
252 si.hStdOutput = INVALID_HANDLE_VALUE;
253 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000254
Jeff Cohen4220bf52005-02-20 02:43:04 +0000255 if (redirects) {
256 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000257
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000258 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
259 if (si.hStdInput == INVALID_HANDLE_VALUE) {
260 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000261 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000262 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000263 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000264 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000265 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000266 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000267 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000268 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000269 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
270 // If stdout and stderr should go to the same place, redirect stderr
271 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000272 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
273 GetCurrentProcess(), &si.hStdError,
274 0, TRUE, DUPLICATE_SAME_ACCESS)) {
275 CloseHandle(si.hStdInput);
276 CloseHandle(si.hStdOutput);
277 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
278 return false;
279 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000280 } else {
281 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000282 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000283 if (si.hStdError == INVALID_HANDLE_VALUE) {
284 CloseHandle(si.hStdInput);
285 CloseHandle(si.hStdOutput);
286 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000287 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000288 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000289 }
290 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000291
Reid Spencerb88212e2004-09-15 05:49:50 +0000292 PROCESS_INFORMATION pi;
293 memset(&pi, 0, sizeof(pi));
294
Jeff Cohen4220bf52005-02-20 02:43:04 +0000295 fflush(stdout);
296 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000297
298 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000299 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000300 SetLastError(ec.value());
301 MakeErrMsg(ErrMsg,
302 std::string("Unable to convert application name to UTF-16"));
303 return false;
304 }
305
306 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000307 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000308 SetLastError(ec.value());
309 MakeErrMsg(ErrMsg,
310 std::string("Unable to convert command-line to UTF-16"));
311 return false;
312 }
313
314 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
315 TRUE, CREATE_UNICODE_ENVIRONMENT,
316 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
317 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000318 DWORD err = GetLastError();
319
320 // Regardless of whether the process got created or not, we are done with
321 // the handles we created for it to inherit.
322 CloseHandle(si.hStdInput);
323 CloseHandle(si.hStdOutput);
324 CloseHandle(si.hStdError);
325
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000326 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000327 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000328 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000329 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000330 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000331 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000332 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000333
334 PI.Pid = pi.dwProcessId;
335 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000336
Jeff Cohena531d042007-03-05 05:22:08 +0000337 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000338 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000339
340 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000341 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000342 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000343 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000344 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000345 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000346 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
347 memset(&jeli, 0, sizeof(jeli));
348 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000349 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000350 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
351 &jeli, sizeof(jeli))) {
352 if (AssignProcessToJobObject(hJob, pi.hProcess))
353 success = true;
354 }
355 }
356 if (!success) {
357 SetLastError(GetLastError());
358 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
359 TerminateProcess(pi.hProcess, 1);
360 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000361 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000362 }
363 }
364
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000365 return true;
366}
367
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000368namespace llvm {
369ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
370 bool WaitUntilChildTerminates, std::string *ErrMsg) {
371 assert(PI.Pid && "invalid pid to wait on, process not started?");
372 assert(PI.ProcessHandle &&
373 "invalid process handle to wait on, process not started?");
374 DWORD milliSecondsToWait = 0;
375 if (WaitUntilChildTerminates)
376 milliSecondsToWait = INFINITE;
377 else if (SecondsToWait > 0)
378 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000379
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000380 ProcessInfo WaitResult = PI;
381 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
382 if (WaitStatus == WAIT_TIMEOUT) {
383 if (SecondsToWait) {
384 if (!TerminateProcess(PI.ProcessHandle, 1)) {
385 if (ErrMsg)
386 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
387
388 // -2 indicates a crash or timeout as opposed to failure to execute.
389 WaitResult.ReturnCode = -2;
390 CloseHandle(PI.ProcessHandle);
391 return WaitResult;
392 }
393 WaitForSingleObject(PI.ProcessHandle, INFINITE);
394 CloseHandle(PI.ProcessHandle);
395 } else {
396 // Non-blocking wait.
397 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000398 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000399 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000400
Reid Spencerb88212e2004-09-15 05:49:50 +0000401 // Get its exit status.
402 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000403 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000404 DWORD err = GetLastError();
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000405 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000406
Jeff Cohen4220bf52005-02-20 02:43:04 +0000407 if (!rc) {
408 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000409 if (ErrMsg)
410 MakeErrMsg(ErrMsg, "Failed getting status for program.");
411
Andrew Trickd5d07642011-05-21 00:56:46 +0000412 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000413 WaitResult.ReturnCode = -2;
414 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000415 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000416
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000417 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000418 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000419
420 // Pass 10(Warning) and 11(Error) to the callee as negative value.
421 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000422 WaitResult.ReturnCode = static_cast<int>(status);
423 else if (status & 0xFF)
424 WaitResult.ReturnCode = status & 0x7FFFFFFF;
425 else
426 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000427
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000428 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000429}
430
Yaron Kerenabce3c42014-09-26 22:27:11 +0000431std::error_code sys::ChangeStdinToBinary() {
432 int result = _setmode(_fileno(stdin), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000433 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000434 return std::error_code(errno, std::generic_category());
435 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000436}
437
Yaron Kerenabce3c42014-09-26 22:27:11 +0000438std::error_code sys::ChangeStdoutToBinary() {
439 int result = _setmode(_fileno(stdout), _O_BINARY);
Michael J. Spencera2755f82011-12-13 23:16:49 +0000440 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000441 return std::error_code(errno, std::generic_category());
442 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000443}
444
Rafael Espindola9c359662014-09-03 20:02:00 +0000445std::error_code
446llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
447 WindowsEncodingMethod Encoding) {
448 std::error_code EC;
449 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
450 if (EC)
451 return EC;
452
453 if (Encoding == WEM_UTF8) {
454 OS << Contents;
455 } else if (Encoding == WEM_CurrentCodePage) {
456 SmallVector<wchar_t, 1> ArgsUTF16;
457 SmallVector<char, 1> ArgsCurCP;
458
459 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
460 return EC;
461
462 if ((EC = windows::UTF16ToCurCP(
463 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
464 return EC;
465
466 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
467 } else if (Encoding == WEM_UTF16) {
468 SmallVector<wchar_t, 1> ArgsUTF16;
469
470 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
471 return EC;
472
473 // Endianness guessing
474 char BOM[2];
475 uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
476 memcpy(BOM, &src, 2);
477 OS.write(BOM, 2);
478 OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
479 } else {
480 llvm_unreachable("Unknown encoding");
481 }
482
483 if (OS.has_error())
484 return std::make_error_code(std::errc::io_error);
485
486 return EC;
487}
488
Rafael Espindolacd848c02013-04-11 14:06:34 +0000489bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
490 // The documented max length of the command line passed to CreateProcess.
491 static const size_t MaxCommandStringLength = 32768;
492 size_t ArgLength = 0;
493 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
494 I != E; ++I) {
495 // Account for the trailing space for every arg but the last one and the
496 // trailing NULL of the last argument.
497 ArgLength += ArgLenWithQuotes(*I) + 1;
498 if (ArgLength > MaxCommandStringLength) {
499 return false;
500 }
501 }
502 return true;
503}
Reid Spencerb88212e2004-09-15 05:49:50 +0000504}