blob: b2f71aed0c7d8a00b8981653abd234c3e242ebc6 [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 Espindolab0a5c962013-06-14 19:38:45 +000015#include "llvm/Support/FileSystem.h"
Reid Spencerab97f222006-06-07 23:18:34 +000016#include <cstdio>
Reid Spencerab97f222006-06-07 23:18:34 +000017#include <fcntl.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <io.h>
19#include <malloc.h>
Reid Spencerb88212e2004-09-15 05:49:50 +000020
Reid Spencer76b83a12004-08-29 19:20:41 +000021//===----------------------------------------------------------------------===//
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000022//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencerb88212e2004-09-15 05:49:50 +000023//=== and must not be UNIX code
Reid Spencer76b83a12004-08-29 19:20:41 +000024//===----------------------------------------------------------------------===//
25
Reid Spencerb88212e2004-09-15 05:49:50 +000026namespace llvm {
27using namespace sys;
28
Alp Toker153675b2013-10-18 07:09:58 +000029ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
Tareq A. Sirajd88b9832013-10-01 14:28:18 +000030
Reid Spencerb88212e2004-09-15 05:49:50 +000031// This function just uses the PATH environment variable to find the program.
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000032std::string sys::FindProgramByName(const std::string &progName) {
Reid Spencerb88212e2004-09-15 05:49:50 +000033 // Check some degenerate cases
34 if (progName.length() == 0) // no program
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000035 return "";
Rafael Espindolab0a5c962013-06-14 19:38:45 +000036 std::string temp = progName;
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000037 // Return paths with slashes verbatim.
38 if (progName.find('\\') != std::string::npos ||
39 progName.find('/') != std::string::npos)
Rafael Espindolab0a5c962013-06-14 19:38:45 +000040 return temp;
Reid Spencerb88212e2004-09-15 05:49:50 +000041
Mikhail Glushenkova581d8a2010-11-02 20:32:39 +000042 // At this point, the file name is valid and does not contain slashes.
Reid Spencerb88212e2004-09-15 05:49:50 +000043 // Let Windows search for it.
David Majnemer61eae2e2013-10-07 01:00:07 +000044 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
45 if (windows::UTF8ToUTF16(progName, progNameUnicode))
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000046 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000047
David Majnemer61eae2e2013-10-07 01:00:07 +000048 SmallVector<wchar_t, MAX_PATH> buffer;
49 DWORD len = MAX_PATH;
50 do {
51 buffer.reserve(len);
52 len = ::SearchPathW(NULL, progNameUnicode.data(), L".exe",
53 buffer.capacity(), buffer.data(), NULL);
Reid Spencerb88212e2004-09-15 05:49:50 +000054
David Majnemer61eae2e2013-10-07 01:00:07 +000055 // See if it wasn't found.
56 if (len == 0)
Rafael Espindola4c7ad8f2013-06-13 19:25:37 +000057 return "";
Reid Spencerb88212e2004-09-15 05:49:50 +000058
David Majnemer61eae2e2013-10-07 01:00:07 +000059 // Buffer was too small; grow and retry.
60 } while (len > buffer.capacity());
61
62 buffer.set_size(len);
63 SmallVector<char, MAX_PATH> result;
64 if (windows::UTF16ToUTF8(buffer.begin(), buffer.size(), result))
65 return "";
66
67 return std::string(result.data(), result.size());
Reid Spencerb88212e2004-09-15 05:49:50 +000068}
69
Rafael Espindolab0a5c962013-06-14 19:38:45 +000070static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
Jeff Cohen4220bf52005-02-20 02:43:04 +000071 HANDLE h;
72 if (path == 0) {
David Majnemer61eae2e2013-10-07 01:00:07 +000073 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
74 GetCurrentProcess(), &h,
75 0, TRUE, DUPLICATE_SAME_ACCESS))
76 return INVALID_HANDLE_VALUE;
Jeff Cohen4220bf52005-02-20 02:43:04 +000077 return h;
78 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +000079
Rafael Espindolab0a5c962013-06-14 19:38:45 +000080 std::string fname;
81 if (path->empty())
Jeff Cohen4220bf52005-02-20 02:43:04 +000082 fname = "NUL";
Matthijs Kooijman616e4842008-06-12 10:47:18 +000083 else
Rafael Espindolab0a5c962013-06-14 19:38:45 +000084 fname = *path;
Jeff Cohen4220bf52005-02-20 02:43:04 +000085
86 SECURITY_ATTRIBUTES sa;
87 sa.nLength = sizeof(sa);
88 sa.lpSecurityDescriptor = 0;
89 sa.bInheritHandle = TRUE;
90
David Majnemer61eae2e2013-10-07 01:00:07 +000091 SmallVector<wchar_t, 128> fnameUnicode;
92 if (windows::UTF8ToUTF16(fname, fnameUnicode))
93 return INVALID_HANDLE_VALUE;
94
95 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
96 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
97 FILE_ATTRIBUTE_NORMAL, NULL);
Jeff Cohen4220bf52005-02-20 02:43:04 +000098 if (h == INVALID_HANDLE_VALUE) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +000099 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
Jeff Cohen4220bf52005-02-20 02:43:04 +0000100 (fd ? "input: " : "output: "));
101 }
Jeff Cohena531d042007-03-05 05:22:08 +0000102
Jeff Cohen4220bf52005-02-20 02:43:04 +0000103 return h;
104}
105
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000106/// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
107/// CreateProcess.
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000108static bool ArgNeedsQuotes(const char *Str) {
NAKAMURA Takumi3e600a22011-02-05 08:53:12 +0000109 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000110}
111
Reid Kleckner74679a92013-04-22 19:03:55 +0000112/// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
113/// in the C string Start.
114static unsigned int CountPrecedingBackslashes(const char *Start,
115 const char *Cur) {
116 unsigned int Count = 0;
117 --Cur;
118 while (Cur >= Start && *Cur == '\\') {
119 ++Count;
120 --Cur;
121 }
122 return Count;
123}
124
125/// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
126/// preceding Cur in the Start string. Assumes Dst has enough space.
127static char *EscapePrecedingEscapes(char *Dst, const char *Start,
128 const char *Cur) {
129 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
130 while (PrecedingEscapes > 0) {
131 *Dst++ = '\\';
132 --PrecedingEscapes;
133 }
134 return Dst;
135}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000136
137/// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
138/// CreateProcess and returns length of quoted arg with escaped quotes
139static unsigned int ArgLenWithQuotes(const char *Str) {
Reid Kleckner74679a92013-04-22 19:03:55 +0000140 const char *Start = Str;
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000141 bool Quoted = ArgNeedsQuotes(Str);
142 unsigned int len = Quoted ? 2 : 0;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000143
144 while (*Str != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000145 if (*Str == '\"') {
146 // We need to add a backslash, but ensure that it isn't escaped.
147 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
148 len += PrecedingEscapes + 1;
149 }
150 // Note that we *don't* need to escape runs of backslashes that don't
151 // precede a double quote! See MSDN:
152 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000153
154 ++len;
155 ++Str;
156 }
157
Aaron Ballmanfd86e162013-05-01 02:53:14 +0000158 if (Quoted) {
159 // Make sure the closing quote doesn't get escaped by a trailing backslash.
160 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
161 len += PrecedingEscapes + 1;
162 }
163
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000164 return len;
165}
166
Rafael Espindola404ae772013-06-12 21:11:50 +0000167}
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000168
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000169static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
170 const char **envp, const StringRef **redirects,
171 unsigned memoryLimit, std::string *ErrMsg) {
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000172 if (!sys::fs::can_execute(Program)) {
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000173 if (ErrMsg)
174 *ErrMsg = "program not executable";
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000175 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000176 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000177
178 // Windows wants a command line, not an array of args, to pass to the new
179 // process. We have to concatenate them all, while quoting the args that
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000180 // have embedded spaces (or are empty).
Reid Spencerb88212e2004-09-15 05:49:50 +0000181
182 // First, determine the length of the command line.
Jeff Cohen97a41e22005-02-16 04:43:45 +0000183 unsigned len = 0;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000184 for (unsigned i = 0; args[i]; i++) {
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000185 len += ArgLenWithQuotes(args[i]) + 1;
Reid Spencerb88212e2004-09-15 05:49:50 +0000186 }
187
188 // Now build the command line.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000189 std::unique_ptr<char[]> command(new char[len+1]);
Reid Klecknerac20e612013-08-07 01:21:33 +0000190 char *p = command.get();
Reid Spencerb88212e2004-09-15 05:49:50 +0000191
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000192 for (unsigned i = 0; args[i]; i++) {
193 const char *arg = args[i];
Reid Kleckner74679a92013-04-22 19:03:55 +0000194 const char *start = arg;
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000195
Daniel Dunbar381b89d2009-08-02 20:41:09 +0000196 bool needsQuoting = ArgNeedsQuotes(arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000197 if (needsQuoting)
198 *p++ = '"';
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000199
200 while (*arg != '\0') {
Reid Kleckner74679a92013-04-22 19:03:55 +0000201 if (*arg == '\"') {
202 // Escape all preceding escapes (if any), and then escape the quote.
203 p = EscapePrecedingEscapes(p, start, arg);
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000204 *p++ = '\\';
Reid Kleckner74679a92013-04-22 19:03:55 +0000205 }
Anton Korobeynikovc2747d02010-03-28 15:07:02 +0000206
207 *p++ = *arg++;
208 }
209
Reid Kleckner74679a92013-04-22 19:03:55 +0000210 if (needsQuoting) {
211 // Make sure our quote doesn't get escaped by a trailing backslash.
212 p = EscapePrecedingEscapes(p, start, arg);
Reid Spencerb88212e2004-09-15 05:49:50 +0000213 *p++ = '"';
Reid Kleckner74679a92013-04-22 19:03:55 +0000214 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000215 *p++ = ' ';
216 }
217
218 *p = 0;
219
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000220 // The pointer to the environment block for the new process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000221 std::vector<wchar_t> EnvBlock;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000222
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000223 if (envp) {
224 // An environment block consists of a null-terminated block of
225 // null-terminated strings. Convert the array of environment variables to
226 // an environment block by concatenating them.
David Majnemer61eae2e2013-10-07 01:00:07 +0000227 for (unsigned i = 0; envp[i]; ++i) {
228 SmallVector<wchar_t, MAX_PATH> EnvString;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000229 if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000230 SetLastError(ec.value());
231 MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
232 return false;
233 }
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000234
David Majnemer61eae2e2013-10-07 01:00:07 +0000235 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
236 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000237 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000238 EnvBlock.push_back(0);
Argyrios Kyrtzidis24f99982008-06-15 03:54:39 +0000239 }
240
Reid Spencerb88212e2004-09-15 05:49:50 +0000241 // Create a child process.
David Majnemer61eae2e2013-10-07 01:00:07 +0000242 STARTUPINFOW si;
Reid Spencerb88212e2004-09-15 05:49:50 +0000243 memset(&si, 0, sizeof(si));
244 si.cb = sizeof(si);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000245 si.hStdInput = INVALID_HANDLE_VALUE;
246 si.hStdOutput = INVALID_HANDLE_VALUE;
247 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb88212e2004-09-15 05:49:50 +0000248
Jeff Cohen4220bf52005-02-20 02:43:04 +0000249 if (redirects) {
250 si.dwFlags = STARTF_USESTDHANDLES;
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000251
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000252 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
253 if (si.hStdInput == INVALID_HANDLE_VALUE) {
254 MakeErrMsg(ErrMsg, "can't redirect stdin");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000255 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000256 }
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000257 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000258 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000259 CloseHandle(si.hStdInput);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000260 MakeErrMsg(ErrMsg, "can't redirect stdout");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000261 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000262 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000263 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
264 // If stdout and stderr should go to the same place, redirect stderr
265 // to the handle already open for stdout.
David Majnemer61eae2e2013-10-07 01:00:07 +0000266 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
267 GetCurrentProcess(), &si.hStdError,
268 0, TRUE, DUPLICATE_SAME_ACCESS)) {
269 CloseHandle(si.hStdInput);
270 CloseHandle(si.hStdOutput);
271 MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
272 return false;
273 }
Matthijs Kooijman1cc695e2008-06-12 12:53:35 +0000274 } else {
275 // Just redirect stderr
Anton Korobeynikov6c6a70f2006-09-01 20:35:17 +0000276 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000277 if (si.hStdError == INVALID_HANDLE_VALUE) {
278 CloseHandle(si.hStdInput);
279 CloseHandle(si.hStdOutput);
280 MakeErrMsg(ErrMsg, "can't redirect stderr");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000281 return false;
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000282 }
Jeff Cohen4220bf52005-02-20 02:43:04 +0000283 }
284 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000285
Reid Spencerb88212e2004-09-15 05:49:50 +0000286 PROCESS_INFORMATION pi;
287 memset(&pi, 0, sizeof(pi));
288
Jeff Cohen4220bf52005-02-20 02:43:04 +0000289 fflush(stdout);
290 fflush(stderr);
David Majnemer61eae2e2013-10-07 01:00:07 +0000291
292 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000293 if (std::error_code ec = windows::UTF8ToUTF16(Program, ProgramUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000294 SetLastError(ec.value());
295 MakeErrMsg(ErrMsg,
296 std::string("Unable to convert application name to UTF-16"));
297 return false;
298 }
299
300 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000301 if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000302 SetLastError(ec.value());
303 MakeErrMsg(ErrMsg,
304 std::string("Unable to convert command-line to UTF-16"));
305 return false;
306 }
307
308 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
309 TRUE, CREATE_UNICODE_ENVIRONMENT,
310 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
311 &pi);
Jeff Cohen4220bf52005-02-20 02:43:04 +0000312 DWORD err = GetLastError();
313
314 // Regardless of whether the process got created or not, we are done with
315 // the handles we created for it to inherit.
316 CloseHandle(si.hStdInput);
317 CloseHandle(si.hStdOutput);
318 CloseHandle(si.hStdError);
319
Reid Spencer42bcf6e2006-08-21 06:02:44 +0000320 // Now return an error if the process didn't get created.
Chris Lattnerc521f542009-08-23 22:45:37 +0000321 if (!rc) {
Jeff Cohen4220bf52005-02-20 02:43:04 +0000322 SetLastError(err);
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000323 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
David Majnemer61eae2e2013-10-07 01:00:07 +0000324 Program.str() + "'");
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000325 return false;
Reid Spencerb88212e2004-09-15 05:49:50 +0000326 }
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000327
328 PI.Pid = pi.dwProcessId;
329 PI.ProcessHandle = pi.hProcess;
Mikhail Glushenkov4a91b762009-09-08 19:50:27 +0000330
Jeff Cohena531d042007-03-05 05:22:08 +0000331 // Make sure these get closed no matter what.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000332 ScopedCommonHandle hThread(pi.hThread);
Jeff Cohena531d042007-03-05 05:22:08 +0000333
334 // Assign the process to a job if a memory limit is defined.
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000335 ScopedJobHandle hJob;
Jeff Cohena531d042007-03-05 05:22:08 +0000336 if (memoryLimit != 0) {
David Majnemer17a44962013-10-07 09:52:36 +0000337 hJob = CreateJobObjectW(0, 0);
Jeff Cohena531d042007-03-05 05:22:08 +0000338 bool success = false;
Michael J. Spencer513f1b62011-12-12 06:03:33 +0000339 if (hJob) {
Jeff Cohena531d042007-03-05 05:22:08 +0000340 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
341 memset(&jeli, 0, sizeof(jeli));
342 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
Jeff Cohen7157fe32007-03-05 05:45:08 +0000343 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
Jeff Cohena531d042007-03-05 05:22:08 +0000344 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
345 &jeli, sizeof(jeli))) {
346 if (AssignProcessToJobObject(hJob, pi.hProcess))
347 success = true;
348 }
349 }
350 if (!success) {
351 SetLastError(GetLastError());
352 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
353 TerminateProcess(pi.hProcess, 1);
354 WaitForSingleObject(pi.hProcess, INFINITE);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000355 return false;
Jeff Cohena531d042007-03-05 05:22:08 +0000356 }
357 }
358
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000359 return true;
360}
361
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000362namespace llvm {
363ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
364 bool WaitUntilChildTerminates, std::string *ErrMsg) {
365 assert(PI.Pid && "invalid pid to wait on, process not started?");
366 assert(PI.ProcessHandle &&
367 "invalid process handle to wait on, process not started?");
368 DWORD milliSecondsToWait = 0;
369 if (WaitUntilChildTerminates)
370 milliSecondsToWait = INFINITE;
371 else if (SecondsToWait > 0)
372 milliSecondsToWait = SecondsToWait * 1000;
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000373
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000374 ProcessInfo WaitResult = PI;
375 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
376 if (WaitStatus == WAIT_TIMEOUT) {
377 if (SecondsToWait) {
378 if (!TerminateProcess(PI.ProcessHandle, 1)) {
379 if (ErrMsg)
380 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
381
382 // -2 indicates a crash or timeout as opposed to failure to execute.
383 WaitResult.ReturnCode = -2;
384 CloseHandle(PI.ProcessHandle);
385 return WaitResult;
386 }
387 WaitForSingleObject(PI.ProcessHandle, INFINITE);
388 CloseHandle(PI.ProcessHandle);
389 } else {
390 // Non-blocking wait.
391 return ProcessInfo();
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000392 }
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000393 }
Mikhail Glushenkov3a62efb2009-04-14 21:31:14 +0000394
Reid Spencerb88212e2004-09-15 05:49:50 +0000395 // Get its exit status.
396 DWORD status;
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000397 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
Mikhail Glushenkov36cb8322009-07-18 21:43:12 +0000398 DWORD err = GetLastError();
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000399 CloseHandle(PI.ProcessHandle);
Reid Spencerb88212e2004-09-15 05:49:50 +0000400
Jeff Cohen4220bf52005-02-20 02:43:04 +0000401 if (!rc) {
402 SetLastError(err);
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000403 if (ErrMsg)
404 MakeErrMsg(ErrMsg, "Failed getting status for program.");
405
Andrew Trickd5d07642011-05-21 00:56:46 +0000406 // -2 indicates a crash or timeout as opposed to failure to execute.
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000407 WaitResult.ReturnCode = -2;
408 return WaitResult;
Jeff Cohen4220bf52005-02-20 02:43:04 +0000409 }
Reid Spencerb88212e2004-09-15 05:49:50 +0000410
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000411 if (!status)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000412 return WaitResult;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000413
414 // Pass 10(Warning) and 11(Error) to the callee as negative value.
415 if ((status & 0xBFFF0000U) == 0x80000000U)
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000416 WaitResult.ReturnCode = static_cast<int>(status);
417 else if (status & 0xFF)
418 WaitResult.ReturnCode = status & 0x7FFFFFFF;
419 else
420 WaitResult.ReturnCode = 1;
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000421
Tareq A. Sirajd88b9832013-10-01 14:28:18 +0000422 return WaitResult;
Reid Spencerb88212e2004-09-15 05:49:50 +0000423}
424
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000425 std::error_code sys::ChangeStdinToBinary(){
Reid Spencerab97f222006-06-07 23:18:34 +0000426 int result = _setmode( _fileno(stdin), _O_BINARY );
Michael J. Spencera2755f82011-12-13 23:16:49 +0000427 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000428 return std::error_code(errno, std::generic_category());
429 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000430}
431
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000432 std::error_code sys::ChangeStdoutToBinary(){
Reid Spencerab97f222006-06-07 23:18:34 +0000433 int result = _setmode( _fileno(stdout), _O_BINARY );
Michael J. Spencera2755f82011-12-13 23:16:49 +0000434 if (result == -1)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000435 return std::error_code(errno, std::generic_category());
436 return std::error_code();
Reid Spencerab97f222006-06-07 23:18:34 +0000437}
438
Rafael Espindolacd848c02013-04-11 14:06:34 +0000439bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
440 // The documented max length of the command line passed to CreateProcess.
441 static const size_t MaxCommandStringLength = 32768;
442 size_t ArgLength = 0;
443 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
444 I != E; ++I) {
445 // Account for the trailing space for every arg but the last one and the
446 // trailing NULL of the last argument.
447 ArgLength += ArgLenWithQuotes(*I) + 1;
448 if (ArgLength > MaxCommandStringLength) {
449 return false;
450 }
451 }
452 return true;
453}
Reid Spencerb88212e2004-09-15 05:49:50 +0000454}