1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Program class.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/FileSystem.h"
21 //===----------------------------------------------------------------------===//
22 //=== WARNING: Implementation here must contain only Win32 specific code
23 //=== and must not be UNIX code
24 //===----------------------------------------------------------------------===//
27 struct Win32ProcessInfo {
36 // This function just uses the PATH environment variable to find the program.
37 std::string sys::FindProgramByName(const std::string &progName) {
38 // Check some degenerate cases
39 if (progName.length() == 0) // no program
41 std::string temp = progName;
42 // Return paths with slashes verbatim.
43 if (progName.find('\\') != std::string::npos ||
44 progName.find('/') != std::string::npos)
47 // At this point, the file name is valid and does not contain slashes.
48 // Let Windows search for it.
49 char buffer[MAX_PATH];
51 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
54 // See if it wasn't found.
58 // See if we got the entire path.
60 return std::string(buffer);
62 // Buffer was too small; grow and retry.
64 char *b = reinterpret_cast<char *>(_alloca(len+1));
65 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
67 // It is unlikely the search failed, but it's always possible some file
68 // was added or removed since the last search, so be paranoid...
72 return std::string(b);
78 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
81 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
82 GetCurrentProcess(), &h,
83 0, TRUE, DUPLICATE_SAME_ACCESS);
93 SECURITY_ATTRIBUTES sa;
94 sa.nLength = sizeof(sa);
95 sa.lpSecurityDescriptor = 0;
96 sa.bInheritHandle = TRUE;
98 h = CreateFile(fname.c_str(), fd ? GENERIC_WRITE : GENERIC_READ,
99 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
100 FILE_ATTRIBUTE_NORMAL, NULL);
101 if (h == INVALID_HANDLE_VALUE) {
102 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
103 (fd ? "input: " : "output: "));
109 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
111 static bool ArgNeedsQuotes(const char *Str) {
112 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
115 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
116 /// in the C string Start.
117 static unsigned int CountPrecedingBackslashes(const char *Start,
119 unsigned int Count = 0;
121 while (Cur >= Start && *Cur == '\\') {
128 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
129 /// preceding Cur in the Start string. Assumes Dst has enough space.
130 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
132 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
133 while (PrecedingEscapes > 0) {
140 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
141 /// CreateProcess and returns length of quoted arg with escaped quotes
142 static unsigned int ArgLenWithQuotes(const char *Str) {
143 const char *Start = Str;
144 bool Quoted = ArgNeedsQuotes(Str);
145 unsigned int len = Quoted ? 2 : 0;
147 while (*Str != '\0') {
149 // We need to add a backslash, but ensure that it isn't escaped.
150 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
151 len += PrecedingEscapes + 1;
153 // Note that we *don't* need to escape runs of backslashes that don't
154 // precede a double quote! See MSDN:
155 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
162 // Make sure the closing quote doesn't get escaped by a trailing backslash.
163 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
164 len += PrecedingEscapes + 1;
172 static bool Execute(void **Data,
176 const StringRef** redirects,
177 unsigned memoryLimit,
178 std::string* ErrMsg) {
179 if (!sys::fs::can_execute(Program)) {
181 *ErrMsg = "program not executable";
185 // Windows wants a command line, not an array of args, to pass to the new
186 // process. We have to concatenate them all, while quoting the args that
187 // have embedded spaces (or are empty).
189 // First, determine the length of the command line.
191 for (unsigned i = 0; args[i]; i++) {
192 len += ArgLenWithQuotes(args[i]) + 1;
195 // Now build the command line.
196 char *command = reinterpret_cast<char *>(_alloca(len+1));
199 for (unsigned i = 0; args[i]; i++) {
200 const char *arg = args[i];
201 const char *start = arg;
203 bool needsQuoting = ArgNeedsQuotes(arg);
207 while (*arg != '\0') {
209 // Escape all preceding escapes (if any), and then escape the quote.
210 p = EscapePrecedingEscapes(p, start, arg);
218 // Make sure our quote doesn't get escaped by a trailing backslash.
219 p = EscapePrecedingEscapes(p, start, arg);
227 // The pointer to the environment block for the new process.
231 // An environment block consists of a null-terminated block of
232 // null-terminated strings. Convert the array of environment variables to
233 // an environment block by concatenating them.
235 // First, determine the length of the environment block.
237 for (unsigned i = 0; envp[i]; i++)
238 len += strlen(envp[i]) + 1;
240 // Now build the environment block.
241 envblock = reinterpret_cast<char *>(_alloca(len+1));
244 for (unsigned i = 0; envp[i]; i++) {
245 const char *ev = envp[i];
246 size_t len = strlen(ev) + 1;
254 // Create a child process.
256 memset(&si, 0, sizeof(si));
258 si.hStdInput = INVALID_HANDLE_VALUE;
259 si.hStdOutput = INVALID_HANDLE_VALUE;
260 si.hStdError = INVALID_HANDLE_VALUE;
263 si.dwFlags = STARTF_USESTDHANDLES;
265 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
266 if (si.hStdInput == INVALID_HANDLE_VALUE) {
267 MakeErrMsg(ErrMsg, "can't redirect stdin");
270 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
271 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
272 CloseHandle(si.hStdInput);
273 MakeErrMsg(ErrMsg, "can't redirect stdout");
276 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
277 // If stdout and stderr should go to the same place, redirect stderr
278 // to the handle already open for stdout.
279 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
280 GetCurrentProcess(), &si.hStdError,
281 0, TRUE, DUPLICATE_SAME_ACCESS);
283 // Just redirect stderr
284 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
285 if (si.hStdError == INVALID_HANDLE_VALUE) {
286 CloseHandle(si.hStdInput);
287 CloseHandle(si.hStdOutput);
288 MakeErrMsg(ErrMsg, "can't redirect stderr");
294 PROCESS_INFORMATION pi;
295 memset(&pi, 0, sizeof(pi));
299 std::string ProgramStr = Program;
300 BOOL rc = CreateProcess(ProgramStr.c_str(), command, NULL, NULL, TRUE, 0,
301 envblock, NULL, &si, &pi);
302 DWORD err = GetLastError();
304 // Regardless of whether the process got created or not, we are done with
305 // the handles we created for it to inherit.
306 CloseHandle(si.hStdInput);
307 CloseHandle(si.hStdOutput);
308 CloseHandle(si.hStdError);
310 // Now return an error if the process didn't get created.
313 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
318 Win32ProcessInfo* wpi = new Win32ProcessInfo;
319 wpi->hProcess = pi.hProcess;
320 wpi->dwProcessId = pi.dwProcessId;
324 // Make sure these get closed no matter what.
325 ScopedCommonHandle hThread(pi.hThread);
327 // Assign the process to a job if a memory limit is defined.
328 ScopedJobHandle hJob;
329 if (memoryLimit != 0) {
330 hJob = CreateJobObject(0, 0);
331 bool success = false;
333 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
334 memset(&jeli, 0, sizeof(jeli));
335 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
336 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
337 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
338 &jeli, sizeof(jeli))) {
339 if (AssignProcessToJobObject(hJob, pi.hProcess))
344 SetLastError(GetLastError());
345 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
346 TerminateProcess(pi.hProcess, 1);
347 WaitForSingleObject(pi.hProcess, INFINITE);
352 // Don't leak the handle if the caller doesn't want it.
354 CloseHandle(pi.hProcess);
359 static int WaitAux(Win32ProcessInfo *wpi, unsigned secondsToWait,
360 std::string *ErrMsg) {
361 // Wait for the process to terminate.
362 HANDLE hProcess = wpi->hProcess;
363 DWORD millisecondsToWait = INFINITE;
364 if (secondsToWait > 0)
365 millisecondsToWait = secondsToWait * 1000;
367 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
368 if (!TerminateProcess(hProcess, 1)) {
369 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
370 // -2 indicates a crash or timeout as opposed to failure to execute.
373 WaitForSingleObject(hProcess, INFINITE);
376 // Get its exit status.
378 BOOL rc = GetExitCodeProcess(hProcess, &status);
379 DWORD err = GetLastError();
383 MakeErrMsg(ErrMsg, "Failed getting status for program.");
384 // -2 indicates a crash or timeout as opposed to failure to execute.
391 // Pass 10(Warning) and 11(Error) to the callee as negative value.
392 if ((status & 0xBFFF0000U) == 0x80000000U)
396 return status & 0x7FFFFFFF;
401 static int Wait(void *&Data, StringRef Program, unsigned secondsToWait,
402 std::string *ErrMsg) {
403 Win32ProcessInfo *wpi = reinterpret_cast<Win32ProcessInfo *>(Data);
404 int Ret = WaitAux(wpi, secondsToWait, ErrMsg);
406 CloseHandle(wpi->hProcess);
414 error_code sys::ChangeStdinToBinary(){
415 int result = _setmode( _fileno(stdin), _O_BINARY );
417 return error_code(errno, generic_category());
418 return make_error_code(errc::success);
421 error_code sys::ChangeStdoutToBinary(){
422 int result = _setmode( _fileno(stdout), _O_BINARY );
424 return error_code(errno, generic_category());
425 return make_error_code(errc::success);
428 error_code sys::ChangeStderrToBinary(){
429 int result = _setmode( _fileno(stderr), _O_BINARY );
431 return error_code(errno, generic_category());
432 return make_error_code(errc::success);
435 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
436 // The documented max length of the command line passed to CreateProcess.
437 static const size_t MaxCommandStringLength = 32768;
438 size_t ArgLength = 0;
439 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
441 // Account for the trailing space for every arg but the last one and the
442 // trailing NULL of the last argument.
443 ArgLength += ArgLenWithQuotes(*I) + 1;
444 if (ArgLength > MaxCommandStringLength) {