blob: c29adf0bd13c5be1ae9fb0f76bf1880c5d59e7b6 [file] [log] [blame]
Reid Spencerb016a372004-09-15 05:49:50 +00001//===- Win32/Program.cpp - Win32 Program Implementation ------- -*- C++ -*-===//
Reid Spencer52a7efa2004-08-29 19:20:41 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencerb016a372004-09-15 05:49:50 +00005// This file was developed by Jeff Cohen and is distributed under the
Reid Spencer52a7efa2004-08-29 19:20:41 +00006// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencerb016a372004-09-15 05:49:50 +000014#include "Win32.h"
Reid Spencer32f55532006-06-07 23:18:34 +000015#include <cstdio>
Reid Spencerb016a372004-09-15 05:49:50 +000016#include <malloc.h>
Jeff Cohen875d08e2005-02-20 02:43:04 +000017#include <io.h>
Reid Spencer32f55532006-06-07 23:18:34 +000018#include <fcntl.h>
Reid Spencerb016a372004-09-15 05:49:50 +000019
Reid Spencer52a7efa2004-08-29 19:20:41 +000020//===----------------------------------------------------------------------===//
Reid Spencerb016a372004-09-15 05:49:50 +000021//=== WARNING: Implementation here must contain only Win32 specific code
22//=== and must not be UNIX code
Reid Spencer52a7efa2004-08-29 19:20:41 +000023//===----------------------------------------------------------------------===//
24
Reid Spencerb016a372004-09-15 05:49:50 +000025namespace llvm {
26using namespace sys;
27
28// This function just uses the PATH environment variable to find the program.
29Path
30Program::FindProgramByName(const std::string& progName) {
31
32 // Check some degenerate cases
33 if (progName.length() == 0) // no program
34 return Path();
35 Path temp;
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000036 if (!temp.set(progName)) // invalid name
Reid Spencerb016a372004-09-15 05:49:50 +000037 return Path();
Jeff Cohenedb9d6b2005-07-08 02:48:42 +000038 if (temp.canExecute()) // already executable as is
Reid Spencerb016a372004-09-15 05:49:50 +000039 return temp;
40
41 // At this point, the file name is valid and its not executable.
42 // Let Windows search for it.
43 char buffer[MAX_PATH];
44 char *dummy = NULL;
45 DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
46 buffer, &dummy);
47
48 // See if it wasn't found.
49 if (len == 0)
50 return Path();
51
52 // See if we got the entire path.
53 if (len < MAX_PATH)
54 return Path(buffer);
55
56 // Buffer was too small; grow and retry.
57 while (true) {
58 char *b = reinterpret_cast<char *>(_alloca(len+1));
59 DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
60
61 // It is unlikely the search failed, but it's always possible some file
62 // was added or removed since the last search, so be paranoid...
63 if (len2 == 0)
64 return Path();
65 else if (len2 <= len)
66 return Path(b);
67
68 len = len2;
69 }
70}
71
Jeff Cohen875d08e2005-02-20 02:43:04 +000072static HANDLE RedirectIO(const Path *path, int fd) {
73 HANDLE h;
74 if (path == 0) {
75 DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
76 GetCurrentProcess(), &h,
77 0, TRUE, DUPLICATE_SAME_ACCESS);
78 return h;
79 }
80
81 const char *fname = path->toString().c_str();
82 if (*fname == 0)
83 fname = "NUL";
84
85 SECURITY_ATTRIBUTES sa;
86 sa.nLength = sizeof(sa);
87 sa.lpSecurityDescriptor = 0;
88 sa.bInheritHandle = TRUE;
89
90 h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
Jeff Cohen45a1b262005-02-20 02:48:51 +000091 &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
Jeff Cohen875d08e2005-02-20 02:43:04 +000092 FILE_ATTRIBUTE_NORMAL, NULL);
93 if (h == INVALID_HANDLE_VALUE) {
94 ThrowError(std::string(fname) + ": Can't open file for " +
95 (fd ? "input: " : "output: "));
96 }
97 return h;
98}
99
Reid Spencerb016a372004-09-15 05:49:50 +0000100int
101Program::ExecuteAndWait(const Path& path,
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000102 const char** args,
103 const char** envp,
104 const Path** redirects,
105 unsigned secondsToWait) {
Jeff Cohenedb9d6b2005-07-08 02:48:42 +0000106 if (!path.canExecute())
Reid Spencer707a27c2004-12-11 17:37:01 +0000107 throw path.toString() + " is not executable";
Reid Spencerb016a372004-09-15 05:49:50 +0000108
109 // Windows wants a command line, not an array of args, to pass to the new
110 // process. We have to concatenate them all, while quoting the args that
111 // have embedded spaces.
112
113 // First, determine the length of the command line.
Jeff Cohene5f7e652005-02-16 04:43:45 +0000114 unsigned len = 0;
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000115 for (unsigned i = 0; args[i]; i++) {
116 len += strlen(args[i]) + 1;
117 if (strchr(args[i], ' '))
Reid Spencerb016a372004-09-15 05:49:50 +0000118 len += 2;
119 }
120
121 // Now build the command line.
122 char *command = reinterpret_cast<char *>(_alloca(len));
123 char *p = command;
124
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000125 for (unsigned i = 0; args[i]; i++) {
126 const char *arg = args[i];
Jeff Cohen01c55132005-04-11 03:44:22 +0000127 size_t len = strlen(arg);
Jeff Cohene5f7e652005-02-16 04:43:45 +0000128 bool needsQuoting = strchr(arg, ' ') != 0;
Reid Spencerb016a372004-09-15 05:49:50 +0000129 if (needsQuoting)
130 *p++ = '"';
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000131 memcpy(p, arg, len);
132 p += len;
Reid Spencerb016a372004-09-15 05:49:50 +0000133 if (needsQuoting)
134 *p++ = '"';
135 *p++ = ' ';
136 }
137
138 *p = 0;
139
140 // Create a child process.
141 STARTUPINFO si;
142 memset(&si, 0, sizeof(si));
143 si.cb = sizeof(si);
Jeff Cohen875d08e2005-02-20 02:43:04 +0000144 si.hStdInput = INVALID_HANDLE_VALUE;
145 si.hStdOutput = INVALID_HANDLE_VALUE;
146 si.hStdError = INVALID_HANDLE_VALUE;
Reid Spencerb016a372004-09-15 05:49:50 +0000147
Jeff Cohen875d08e2005-02-20 02:43:04 +0000148 if (redirects) {
149 si.dwFlags = STARTF_USESTDHANDLES;
150
151 try {
152 si.hStdInput = RedirectIO(redirects[0], 0);
153 si.hStdOutput = RedirectIO(redirects[1], 1);
154 if (redirects[1] && redirects[2] && *(redirects[1]) != *(redirects[2])) {
155 si.hStdError = RedirectIO(redirects[2], 2);
156 } else {
157 DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
158 GetCurrentProcess(), &si.hStdError,
159 0, TRUE, DUPLICATE_SAME_ACCESS);
160 }
161 } catch (...) {
162 CloseHandle(si.hStdInput);
163 CloseHandle(si.hStdOutput);
164 CloseHandle(si.hStdError);
165 throw;
166 }
167 }
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000168
Reid Spencerb016a372004-09-15 05:49:50 +0000169 PROCESS_INFORMATION pi;
170 memset(&pi, 0, sizeof(pi));
171
Jeff Cohen875d08e2005-02-20 02:43:04 +0000172 fflush(stdout);
173 fflush(stderr);
174 BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, FALSE, 0,
175 envp, NULL, &si, &pi);
176 DWORD err = GetLastError();
177
178 // Regardless of whether the process got created or not, we are done with
179 // the handles we created for it to inherit.
180 CloseHandle(si.hStdInput);
181 CloseHandle(si.hStdOutput);
182 CloseHandle(si.hStdError);
183
184 // Now throw an error if the process didn't get created.
185 if (!rc)
Reid Spencerb016a372004-09-15 05:49:50 +0000186 {
Jeff Cohen875d08e2005-02-20 02:43:04 +0000187 SetLastError(err);
Reid Spencer707a27c2004-12-11 17:37:01 +0000188 ThrowError(std::string("Couldn't execute program '") +
189 path.toString() + "'");
Reid Spencerb016a372004-09-15 05:49:50 +0000190 }
191
192 // Wait for it to terminate.
Jeff Cohena1b3d3d2004-12-20 03:24:56 +0000193 DWORD millisecondsToWait = INFINITE;
194 if (secondsToWait > 0)
195 millisecondsToWait = secondsToWait * 1000;
196
197 if (WaitForSingleObject(pi.hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
198 if (!TerminateProcess(pi.hProcess, 1)) {
199 ThrowError(std::string("Failed to terminate timed-out program '") +
200 path.toString() + "'");
201 }
202 WaitForSingleObject(pi.hProcess, INFINITE);
203 }
Reid Spencerb016a372004-09-15 05:49:50 +0000204
205 // Get its exit status.
206 DWORD status;
Jeff Cohen875d08e2005-02-20 02:43:04 +0000207 rc = GetExitCodeProcess(pi.hProcess, &status);
208 err = GetLastError();
Reid Spencerb016a372004-09-15 05:49:50 +0000209
210 // Done with the handles; go close them.
211 CloseHandle(pi.hProcess);
212 CloseHandle(pi.hThread);
213
Jeff Cohen875d08e2005-02-20 02:43:04 +0000214 if (!rc) {
215 SetLastError(err);
Reid Spencer707a27c2004-12-11 17:37:01 +0000216 ThrowError(std::string("Failed getting status for program '") +
217 path.toString() + "'");
Jeff Cohen875d08e2005-02-20 02:43:04 +0000218 }
Reid Spencerb016a372004-09-15 05:49:50 +0000219
220 return status;
221}
222
Reid Spencer32f55532006-06-07 23:18:34 +0000223void Program::ChangeStdinToBinary(){
224 int result = _setmode( _fileno(stdin), _O_BINARY );
225 if( result == -1 )
226 throw std::string("Cannot set input mode on stdin to binary.");
227}
228
229void Program::ChangeStdoutToBinary(){
230 int result = _setmode( _fileno(stdout), _O_BINARY );
231 if( result == -1 )
232 throw std::string("Cannot set output mode on stdout to binary.");
233}
234
Reid Spencerb016a372004-09-15 05:49:50 +0000235}