raw_ostream::indent is used for PadToColumn which often prints more
[oota-llvm.git] / lib / System / Win32 / Program.inc
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 "Win32.h"
15 #include <cstdio>
16 #include <malloc.h>
17 #include <io.h>
18 #include <fcntl.h>
19
20 //===----------------------------------------------------------------------===//
21 //=== WARNING: Implementation here must contain only Win32 specific code
22 //===          and must not be UNIX code
23 //===----------------------------------------------------------------------===//
24
25 namespace llvm {
26 using namespace sys;
27
28 Program::Program() : Pid_(0), Data(0) {}
29
30 Program::~Program() {
31         if (Data) {
32                 HANDLE hProcess = (HANDLE) Data;
33                 CloseHandle(hProcess);
34                 Data = 0;
35         }
36 }
37
38 // This function just uses the PATH environment variable to find the program.
39 Path
40 Program::FindProgramByName(const std::string& progName) {
41
42   // Check some degenerate cases
43   if (progName.length() == 0) // no program
44     return Path();
45   Path temp;
46   if (!temp.set(progName)) // invalid name
47     return Path();
48   if (temp.canExecute()) // already executable as is
49     return temp;
50
51   // At this point, the file name is valid and its not executable.
52   // Let Windows search for it.
53   char buffer[MAX_PATH];
54   char *dummy = NULL;
55   DWORD len = SearchPath(NULL, progName.c_str(), ".exe", MAX_PATH,
56                          buffer, &dummy);
57
58   // See if it wasn't found.
59   if (len == 0)
60     return Path();
61
62   // See if we got the entire path.
63   if (len < MAX_PATH)
64     return Path(buffer);
65
66   // Buffer was too small; grow and retry.
67   while (true) {
68     char *b = reinterpret_cast<char *>(_alloca(len+1));
69     DWORD len2 = SearchPath(NULL, progName.c_str(), ".exe", len+1, b, &dummy);
70
71     // It is unlikely the search failed, but it's always possible some file
72     // was added or removed since the last search, so be paranoid...
73     if (len2 == 0)
74       return Path();
75     else if (len2 <= len)
76       return Path(b);
77
78     len = len2;
79   }
80 }
81
82 static HANDLE RedirectIO(const Path *path, int fd, std::string* ErrMsg) {
83   HANDLE h;
84   if (path == 0) {
85     DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
86                     GetCurrentProcess(), &h,
87                     0, TRUE, DUPLICATE_SAME_ACCESS);
88     return h;
89   }
90
91   const char *fname;
92   if (path->isEmpty())
93     fname = "NUL";
94   else
95     fname = path->c_str();
96
97   SECURITY_ATTRIBUTES sa;
98   sa.nLength = sizeof(sa);
99   sa.lpSecurityDescriptor = 0;
100   sa.bInheritHandle = TRUE;
101
102   h = CreateFile(fname, fd ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
103                  &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
104                  FILE_ATTRIBUTE_NORMAL, NULL);
105   if (h == INVALID_HANDLE_VALUE) {
106     MakeErrMsg(ErrMsg, std::string(fname) + ": Can't open file for " +
107         (fd ? "input: " : "output: "));
108   }
109
110   return h;
111 }
112
113 #ifdef __MINGW32__
114   // Due to unknown reason, mingw32's w32api doesn't have this declaration.
115   extern "C"
116   BOOL WINAPI SetInformationJobObject(HANDLE hJob,
117                                       JOBOBJECTINFOCLASS JobObjectInfoClass,
118                                       LPVOID lpJobObjectInfo,
119                                       DWORD cbJobObjectInfoLength);
120 #endif
121
122 /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
123 /// CreateProcess.
124 static bool ArgNeedsQuotes(const char *Str) {  
125   return Str[0] == '\0' || strchr(Str, ' ') != 0;
126 }
127
128 bool
129 Program::Execute(const Path& path,
130                  const char** args,
131                  const char** envp,
132                  const Path** redirects,
133                  unsigned memoryLimit,
134                  std::string* ErrMsg) {
135   if (Data) {
136     HANDLE hProcess = (HANDLE) Data;
137     CloseHandle(Data);
138     Data = 0;
139   }
140   
141   if (!path.canExecute()) {
142     if (ErrMsg)
143       *ErrMsg = "program not executable";
144     return false;
145   }
146
147   // Windows wants a command line, not an array of args, to pass to the new
148   // process.  We have to concatenate them all, while quoting the args that
149   // have embedded spaces (or are empty).
150
151   // First, determine the length of the command line.
152   unsigned len = 0;
153   for (unsigned i = 0; args[i]; i++) {
154     len += strlen(args[i]) + 1;
155     if (ArgNeedsQuotes(args[i]))
156       len += 2;
157   }
158
159   // Now build the command line.
160   char *command = reinterpret_cast<char *>(_alloca(len+1));
161   char *p = command;
162
163   for (unsigned i = 0; args[i]; i++) {
164     const char *arg = args[i];
165     size_t len = strlen(arg);
166     bool needsQuoting = ArgNeedsQuotes(arg);
167     if (needsQuoting)
168       *p++ = '"';
169     memcpy(p, arg, len);
170     p += len;
171     if (needsQuoting)
172       *p++ = '"';
173     *p++ = ' ';
174   }
175
176   *p = 0;
177
178   // The pointer to the environment block for the new process.
179   char *envblock = 0;
180
181   if (envp) {
182     // An environment block consists of a null-terminated block of
183     // null-terminated strings. Convert the array of environment variables to
184     // an environment block by concatenating them.
185
186     // First, determine the length of the environment block.
187     len = 0;
188     for (unsigned i = 0; envp[i]; i++)
189       len += strlen(envp[i]) + 1;
190
191     // Now build the environment block.
192     envblock = reinterpret_cast<char *>(_alloca(len+1));
193     p = envblock;
194
195     for (unsigned i = 0; envp[i]; i++) {
196       const char *ev = envp[i];
197       size_t len = strlen(ev) + 1;
198       memcpy(p, ev, len);
199       p += len;
200     }
201
202     *p = 0;
203   }
204
205   // Create a child process.
206   STARTUPINFO si;
207   memset(&si, 0, sizeof(si));
208   si.cb = sizeof(si);
209   si.hStdInput = INVALID_HANDLE_VALUE;
210   si.hStdOutput = INVALID_HANDLE_VALUE;
211   si.hStdError = INVALID_HANDLE_VALUE;
212
213   if (redirects) {
214     si.dwFlags = STARTF_USESTDHANDLES;
215
216     si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
217     if (si.hStdInput == INVALID_HANDLE_VALUE) {
218       MakeErrMsg(ErrMsg, "can't redirect stdin");
219       return false;
220     }
221     si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
222     if (si.hStdOutput == INVALID_HANDLE_VALUE) {
223       CloseHandle(si.hStdInput);
224       MakeErrMsg(ErrMsg, "can't redirect stdout");
225       return false;
226     }
227     if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
228       // If stdout and stderr should go to the same place, redirect stderr
229       // to the handle already open for stdout.
230       DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
231                       GetCurrentProcess(), &si.hStdError,
232                       0, TRUE, DUPLICATE_SAME_ACCESS);
233     } else {
234       // Just redirect stderr
235       si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
236       if (si.hStdError == INVALID_HANDLE_VALUE) {
237         CloseHandle(si.hStdInput);
238         CloseHandle(si.hStdOutput);
239         MakeErrMsg(ErrMsg, "can't redirect stderr");
240         return false;
241       }
242     }
243   }
244
245   PROCESS_INFORMATION pi;
246   memset(&pi, 0, sizeof(pi));
247
248   fflush(stdout);
249   fflush(stderr);
250   BOOL rc = CreateProcess(path.c_str(), command, NULL, NULL, TRUE, 0,
251                           envblock, NULL, &si, &pi);
252   DWORD err = GetLastError();
253
254   // Regardless of whether the process got created or not, we are done with
255   // the handles we created for it to inherit.
256   CloseHandle(si.hStdInput);
257   CloseHandle(si.hStdOutput);
258   CloseHandle(si.hStdError);
259
260   // Now return an error if the process didn't get created.
261   if (!rc) {
262     SetLastError(err);
263     MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
264                path.str() + "'");
265     return false;
266   }
267   Pid_ = pi.dwProcessId;
268   Data = pi.hProcess;
269   
270   // Make sure these get closed no matter what.
271   AutoHandle hThread(pi.hThread);
272
273   // Assign the process to a job if a memory limit is defined.
274   AutoHandle hJob(0);
275   if (memoryLimit != 0) {
276     hJob = CreateJobObject(0, 0);
277     bool success = false;
278     if (hJob != 0) {
279       JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
280       memset(&jeli, 0, sizeof(jeli));
281       jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
282       jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
283       if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
284                                   &jeli, sizeof(jeli))) {
285         if (AssignProcessToJobObject(hJob, pi.hProcess))
286           success = true;
287       }
288     }
289     if (!success) {
290       SetLastError(GetLastError());
291       MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
292       TerminateProcess(pi.hProcess, 1);
293       WaitForSingleObject(pi.hProcess, INFINITE);
294       return false;
295     }
296   }
297
298   return true;
299 }
300
301 int
302 Program::Wait(unsigned secondsToWait,
303               std::string* ErrMsg) {
304   if (Data == 0) {
305     MakeErrMsg(ErrMsg, "Process not started!");
306     return -1;
307   }
308
309   HANDLE hProcess = (HANDLE) Data;
310   
311   // Wait for the process to terminate.
312   DWORD millisecondsToWait = INFINITE;
313   if (secondsToWait > 0)
314     millisecondsToWait = secondsToWait * 1000;
315
316   if (WaitForSingleObject(hProcess, millisecondsToWait) == WAIT_TIMEOUT) {
317     if (!TerminateProcess(hProcess, 1)) {
318       MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
319       return -1;
320     }
321     WaitForSingleObject(hProcess, INFINITE);
322   }
323
324   // Get its exit status.
325   DWORD status;
326   BOOL rc = GetExitCodeProcess(hProcess, &status);
327   DWORD err = GetLastError();
328
329   if (!rc) {
330     SetLastError(err);
331     MakeErrMsg(ErrMsg, "Failed getting status for program.");
332     return -1;
333   }
334
335   return status;
336 }
337
338 bool Program::ChangeStdinToBinary(){
339   int result = _setmode( _fileno(stdin), _O_BINARY );
340   return result == -1;
341 }
342
343 bool Program::ChangeStdoutToBinary(){
344   int result = _setmode( _fileno(stdout), _O_BINARY );
345   return result == -1;
346 }
347
348 }