blob: 774bd02e88b26e642731154b648df5b52f7c9d04 [file] [log] [blame]
Reid Spencer52a7efa2004-08-29 19:20:41 +00001//===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Program class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
16//=== is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include <llvm/Config/config.h>
Reid Spencer52a7efa2004-08-29 19:20:41 +000020#include "Unix.h"
Reid Spencer2a7d9e92004-12-19 18:00:44 +000021#include <iostream>
Reid Spencercdf54d02004-12-27 06:16:52 +000022#if HAVE_SYS_STAT_H
23#include <sys/stat.h>
24#endif
25#if HAVE_SIGNAL_H
26#include <signal.h>
27#endif
28#if HAVE_FCNTL_H
29#include <fcntl.h>
30#endif
Reid Spencer52a7efa2004-08-29 19:20:41 +000031
Reid Spencerc0854bf2004-08-29 20:10:07 +000032extern char** environ;
33
Reid Spencer52a7efa2004-08-29 19:20:41 +000034namespace llvm {
35using namespace sys;
36
37// This function just uses the PATH environment variable to find the program.
Reid Spencer25659432004-09-13 21:48:44 +000038Path
Reid Spencer52a7efa2004-08-29 19:20:41 +000039Program::FindProgramByName(const std::string& progName) {
40
41 // Check some degenerate cases
42 if (progName.length() == 0) // no program
Reid Spencer25659432004-09-13 21:48:44 +000043 return Path();
44 Path temp;
Reid Spencer07adb282004-11-05 22:15:36 +000045 if (!temp.setFile(progName)) // invalid name
Reid Spencer25659432004-09-13 21:48:44 +000046 return Path();
Misha Brukman22c46da2005-04-20 15:42:11 +000047 // FIXME: have to check for absolute filename - we cannot assume anything
48 // about "." being in $PATH
Reid Spencerc7f08322005-07-07 18:21:42 +000049 if (temp.canExecute()) // already executable as is
Reid Spencer52a7efa2004-08-29 19:20:41 +000050 return temp;
51
52 // At this point, the file name is valid and its not executable
53
54 // Get the path. If its empty, we can't do anything to find it.
55 const char *PathStr = getenv("PATH");
56 if (PathStr == 0)
Reid Spencer25659432004-09-13 21:48:44 +000057 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000058
59 // Now we have a colon separated list of directories to search; try them.
60 unsigned PathLen = strlen(PathStr);
61 while (PathLen) {
62 // Find the first colon...
63 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
64
65 // Check to see if this first directory contains the executable...
Reid Spencer25659432004-09-13 21:48:44 +000066 Path FilePath;
Reid Spencer07adb282004-11-05 22:15:36 +000067 if (FilePath.setDirectory(std::string(PathStr,Colon))) {
68 FilePath.appendFile(progName);
Reid Spencerc7f08322005-07-07 18:21:42 +000069 if (FilePath.canExecute())
Reid Spencer52a7efa2004-08-29 19:20:41 +000070 return FilePath; // Found the executable!
71 }
72
73 // Nope it wasn't in this directory, check the next path in the list!
74 PathLen -= Colon-PathStr;
75 PathStr = Colon;
76
77 // Advance past duplicate colons
78 while (*PathStr == ':') {
79 PathStr++;
80 PathLen--;
81 }
82 }
Reid Spencer25659432004-09-13 21:48:44 +000083 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000084}
85
Reid Spencer2a7d9e92004-12-19 18:00:44 +000086static void RedirectFD(const std::string &File, int FD) {
87 if (File.empty()) return; // Noop
88
89 // Open the file
90 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
91 if (InFD == -1) {
92 ThrowErrno("Cannot open file '" + File + "' for "
93 + (FD == 0 ? "input" : "output") + "!\n");
94 }
95
96 dup2(InFD, FD); // Install it as the requested FD
97 close(InFD); // Close the original FD
98}
99
100static bool Timeout = false;
101static void TimeOutHandler(int Sig) {
102 Timeout = true;
103}
104
Reid Spencer52a7efa2004-08-29 19:20:41 +0000105int
Reid Spencer25659432004-09-13 21:48:44 +0000106Program::ExecuteAndWait(const Path& path,
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000107 const char** args,
108 const char** envp,
109 const Path** redirects,
110 unsigned secondsToWait
111) {
Reid Spencerc7f08322005-07-07 18:21:42 +0000112 if (!path.canExecute())
Reid Spencer1fce0912004-12-11 00:14:15 +0000113 throw path.toString() + " is not executable";
Reid Spencer52a7efa2004-08-29 19:20:41 +0000114
115#ifdef HAVE_SYS_WAIT_H
Reid Spencer52a7efa2004-08-29 19:20:41 +0000116 // Create a child process.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000117 int child = fork();
118 switch (child) {
Reid Spencer52a7efa2004-08-29 19:20:41 +0000119 // An error occured: Return to the caller.
120 case -1:
Reid Spencer1fce0912004-12-11 00:14:15 +0000121 ThrowErrno(std::string("Couldn't execute program '") + path.toString() +
122 "'");
Reid Spencer52a7efa2004-08-29 19:20:41 +0000123 break;
124
125 // Child process: Execute the program.
Reid Spencere2e24112004-12-14 04:18:51 +0000126 case 0: {
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000127 // Redirect file descriptors...
128 if (redirects) {
129 if (redirects[0])
130 if (redirects[0]->isEmpty())
131 RedirectFD("/dev/null",0);
132 else
133 RedirectFD(redirects[0]->toString(), 0);
134 if (redirects[1])
135 if (redirects[1]->isEmpty())
136 RedirectFD("/dev/null",1);
137 else
138 RedirectFD(redirects[1]->toString(), 1);
139 if (redirects[1] && redirects[2] &&
140 *(redirects[1]) != *(redirects[2])) {
141 if (redirects[2]->isEmpty())
142 RedirectFD("/dev/null",2);
143 else
144 RedirectFD(redirects[2]->toString(), 2);
145 } else {
146 dup2(1, 2);
147 }
148 }
149
150 // Set up the environment
Reid Spencere2e24112004-12-14 04:18:51 +0000151 char** env = environ;
152 if (envp != 0)
153 env = (char**) envp;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000154
155 // Execute!
156 execve (path.c_str(), (char** const)args, env);
Reid Spencer52a7efa2004-08-29 19:20:41 +0000157 // If the execve() failed, we should exit and let the parent pick up
158 // our non-zero exit status.
159 exit (errno);
Reid Spencere2e24112004-12-14 04:18:51 +0000160 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000161
162 // Parent process: Break out of the switch to do our processing.
163 default:
164 break;
165 }
166
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000167 // Make sure stderr and stdout have been flushed
168 std::cerr << std::flush;
169 std::cout << std::flush;
170 fsync(1);
171 fsync(2);
172
173 struct sigaction Act, Old;
174
175 // Install a timeout handler.
176 if (secondsToWait) {
177 Timeout = false;
178 Act.sa_sigaction = 0;
179 Act.sa_handler = TimeOutHandler;
180 sigemptyset(&Act.sa_mask);
181 Act.sa_flags = 0;
182 sigaction(SIGALRM, &Act, &Old);
183 alarm(secondsToWait);
184 }
185
Reid Spencer52a7efa2004-08-29 19:20:41 +0000186 // Parent process: Wait for the child process to terminate.
187 int status;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000188 while (wait(&status) != child)
189 if (secondsToWait && errno == EINTR) {
190 // Kill the child.
191 kill(child, SIGKILL);
192
193 // Turn off the alarm and restore the signal handler
194 alarm(0);
195 sigaction(SIGALRM, &Old, 0);
196
197 // Wait for child to die
198 if (wait(&status) != child)
199 ThrowErrno("Child timedout but wouldn't die");
200
201 return -1; // Timeout detected
202 } else {
203 ThrowErrno("Error waiting for child process");
204 }
205
206 // We exited normally without timeout, so turn off the timer.
207 if (secondsToWait) {
208 alarm(0);
209 sigaction(SIGALRM, &Old, 0);
210 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000211
212 // If the program exited normally with a zero exit status, return success!
213 if (WIFEXITED (status))
214 return WEXITSTATUS(status);
215 else if (WIFSIGNALED(status))
Chris Lattner8102fcd2005-01-16 04:23:22 +0000216 return 1;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000217
218#else
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000219 throw std::string(
220 "Program::ExecuteAndWait not implemented on this platform!\n");
Reid Spencer52a7efa2004-08-29 19:20:41 +0000221#endif
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000222 return 0;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000223}
224
225}