LLVM API Documentation
00001 //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file provides the Win32 specific implementation of the Program class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "Win32.h" 00015 #include <cstdio> 00016 #include <malloc.h> 00017 #include <io.h> 00018 #include <fcntl.h> 00019 00020 //===----------------------------------------------------------------------===// 00021 //=== WARNING: Implementation here must contain only Win32 specific code 00022 //=== and must not be UNIX code 00023 //===----------------------------------------------------------------------===// 00024 00025 namespace llvm { 00026 using namespace sys; 00027 00028 Program::Program() : Pid_(0), Data(0) {} 00029 00030 Program::~Program() { 00031 if (Data) { 00032 HANDLE hProcess = (HANDLE) Data; 00033 CloseHandle(hProcess); 00034 Data = 0; 00035 } 00036 } 00037 00038 // This function just uses the PATH environment variable to find the program. 00039 Path 00040 Program::FindProgramByName(const std::string& progName) { 00041 00042 // Check some degenerate cases 00043 if (progName.length() == 0) // no program 00044 return Path(); 00045 Path temp; 00046 if (!temp.set(progName)) // invalid name 00047 return Path(); 00048 if (temp.canExecute()) // already executable as is 00049 return temp; 00050 00051 // At this point, the file name is valid and its not executable. 00052 // Let Windows search for it. 00053 char buffer[MAX_PATH]; 00054 char *dummy = NULL; 00055 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH, 00056 buffer, &dummy); 00057 00058 // See if it wasn't found. 00059 if (len == 0) 00060 return Path(); 00061 00062 // See if we got the entire path. 00063 if (len < MAX_PATH) 00064 return Path(buffer); 00065 00066 // Buffer was too small; grow and retry. 00067 while (true) { 00068 char *b = reinterpret_cast<char *>(_alloca(len+1)); 00069 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy); 00070 00071 // It is unlikely the search failed, but it's always possible some file 00072 // was added or removed since the last search, so be paranoid... 00073 if (len2 == 0) 00074 return Path(); 00075 else if (len2 <= len) 00076 return Path(b); 00077 00078 len = len2; 00079 } 00080 } 00081 00082 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) { 00083 HANDLE h; 00084 if (path == 0) { 00085 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd), 00086 GetCurrentProcess(), &h, 00087 0, TRUE, DUPLICATE_SAME_ACCESS); 00088 return h; 00089 } 00090 00091 const char *fname; 00092 if (path->isEmpty()) 00093 fname = "NUL"; 00094 else 00095 fname = path->toString().c_str(); 00096 00097 SECURITY_ATTRIBUTES sa; 00098 sa.nLength = sizeof(sa); 00099 sa.lpSecurityDescriptor = 0; 00100 sa.bInheritHandle = TRUE; 00101 00102 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ, 00103 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS, 00104 FILE_ATTRIBUTE_NORMAL, NULL); 00105 if (h == INVALID_HANDLE_VALUE) { 00106 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " + 00107 (fd ? "input: " : "output: ")); 00108 } 00109 00110 return h; 00111 } 00112 00113 #ifdef __MINGW32__ 00114 // Due to unknown reason, mingw32's w32api doesn't have this declaration. 00115 extern "C" 00116 BOOL WINAPI SetInformationJobObject(HANDLE hJob, 00117 JOBOBJECTINFOCLASS JobObjectInfoClass, 00118 LPVOID lpJobObjectInfo, 00119 DWORD cbJobObjectInfoLength); 00120 #endif 00121 00122 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling 00123 /// CreateProcess. 00124 static bool ArgNeedsQuotes(const char *Str) { 00125 return Str[0] == '\0' || strchr(Str, ' ') != 0; 00126 } 00127 00128 bool 00129 Program::Execute(const Path& path, 00130 const char** args, 00131 const char** envp, 00132 const Path** redirects, 00133 unsigned memoryLimit, 00134 std::string* ErrMsg) { 00135 if (Data) { 00136 HANDLE hProcess = (HANDLE) Data; 00137 CloseHandle(Data); 00138 Data = 0; 00139 } 00140 00141 if (!path.canExecute()) { 00142 if (ErrMsg) 00143 *ErrMsg = "program not executable"; 00144 return false; 00145 } 00146 00147 // Windows wants a command line, not an array of args, to pass to the new 00148 // process. We have to concatenate them all, while quoting the args that 00149 // have embedded spaces (or are empty). 00150 00151 // First, determine the length of the command line. 00152 unsigned len = 0; 00153 for (unsigned i = 0; args[i]; i++) { 00154 len += strlen(args[i]) + 1; 00155 if (ArgNeedsQuotes(args[i])) 00156 len += 2; 00157 } 00158 00159 // Now build the command line. 00160 char *command = reinterpret_cast<char *>(_alloca(len+1)); 00161 char *p = command; 00162 00163 for (unsigned i = 0; args[i]; i++) { 00164 const char *arg = args[i]; 00165 size_t len = strlen(arg); 00166 bool needsQuoting = ArgNeedsQuotes(arg); 00167 if (needsQuoting) 00168 *p++ = '"'; 00169 memcpy(p, arg, len); 00170 p += len; 00171 if (needsQuoting) 00172 *p++ = '"'; 00173 *p++ = ' '; 00174 } 00175 00176 *p = 0; 00177 00178 // The pointer to the environment block for the new process. 00179 char *envblock = 0; 00180 00181 if (envp) { 00182 // An environment block consists of a null-terminated block of 00183 // null-terminated strings. Convert the array of environment variables to 00184 // an environment block by concatenating them. 00185 00186 // First, determine the length of the environment block. 00187 len = 0; 00188 for (unsigned i = 0; envp[i]; i++) 00189 len += strlen(envp[i]) + 1; 00190 00191 // Now build the environment block. 00192 envblock = reinterpret_cast<char *>(_alloca(len+1)); 00193 p = envblock; 00194 00195 for (unsigned i = 0; envp[i]; i++) { 00196 const char *ev = envp[i]; 00197 size_t len = strlen(ev) + 1; 00198 memcpy(p, ev, len); 00199 p += len; 00200 } 00201 00202 *p = 0; 00203 } 00204 00205 // Create a child process. 00206 STARTUPINFO si; 00207 memset(&si, 0, sizeof(si)); 00208 si.cb = sizeof(si); 00209 si.hStdInput = INVALID_HANDLE_VALUE; 00210 si.hStdOutput = INVALID_HANDLE_VALUE; 00211 si.hStdError = INVALID_HANDLE_VALUE; 00212 00213 if (redirects) { 00214 si.dwFlags = STARTF_USESTDHANDLES; 00215 00216 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg); 00217 if (si.hStdInput == INVALID_HANDLE_VALUE) { 00218 MakeErrMsg(ErrMsg, "can't redirect stdin"); 00219 return false; 00220 } 00221 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg); 00222 if (si.hStdOutput == INVALID_HANDLE_VALUE) { 00223 CloseHandle(si.hStdInput); 00224 MakeErrMsg(ErrMsg, "can't redirect stdout"); 00225 return false; 00226 } 00227 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) { 00228 // If stdout and stderr should go to the same place, redirect stderr 00229 // to the handle already open for stdout. 00230 DuplicateHandle(GetCurrentProcess(), si.hStdOutput, 00231 GetCurrentProcess(), &si.hStdError, 00232 0, TRUE, DUPLICATE_SAME_ACCESS); 00233 } else { 00234 // Just redirect stderr 00235 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg); 00236 if (si.hStdError == INVALID_HANDLE_VALUE) { 00237 CloseHandle(si.hStdInput); 00238 CloseHandle(si.hStdOutput); 00239 MakeErrMsg(ErrMsg, "can't redirect stderr"); 00240 return false; 00241 } 00242 } 00243 } 00244 00245 PROCESS_INFORMATION pi; 00246 memset(&pi, 0, sizeof(pi)); 00247 00248 fflush(stdout); 00249 fflush(stderr); 00250 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0, 00251 envblock, NULL, &si, &pi); 00252 DWORD err = GetLastError(); 00253 00254 // Regardless of whether the process got created or not, we are done with 00255 // the handles we created for it to inherit. 00256 CloseHandle(si.hStdInput); 00257 CloseHandle(si.hStdOutput); 00258 CloseHandle(si.hStdError); 00259 00260 // Now return an error if the process didn't get created. 00261 if (!rc) 00262 { 00263 SetLastError(err); 00264 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") + 00265 path.toString() + "'"); 00266 return false; 00267 } 00268 Pid_ = pi.dwProcessId; 00269 Data = pi.hProcess; 00270 00271 // Make sure these get closed no matter what. 00272 AutoHandle hThread(pi.hThread); 00273 00274 // Assign the process to a job if a memory limit is defined. 00275 AutoHandle hJob(0); 00276 if (memoryLimit != 0) { 00277 hJob = CreateJobObject(0, 0); 00278 bool success = false; 00279 if (hJob != 0) { 00280 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli; 00281 memset(&jeli, 0, sizeof(jeli)); 00282 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY; 00283 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576; 00284 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, 00285 &jeli, sizeof(jeli))) { 00286 if (AssignProcessToJobObject(hJob, pi.hProcess)) 00287 success = true; 00288 } 00289 } 00290 if (!success) { 00291 SetLastError(GetLastError()); 00292 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit")); 00293 TerminateProcess(pi.hProcess, 1); 00294 WaitForSingleObject(pi.hProcess, INFINITE); 00295 return false; 00296 } 00297 } 00298 00299 return true; 00300 } 00301 00302 int 00303 Program::Wait(unsigned secondsToWait, 00304 std::string* ErrMsg) { 00305 if (Data == 0) { 00306 MakeErrMsg(ErrMsg, "Process not started!"); 00307 return -1; 00308 } 00309 00310 HANDLE hProcess = (HANDLE) Data; 00311 00312 // Wait for the process to terminate. 00313 DWORD millisecondsToWait = INFINITE; 00314 if (secondsToWait > 0) 00315 millisecondsToWait = secondsToWait * 1000; 00316 00317 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) { 00318 if (!TerminateProcess(hProcess, 1)) { 00319 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program."); 00320 return -1; 00321 } 00322 WaitForSingleObject(hProcess, INFINITE); 00323 } 00324 00325 // Get its exit status. 00326 DWORD status; 00327 BOOL rc = GetExitCodeProcess(hProcess, &status); 00328 DWORD err = GetLastError(); 00329 00330 if (!rc) { 00331 SetLastError(err); 00332 MakeErrMsg(ErrMsg, "Failed getting status for program."); 00333 return -1; 00334 } 00335 00336 return status; 00337 } 00338 00339 bool Program::ChangeStdinToBinary(){ 00340 int result = _setmode( _fileno(stdin), _O_BINARY ); 00341 return result == -1; 00342 } 00343 00344 bool Program::ChangeStdoutToBinary(){ 00345 int result = _setmode( _fileno(stdout), _O_BINARY ); 00346 return result == -1; 00347 } 00348 00349 }