1 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides the Win32 specific implementation of the Program class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "Windows.h" 15 #include "llvm/ADT/OwningPtr.h" 16 #include "llvm/Support/FileSystem.h" 17 #include <cstdio> 18 #include <fcntl.h> 19 #include <io.h> 20 #include <malloc.h> 21 22 //===----------------------------------------------------------------------===// 23 //=== WARNING: Implementation here must contain only Win32 specific code 24 //=== and must not be UNIX code 25 //===----------------------------------------------------------------------===// 26 27 namespace { 28 struct Win32ProcessInfo { 29 HANDLE hProcess; 30 DWORD dwProcessId; 31 }; 32 } 33 34 namespace llvm { 35 using namespace sys; 36 37 // This function just uses the PATH environment variable to find the program. 38 std::string sys::FindProgramByName(const std::string &progName) { 39 // Check some degenerate cases 40 if (progName.length() == 0) // no program 41 return ""; 42 std::string temp = progName; 43 // Return paths with slashes verbatim. 44 if (progName.find('\\') != std::string::npos || 45 progName.find('/') != std::string::npos) 46 return temp; 47 48 // At this point, the file name is valid and does not contain slashes. 49 // Let Windows search for it. 50 std::string buffer; 51 buffer.resize(MAX_PATH); 52 char *dummy = NULL; 53 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH, 54 &buffer[0], &dummy); 55 56 // See if it wasn't found. 57 if (len == 0) 58 return ""; 59 60 // See if we got the entire path. 61 if (len < MAX_PATH) 62 return buffer; 63 64 // Buffer was too small; grow and retry. 65 while (true) { 66 buffer.resize(len+1); 67 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, &buffer[0], &dummy); 68 69 // It is unlikely the search failed, but it's always possible some file 70 // was added or removed since the last search, so be paranoid... 71 if (len2 == 0) 72 return ""; 73 else if (len2 <= len) 74 return buffer; 75 76 len = len2; 77 } 78 } 79 80 static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) { 81 HANDLE h; 82 if (path == 0) { 83 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd), 84 GetCurrentProcess(), &h, 85 0, TRUE, DUPLICATE_SAME_ACCESS); 86 return h; 87 } 88 89 std::string fname; 90 if (path->empty()) 91 fname = "NUL"; 92 else 93 fname = *path; 94 95 SECURITY_ATTRIBUTES sa; 96 sa.nLength = sizeof(sa); 97 sa.lpSecurityDescriptor = 0; 98 sa.bInheritHandle = TRUE; 99 100 h = CreateFile(fname.c_str(), fd ? GENERIC_WRITE : GENERIC_READ, 101 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS, 102 FILE_ATTRIBUTE_NORMAL, NULL); 103 if (h == INVALID_HANDLE_VALUE) { 104 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " + 105 (fd ? "input: " : "output: ")); 106 } 107 108 return h; 109 } 110 111 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling 112 /// CreateProcess. 113 static bool ArgNeedsQuotes(const char *Str) { 114 return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0; 115 } 116 117 /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur 118 /// in the C string Start. 119 static unsigned int CountPrecedingBackslashes(const char *Start, 120 const char *Cur) { 121 unsigned int Count = 0; 122 --Cur; 123 while (Cur >= Start && *Cur == '\\') { 124 ++Count; 125 --Cur; 126 } 127 return Count; 128 } 129 130 /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash 131 /// preceding Cur in the Start string. Assumes Dst has enough space. 132 static char *EscapePrecedingEscapes(char *Dst, const char *Start, 133 const char *Cur) { 134 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur); 135 while (PrecedingEscapes > 0) { 136 *Dst++ = '\\'; 137 --PrecedingEscapes; 138 } 139 return Dst; 140 } 141 142 /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling 143 /// CreateProcess and returns length of quoted arg with escaped quotes 144 static unsigned int ArgLenWithQuotes(const char *Str) { 145 const char *Start = Str; 146 bool Quoted = ArgNeedsQuotes(Str); 147 unsigned int len = Quoted ? 2 : 0; 148 149 while (*Str != '\0') { 150 if (*Str == '\"') { 151 // We need to add a backslash, but ensure that it isn't escaped. 152 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str); 153 len += PrecedingEscapes + 1; 154 } 155 // Note that we *don't* need to escape runs of backslashes that don't 156 // precede a double quote! See MSDN: 157 // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx 158 159 ++len; 160 ++Str; 161 } 162 163 if (Quoted) { 164 // Make sure the closing quote doesn't get escaped by a trailing backslash. 165 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str); 166 len += PrecedingEscapes + 1; 167 } 168 169 return len; 170 } 171 172 } 173 174 static bool Execute(void **Data, 175 StringRef Program, 176 const char** args, 177 const char** envp, 178 const StringRef** redirects, 179 unsigned memoryLimit, 180 std::string* ErrMsg) { 181 if (!sys::fs::can_execute(Program)) { 182 if (ErrMsg) 183 *ErrMsg = "program not executable"; 184 return false; 185 } 186 187 // Windows wants a command line, not an array of args, to pass to the new 188 // process. We have to concatenate them all, while quoting the args that 189 // have embedded spaces (or are empty). 190 191 // First, determine the length of the command line. 192 unsigned len = 0; 193 for (unsigned i = 0; args[i]; i++) { 194 len += ArgLenWithQuotes(args[i]) + 1; 195 } 196 197 // Now build the command line. 198 OwningArrayPtr<char> command(new char[len+1]); 199 char *p = command.get(); 200 201 for (unsigned i = 0; args[i]; i++) { 202 const char *arg = args[i]; 203 const char *start = arg; 204 205 bool needsQuoting = ArgNeedsQuotes(arg); 206 if (needsQuoting) 207 *p++ = '"'; 208 209 while (*arg != '\0') { 210 if (*arg == '\"') { 211 // Escape all preceding escapes (if any), and then escape the quote. 212 p = EscapePrecedingEscapes(p, start, arg); 213 *p++ = '\\'; 214 } 215 216 *p++ = *arg++; 217 } 218 219 if (needsQuoting) { 220 // Make sure our quote doesn't get escaped by a trailing backslash. 221 p = EscapePrecedingEscapes(p, start, arg); 222 *p++ = '"'; 223 } 224 *p++ = ' '; 225 } 226 227 *p = 0; 228 229 // The pointer to the environment block for the new process. 230 OwningArrayPtr<char> envblock; 231 232 if (envp) { 233 // An environment block consists of a null-terminated block of 234 // null-terminated strings. Convert the array of environment variables to 235 // an environment block by concatenating them. 236 237 // First, determine the length of the environment block. 238 len = 0; 239 for (unsigned i = 0; envp[i]; i++) 240 len += strlen(envp[i]) + 1; 241 242 // Now build the environment block. 243 envblock.reset(new char[len+1]); 244 p = envblock.get(); 245 246 for (unsigned i = 0; envp[i]; i++) { 247 const char *ev = envp[i]; 248 size_t len = strlen(ev) + 1; 249 memcpy(p, ev, len); 250 p += len; 251 } 252 253 *p = 0; 254 } 255 256 // Create a child process. 257 STARTUPINFO si; 258 memset(&si, 0, sizeof(si)); 259 si.cb = sizeof(si); 260 si.hStdInput = INVALID_HANDLE_VALUE; 261 si.hStdOutput = INVALID_HANDLE_VALUE; 262 si.hStdError = INVALID_HANDLE_VALUE; 263 264 if (redirects) { 265 si.dwFlags = STARTF_USESTDHANDLES; 266 267 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg); 268 if (si.hStdInput == INVALID_HANDLE_VALUE) { 269 MakeErrMsg(ErrMsg, "can't redirect stdin"); 270 return false; 271 } 272 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg); 273 if (si.hStdOutput == INVALID_HANDLE_VALUE) { 274 CloseHandle(si.hStdInput); 275 MakeErrMsg(ErrMsg, "can't redirect stdout"); 276 return false; 277 } 278 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) { 279 // If stdout and stderr should go to the same place, redirect stderr 280 // to the handle already open for stdout. 281 DuplicateHandle(GetCurrentProcess(), si.hStdOutput, 282 GetCurrentProcess(), &si.hStdError, 283 0, TRUE, DUPLICATE_SAME_ACCESS); 284 } else { 285 // Just redirect stderr 286 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg); 287 if (si.hStdError == INVALID_HANDLE_VALUE) { 288 CloseHandle(si.hStdInput); 289 CloseHandle(si.hStdOutput); 290 MakeErrMsg(ErrMsg, "can't redirect stderr"); 291 return false; 292 } 293 } 294 } 295 296 PROCESS_INFORMATION pi; 297 memset(&pi, 0, sizeof(pi)); 298 299 fflush(stdout); 300 fflush(stderr); 301 std::string ProgramStr = Program; 302 BOOL rc = CreateProcess(ProgramStr.c_str(), command.get(), NULL, NULL, TRUE, 303 0, envblock.get(), NULL, &si, &pi); 304 DWORD err = GetLastError(); 305 306 // Regardless of whether the process got created or not, we are done with 307 // the handles we created for it to inherit. 308 CloseHandle(si.hStdInput); 309 CloseHandle(si.hStdOutput); 310 CloseHandle(si.hStdError); 311 312 // Now return an error if the process didn't get created. 313 if (!rc) { 314 SetLastError(err); 315 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") + 316 ProgramStr + "'"); 317 return false; 318 } 319 if (Data) { 320 Win32ProcessInfo* wpi = new Win32ProcessInfo; 321 wpi->hProcess = pi.hProcess; 322 wpi->dwProcessId = pi.dwProcessId; 323 *Data = wpi; 324 } 325 326 // Make sure these get closed no matter what. 327 ScopedCommonHandle hThread(pi.hThread); 328 329 // Assign the process to a job if a memory limit is defined. 330 ScopedJobHandle hJob; 331 if (memoryLimit != 0) { 332 hJob = CreateJobObject(0, 0); 333 bool success = false; 334 if (hJob) { 335 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; 336 memset(&jeli, 0, sizeof(jeli)); 337 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY; 338 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576; 339 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, 340 &jeli, sizeof(jeli))) { 341 if (AssignProcessToJobObject(hJob, pi.hProcess)) 342 success = true; 343 } 344 } 345 if (!success) { 346 SetLastError(GetLastError()); 347 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit")); 348 TerminateProcess(pi.hProcess, 1); 349 WaitForSingleObject(pi.hProcess, INFINITE); 350 return false; 351 } 352 } 353 354 // Don't leak the handle if the caller doesn't want it. 355 if (!Data) 356 CloseHandle(pi.hProcess); 357 358 return true; 359 } 360 361 static int WaitAux(Win32ProcessInfo *wpi, unsigned secondsToWait, 362 std::string *ErrMsg) { 363 // Wait for the process to terminate. 364 HANDLE hProcess = wpi->hProcess; 365 DWORD millisecondsToWait = INFINITE; 366 if (secondsToWait > 0) 367 millisecondsToWait = secondsToWait * 1000; 368 369 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) { 370 if (!TerminateProcess(hProcess, 1)) { 371 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program."); 372 // -2 indicates a crash or timeout as opposed to failure to execute. 373 return -2; 374 } 375 WaitForSingleObject(hProcess, INFINITE); 376 } 377 378 // Get its exit status. 379 DWORD status; 380 BOOL rc = GetExitCodeProcess(hProcess, &status); 381 DWORD err = GetLastError(); 382 383 if (!rc) { 384 SetLastError(err); 385 MakeErrMsg(ErrMsg, "Failed getting status for program."); 386 // -2 indicates a crash or timeout as opposed to failure to execute. 387 return -2; 388 } 389 390 if (!status) 391 return 0; 392 393 // Pass 10(Warning) and 11(Error) to the callee as negative value. 394 if ((status & 0xBFFF0000U) == 0x80000000U) 395 return (int)status; 396 397 if (status & 0xFF) 398 return status & 0x7FFFFFFF; 399 400 return 1; 401 } 402 403 static int Wait(void *&Data, StringRef Program, unsigned secondsToWait, 404 std::string *ErrMsg) { 405 Win32ProcessInfo *wpi = reinterpret_cast<Win32ProcessInfo *>(Data); 406 int Ret = WaitAux(wpi, secondsToWait, ErrMsg); 407 408 CloseHandle(wpi->hProcess); 409 delete wpi; 410 Data = 0; 411 412 return Ret; 413 } 414 415 namespace llvm { 416 error_code sys::ChangeStdinToBinary(){ 417 int result = _setmode( _fileno(stdin), _O_BINARY ); 418 if (result == -1) 419 return error_code(errno, generic_category()); 420 return make_error_code(errc::success); 421 } 422 423 error_code sys::ChangeStdoutToBinary(){ 424 int result = _setmode( _fileno(stdout), _O_BINARY ); 425 if (result == -1) 426 return error_code(errno, generic_category()); 427 return make_error_code(errc::success); 428 } 429 430 error_code sys::ChangeStderrToBinary(){ 431 int result = _setmode( _fileno(stderr), _O_BINARY ); 432 if (result == -1) 433 return error_code(errno, generic_category()); 434 return make_error_code(errc::success); 435 } 436 437 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) { 438 // The documented max length of the command line passed to CreateProcess. 439 static const size_t MaxCommandStringLength = 32768; 440 size_t ArgLength = 0; 441 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end(); 442 I != E; ++I) { 443 // Account for the trailing space for every arg but the last one and the 444 // trailing NULL of the last argument. 445 ArgLength += ArgLenWithQuotes(*I) + 1; 446 if (ArgLength > MaxCommandStringLength) { 447 return false; 448 } 449 } 450 return true; 451 } 452 453 } 454