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 Program::Program() : Data_(0) {}
39 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
40 CloseHandle(wpi->hProcess);
46 unsigned Program::GetPid() const {
47 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
48 return wpi->dwProcessId;
51 // This function just uses the PATH environment variable to find the program.
53 Program::FindProgramByName(const std::string& progName) {
55 // Check some degenerate cases
56 if (progName.length() == 0) // no program
59 if (!temp.set(progName)) // invalid name
61 if (temp.canExecute()) // already executable as is
64 // At this point, the file name is valid and its not executable.
65 // Let Windows search for it.
66 char buffer[MAX_PATH];
68 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
71 // See if it wasn't found.
75 // See if we got the entire path.
79 // Buffer was too small; grow and retry.
81 char *b = reinterpret_cast<char *>(_alloca(len+1));
82 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
84 // It is unlikely the search failed, but it's always possible some file
85 // was added or removed since the last search, so be paranoid...
95 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
98 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
99 GetCurrentProcess(), &h,
100 0, TRUE, DUPLICATE_SAME_ACCESS);
108 fname = path->c_str();
110 SECURITY_ATTRIBUTES sa;
111 sa.nLength = sizeof(sa);
112 sa.lpSecurityDescriptor = 0;
113 sa.bInheritHandle = TRUE;
115 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
116 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
117 FILE_ATTRIBUTE_NORMAL, NULL);
118 if (h == INVALID_HANDLE_VALUE) {
119 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
120 (fd ? "input: " : "output: "));
127 // Due to unknown reason, mingw32's w32api doesn't have this declaration.
129 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
130 JOBOBJECTINFOCLASS JobObjectInfoClass,
131 LPVOID lpJobObjectInfo,
132 DWORD cbJobObjectInfoLength);
135 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
137 static bool ArgNeedsQuotes(const char *Str) {
138 return Str[0] == '\0' || strchr(Str, ' ') != 0;
142 Program::Execute(const Path& path,
145 const Path** redirects,
146 unsigned memoryLimit,
147 std::string* ErrMsg) {
149 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
150 CloseHandle(wpi->hProcess);
155 if (!path.canExecute()) {
157 *ErrMsg = "program not executable";
161 // Windows wants a command line, not an array of args, to pass to the new
162 // process. We have to concatenate them all, while quoting the args that
163 // have embedded spaces (or are empty).
165 // First, determine the length of the command line.
167 for (unsigned i = 0; args[i]; i++) {
168 len += strlen(args[i]) + 1;
169 if (ArgNeedsQuotes(args[i]))
173 // Now build the command line.
174 char *command = reinterpret_cast<char *>(_alloca(len+1));
177 for (unsigned i = 0; args[i]; i++) {
178 const char *arg = args[i];
179 size_t len = strlen(arg);
180 bool needsQuoting = ArgNeedsQuotes(arg);
192 // The pointer to the environment block for the new process.
196 // An environment block consists of a null-terminated block of
197 // null-terminated strings. Convert the array of environment variables to
198 // an environment block by concatenating them.
200 // First, determine the length of the environment block.
202 for (unsigned i = 0; envp[i]; i++)
203 len += strlen(envp[i]) + 1;
205 // Now build the environment block.
206 envblock = reinterpret_cast<char *>(_alloca(len+1));
209 for (unsigned i = 0; envp[i]; i++) {
210 const char *ev = envp[i];
211 size_t len = strlen(ev) + 1;
219 // Create a child process.
221 memset(&si, 0, sizeof(si));
223 si.hStdInput = INVALID_HANDLE_VALUE;
224 si.hStdOutput = INVALID_HANDLE_VALUE;
225 si.hStdError = INVALID_HANDLE_VALUE;
228 si.dwFlags = STARTF_USESTDHANDLES;
230 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
231 if (si.hStdInput == INVALID_HANDLE_VALUE) {
232 MakeErrMsg(ErrMsg, "can't redirect stdin");
235 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
236 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
237 CloseHandle(si.hStdInput);
238 MakeErrMsg(ErrMsg, "can't redirect stdout");
241 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
242 // If stdout and stderr should go to the same place, redirect stderr
243 // to the handle already open for stdout.
244 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
245 GetCurrentProcess(), &si.hStdError,
246 0, TRUE, DUPLICATE_SAME_ACCESS);
248 // Just redirect stderr
249 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
250 if (si.hStdError == INVALID_HANDLE_VALUE) {
251 CloseHandle(si.hStdInput);
252 CloseHandle(si.hStdOutput);
253 MakeErrMsg(ErrMsg, "can't redirect stderr");
259 PROCESS_INFORMATION pi;
260 memset(&pi, 0, sizeof(pi));
264 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
265 envblock, NULL, &si, &pi);
266 DWORD err = GetLastError();
268 // Regardless of whether the process got created or not, we are done with
269 // the handles we created for it to inherit.
270 CloseHandle(si.hStdInput);
271 CloseHandle(si.hStdOutput);
272 CloseHandle(si.hStdError);
274 // Now return an error if the process didn't get created.
277 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
281 Win32ProcessInfo* wpi = new Win32ProcessInfo;
282 wpi->hProcess = pi.hProcess;
283 wpi->dwProcessId = pi.dwProcessId;
286 // Make sure these get closed no matter what.
287 AutoHandle hThread(pi.hThread);
289 // Assign the process to a job if a memory limit is defined.
291 if (memoryLimit != 0) {
292 hJob = CreateJobObject(0, 0);
293 bool success = false;
295 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
296 memset(&jeli, 0, sizeof(jeli));
297 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
298 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
299 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
300 &jeli, sizeof(jeli))) {
301 if (AssignProcessToJobObject(hJob, pi.hProcess))
306 SetLastError(GetLastError());
307 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
308 TerminateProcess(pi.hProcess, 1);
309 WaitForSingleObject(pi.hProcess, INFINITE);
318 Program::Wait(unsigned secondsToWait,
319 std::string* ErrMsg) {
321 MakeErrMsg(ErrMsg, "Process not started!");
325 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
326 HANDLE hProcess = wpi->hProcess;
328 // Wait for the process to terminate.
329 DWORD millisecondsToWait = INFINITE;
330 if (secondsToWait > 0)
331 millisecondsToWait = secondsToWait * 1000;
333 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
334 if (!TerminateProcess(hProcess, 1)) {
335 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
338 WaitForSingleObject(hProcess, INFINITE);
341 // Get its exit status.
343 BOOL rc = GetExitCodeProcess(hProcess, &status);
344 DWORD err = GetLastError();
348 MakeErrMsg(ErrMsg, "Failed getting status for program.");
356 Program::Kill(std::string* ErrMsg) {
358 MakeErrMsg(ErrMsg, "Process not started!");
362 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
363 HANDLE hProcess = wpi->hProcess;
364 if (TerminateProcess(hProcess, 1) == 0) {
365 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
372 bool Program::ChangeStdinToBinary(){
373 int result = _setmode( _fileno(stdin), _O_BINARY );
377 bool Program::ChangeStdoutToBinary(){
378 int result = _setmode( _fileno(stdout), _O_BINARY );
382 bool Program::ChangeStderrToBinary(){
383 int result = _setmode( _fileno(stderr), _O_BINARY );