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 // Ancient mingw32's w32api might not have this declaration.
28 BOOL WINAPI SetInformationJobObject(HANDLE hJob,
29 JOBOBJECTINFOCLASS JobObjectInfoClass,
30 LPVOID lpJobObjectInfo,
31 DWORD cbJobObjectInfoLength);
35 struct Win32ProcessInfo {
44 Program::Program() : Data_(0) {}
48 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
49 CloseHandle(wpi->hProcess);
55 unsigned Program::GetPid() const {
56 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
57 return wpi->dwProcessId;
60 // This function just uses the PATH environment variable to find the program.
62 Program::FindProgramByName(const std::string& progName) {
64 // Check some degenerate cases
65 if (progName.length() == 0) // no program
68 if (!temp.set(progName)) // invalid name
70 if (temp.canExecute()) // already executable as is
73 // At this point, the file name is valid and its not executable.
74 // Let Windows search for it.
75 char buffer[MAX_PATH];
77 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
80 // See if it wasn't found.
84 // See if we got the entire path.
88 // Buffer was too small; grow and retry.
90 char *b = reinterpret_cast<char *>(_alloca(len+1));
91 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
93 // It is unlikely the search failed, but it's always possible some file
94 // was added or removed since the last search, so be paranoid...
104 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
107 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
108 GetCurrentProcess(), &h,
109 0, TRUE, DUPLICATE_SAME_ACCESS);
117 fname = path->c_str();
119 SECURITY_ATTRIBUTES sa;
120 sa.nLength = sizeof(sa);
121 sa.lpSecurityDescriptor = 0;
122 sa.bInheritHandle = TRUE;
124 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
125 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
126 FILE_ATTRIBUTE_NORMAL, NULL);
127 if (h == INVALID_HANDLE_VALUE) {
128 MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
129 (fd ? "input: " : "output: "));
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 /// 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 unsigned int len = ArgNeedsQuotes(Str) ? 2 : 0;
147 while (*Str != '\0') {
160 Program::Execute(const Path& path,
163 const Path** redirects,
164 unsigned memoryLimit,
165 std::string* ErrMsg) {
167 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
168 CloseHandle(wpi->hProcess);
173 if (!path.canExecute()) {
175 *ErrMsg = "program not executable";
179 // Windows wants a command line, not an array of args, to pass to the new
180 // process. We have to concatenate them all, while quoting the args that
181 // have embedded spaces (or are empty).
183 // First, determine the length of the command line.
185 for (unsigned i = 0; args[i]; i++) {
186 len += ArgLenWithQuotes(args[i]) + 1;
189 // Now build the command line.
190 char *command = reinterpret_cast<char *>(_alloca(len+1));
193 for (unsigned i = 0; args[i]; i++) {
194 const char *arg = args[i];
196 bool needsQuoting = ArgNeedsQuotes(arg);
200 while (*arg != '\0') {
214 // The pointer to the environment block for the new process.
218 // An environment block consists of a null-terminated block of
219 // null-terminated strings. Convert the array of environment variables to
220 // an environment block by concatenating them.
222 // First, determine the length of the environment block.
224 for (unsigned i = 0; envp[i]; i++)
225 len += strlen(envp[i]) + 1;
227 // Now build the environment block.
228 envblock = reinterpret_cast<char *>(_alloca(len+1));
231 for (unsigned i = 0; envp[i]; i++) {
232 const char *ev = envp[i];
233 size_t len = strlen(ev) + 1;
241 // Create a child process.
243 memset(&si, 0, sizeof(si));
245 si.hStdInput = INVALID_HANDLE_VALUE;
246 si.hStdOutput = INVALID_HANDLE_VALUE;
247 si.hStdError = INVALID_HANDLE_VALUE;
250 si.dwFlags = STARTF_USESTDHANDLES;
252 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
253 if (si.hStdInput == INVALID_HANDLE_VALUE) {
254 MakeErrMsg(ErrMsg, "can't redirect stdin");
257 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
258 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
259 CloseHandle(si.hStdInput);
260 MakeErrMsg(ErrMsg, "can't redirect stdout");
263 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
264 // If stdout and stderr should go to the same place, redirect stderr
265 // to the handle already open for stdout.
266 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
267 GetCurrentProcess(), &si.hStdError,
268 0, TRUE, DUPLICATE_SAME_ACCESS);
270 // Just redirect stderr
271 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
272 if (si.hStdError == INVALID_HANDLE_VALUE) {
273 CloseHandle(si.hStdInput);
274 CloseHandle(si.hStdOutput);
275 MakeErrMsg(ErrMsg, "can't redirect stderr");
281 PROCESS_INFORMATION pi;
282 memset(&pi, 0, sizeof(pi));
286 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
287 envblock, NULL, &si, &pi);
288 DWORD err = GetLastError();
290 // Regardless of whether the process got created or not, we are done with
291 // the handles we created for it to inherit.
292 CloseHandle(si.hStdInput);
293 CloseHandle(si.hStdOutput);
294 CloseHandle(si.hStdError);
296 // Now return an error if the process didn't get created.
299 MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
303 Win32ProcessInfo* wpi = new Win32ProcessInfo;
304 wpi->hProcess = pi.hProcess;
305 wpi->dwProcessId = pi.dwProcessId;
308 // Make sure these get closed no matter what.
309 AutoHandle hThread(pi.hThread);
311 // Assign the process to a job if a memory limit is defined.
313 if (memoryLimit != 0) {
314 hJob = CreateJobObject(0, 0);
315 bool success = false;
317 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
318 memset(&jeli, 0, sizeof(jeli));
319 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
320 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
321 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
322 &jeli, sizeof(jeli))) {
323 if (AssignProcessToJobObject(hJob, pi.hProcess))
328 SetLastError(GetLastError());
329 MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
330 TerminateProcess(pi.hProcess, 1);
331 WaitForSingleObject(pi.hProcess, INFINITE);
340 Program::Wait(const Path &path,
341 unsigned secondsToWait,
342 std::string* ErrMsg) {
344 MakeErrMsg(ErrMsg, "Process not started!");
348 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
349 HANDLE hProcess = wpi->hProcess;
351 // Wait for the process to terminate.
352 DWORD millisecondsToWait = INFINITE;
353 if (secondsToWait > 0)
354 millisecondsToWait = secondsToWait * 1000;
356 if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
357 if (!TerminateProcess(hProcess, 1)) {
358 MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
361 WaitForSingleObject(hProcess, INFINITE);
364 // Get its exit status.
366 BOOL rc = GetExitCodeProcess(hProcess, &status);
367 DWORD err = GetLastError();
371 MakeErrMsg(ErrMsg, "Failed getting status for program.");
379 Program::Kill(std::string* ErrMsg) {
381 MakeErrMsg(ErrMsg, "Process not started!");
385 Win32ProcessInfo* wpi = reinterpret_cast<Win32ProcessInfo*>(Data_);
386 HANDLE hProcess = wpi->hProcess;
387 if (TerminateProcess(hProcess, 1) == 0) {
388 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
395 bool Program::ChangeStdinToBinary(){
396 int result = _setmode( _fileno(stdin), _O_BINARY );
400 bool Program::ChangeStdoutToBinary(){
401 int result = _setmode( _fileno(stdout), _O_BINARY );
405 bool Program::ChangeStderrToBinary(){
406 int result = _setmode( _fileno(stderr), _O_BINARY );