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 //===----------------------------------------------------------------------===//
20 //===----------------------------------------------------------------------===//
21 //=== WARNING: Implementation here must contain only Win32 specific code
22 //=== and must not be UNIX code
23 //===----------------------------------------------------------------------===//
26 struct Win32ProcessInfo {
35 // This function just uses the PATH environment variable to find the program.
36 Path sys::FindProgramByName(const std::string& progName) {
37 // Check some degenerate cases
38 if (progName.length() == 0) // no program
41 if (!temp.set(progName)) // invalid name
43 // Return paths with slashes verbatim.
44 if (progName.find('\\') != std::string::npos ||
45 progName.find('/') != std::string::npos)
48 // At this point, the file name is valid and does not contain slashes.
49 // Let Windows search for it.
50 char buffer[MAX_PATH];
52 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
55 // See if it wasn't found.
59 // See if we got the entire path.
63 // Buffer was too small; grow and retry.
65 char *b = reinterpret_cast<char *>(_alloca(len+1));
66 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
68 // It is unlikely the search failed, but it's always possible some file
69 // was added or removed since the last search, so be paranoid...
79 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
82 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
83 GetCurrentProcess(), &h,
84 0, TRUE, DUPLICATE_SAME_ACCESS);
92 fname = path->c_str();
94 SECURITY_ATTRIBUTES sa;
95 sa.nLength = sizeof(sa);
96 sa.lpSecurityDescriptor = 0;
97 sa.bInheritHandle = TRUE;
99 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
100 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
101 FILE_ATTRIBUTE_NORMAL, NULL);
102 if (h == INVALID_HANDLE_VALUE) {
103 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
104 (fd ? "input: " : "output: "));
110 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
112 static bool ArgNeedsQuotes(const char *Str) {
113 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
116 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
117 /// in the C string Start.
118 static unsigned int CountPrecedingBackslashes(const char *Start,
120 unsigned int Count = 0;
122 while (Cur >= Start && *Cur == '\\') {
129 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
130 /// preceding Cur in the Start string. Assumes Dst has enough space.
131 static char *EscapePrecedingEscapes(char *Dst, const char *Start,
133 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
134 while (PrecedingEscapes > 0) {
141 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
142 /// CreateProcess and returns length of quoted arg with escaped quotes
143 static unsigned int ArgLenWithQuotes(const char *Str) {
144 const char *Start = Str;
145 bool Quoted = ArgNeedsQuotes(Str);
146 unsigned int len = Quoted ? 2 : 0;
148 while (*Str != '\0') {
150 // We need to add a backslash, but ensure that it isn't escaped.
151 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
152 len += PrecedingEscapes + 1;
154 // Note that we *don't* need to escape runs of backslashes that don't
155 // precede a double quote! See MSDN:
156 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
163 // Make sure the closing quote doesn't get escaped by a trailing backslash.
164 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
165 len += PrecedingEscapes + 1;
173 static bool Execute(void *&Data,
177 const Path** redirects,
178 unsigned memoryLimit,
179 std::string* ErrMsg) {
181 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data);
182 CloseHandle(wpi->hProcess);
187 if (!path.canExecute()) {
189 *ErrMsg = "program not executable";
193 // Windows wants a command line, not an array of args, to pass to the new
194 // process. We have to concatenate them all, while quoting the args that
195 // have embedded spaces (or are empty).
197 // First, determine the length of the command line.
199 for (unsigned i = 0; args[i]; i++) {
200 len += ArgLenWithQuotes(args[i]) + 1;
203 // Now build the command line.
204 char *command = reinterpret_cast<char *>(_alloca(len+1));
207 for (unsigned i = 0; args[i]; i++) {
208 const char *arg = args[i];
209 const char *start = arg;
211 bool needsQuoting = ArgNeedsQuotes(arg);
215 while (*arg != '\0') {
217 // Escape all preceding escapes (if any), and then escape the quote.
218 p = EscapePrecedingEscapes(p, start, arg);
226 // Make sure our quote doesn't get escaped by a trailing backslash.
227 p = EscapePrecedingEscapes(p, start, arg);
235 // The pointer to the environment block for the new process.
239 // An environment block consists of a null-terminated block of
240 // null-terminated strings. Convert the array of environment variables to
241 // an environment block by concatenating them.
243 // First, determine the length of the environment block.
245 for (unsigned i = 0; envp[i]; i++)
246 len += strlen(envp[i]) + 1;
248 // Now build the environment block.
249 envblock = reinterpret_cast<char *>(_alloca(len+1));
252 for (unsigned i = 0; envp[i]; i++) {
253 const char *ev = envp[i];
254 size_t len = strlen(ev) + 1;
262 // Create a child process.
264 memset(&si, 0, sizeof(si));
266 si.hStdInput = INVALID_HANDLE_VALUE;
267 si.hStdOutput = INVALID_HANDLE_VALUE;
268 si.hStdError = INVALID_HANDLE_VALUE;
271 si.dwFlags = STARTF_USESTDHANDLES;
273 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
274 if (si.hStdInput == INVALID_HANDLE_VALUE) {
275 MakeErrMsg(ErrMsg, "can't redirect stdin");
278 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
279 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
280 CloseHandle(si.hStdInput);
281 MakeErrMsg(ErrMsg, "can't redirect stdout");
284 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
285 // If stdout and stderr should go to the same place, redirect stderr
286 // to the handle already open for stdout.
287 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
288 GetCurrentProcess(), &si.hStdError,
289 0, TRUE, DUPLICATE_SAME_ACCESS);
291 // Just redirect stderr
292 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
293 if (si.hStdError == INVALID_HANDLE_VALUE) {
294 CloseHandle(si.hStdInput);
295 CloseHandle(si.hStdOutput);
296 MakeErrMsg(ErrMsg, "can't redirect stderr");
302 PROCESS_INFORMATION pi;
303 memset(&pi, 0, sizeof(pi));
307 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
308 envblock, NULL, &si, &pi);
309 DWORD err = GetLastError();
311 // Regardless of whether the process got created or not, we are done with
312 // the handles we created for it to inherit.
313 CloseHandle(si.hStdInput);
314 CloseHandle(si.hStdOutput);
315 CloseHandle(si.hStdError);
317 // Now return an error if the process didn't get created.
320 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
324 Win32ProcessInfo* wpi = new Win32ProcessInfo;
325 wpi->hProcess = pi.hProcess;
326 wpi->dwProcessId = pi.dwProcessId;
329 // Make sure these get closed no matter what.
330 ScopedCommonHandle hThread(pi.hThread);
332 // Assign the process to a job if a memory limit is defined.
333 ScopedJobHandle hJob;
334 if (memoryLimit != 0) {
335 hJob = CreateJobObject(0, 0);
336 bool success = false;
338 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
339 memset(&jeli, 0, sizeof(jeli));
340 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
341 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
342 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
343 &jeli, sizeof(jeli))) {
344 if (AssignProcessToJobObject(hJob, pi.hProcess))
349 SetLastError(GetLastError());
350 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
351 TerminateProcess(pi.hProcess, 1);
352 WaitForSingleObject(pi.hProcess, INFINITE);
360 static int WaitAux(void *&Data, const Path &path,
361 unsigned secondsToWait,
362 std::string* ErrMsg) {
364 MakeErrMsg(ErrMsg, "Process not started!");
368 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data);
369 HANDLE hProcess = wpi->hProcess;
371 // Wait for the process to terminate.
372 DWORD millisecondsToWait = INFINITE;
373 if (secondsToWait > 0)
374 millisecondsToWait = secondsToWait * 1000;
376 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
377 if (!TerminateProcess(hProcess, 1)) {
378 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
379 // -2 indicates a crash or timeout as opposed to failure to execute.
382 WaitForSingleObject(hProcess, INFINITE);
385 // Get its exit status.
387 BOOL rc = GetExitCodeProcess(hProcess, &status);
388 DWORD err = GetLastError();
392 MakeErrMsg(ErrMsg, "Failed getting status for program.");
393 // -2 indicates a crash or timeout as opposed to failure to execute.
400 // Pass 10(Warning) and 11(Error) to the callee as negative value.
401 if ((status & 0xBFFF0000U) == 0x80000000U)
405 return status & 0x7FFFFFFF;
410 static int Wait(void *&Data, const Path &path,
411 unsigned secondsToWait,
412 std::string* ErrMsg) {
413 int Ret = WaitAux(Data, path, secondsToWait, ErrMsg);
415 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data);
416 CloseHandle(wpi->hProcess);
424 error_code sys::ChangeStdinToBinary(){
425 int result = _setmode( _fileno(stdin), _O_BINARY );
427 return error_code(errno, generic_category());
428 return make_error_code(errc::success);
431 error_code sys::ChangeStdoutToBinary(){
432 int result = _setmode( _fileno(stdout), _O_BINARY );
434 return error_code(errno, generic_category());
435 return make_error_code(errc::success);
438 error_code sys::ChangeStderrToBinary(){
439 int result = _setmode( _fileno(stderr), _O_BINARY );
441 return error_code(errno, generic_category());
442 return make_error_code(errc::success);
445 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
446 // The documented max length of the command line passed to CreateProcess.
447 static const size_t MaxCommandStringLength = 32768;
448 size_t ArgLength = 0;
449 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
451 // Account for the trailing space for every arg but the last one and the
452 // trailing NULL of the last argument.
453 ArgLength += ArgLenWithQuotes(*I) + 1;
454 if (ArgLength > MaxCommandStringLength) {