blob: 18cbc33d8417c6fddb210c561a794e3f5e560d4c [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"
21#include <sys/stat.h>
Brian Gaeke5d112c42004-12-19 18:58:11 +000022#include <signal.h>
Reid Spencer52a7efa2004-08-29 19:20:41 +000023#include <fcntl.h>
Reid Spencer52a7efa2004-08-29 19:20:41 +000024#ifdef HAVE_SYS_WAIT_H
25#include <sys/wait.h>
26#endif
Reid Spencer2a7d9e92004-12-19 18:00:44 +000027#include <iostream>
Reid Spencer52a7efa2004-08-29 19:20:41 +000028
Reid Spencerc0854bf2004-08-29 20:10:07 +000029extern char** environ;
30
Reid Spencer52a7efa2004-08-29 19:20:41 +000031namespace llvm {
32using namespace sys;
33
34// This function just uses the PATH environment variable to find the program.
Reid Spencer25659432004-09-13 21:48:44 +000035Path
Reid Spencer52a7efa2004-08-29 19:20:41 +000036Program::FindProgramByName(const std::string& progName) {
37
38 // Check some degenerate cases
39 if (progName.length() == 0) // no program
Reid Spencer25659432004-09-13 21:48:44 +000040 return Path();
41 Path temp;
Reid Spencer07adb282004-11-05 22:15:36 +000042 if (!temp.setFile(progName)) // invalid name
Reid Spencer25659432004-09-13 21:48:44 +000043 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000044 if (temp.executable()) // already executable as is
45 return temp;
46
47 // At this point, the file name is valid and its not executable
48
49 // Get the path. If its empty, we can't do anything to find it.
50 const char *PathStr = getenv("PATH");
51 if (PathStr == 0)
Reid Spencer25659432004-09-13 21:48:44 +000052 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000053
54 // Now we have a colon separated list of directories to search; try them.
55 unsigned PathLen = strlen(PathStr);
56 while (PathLen) {
57 // Find the first colon...
58 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
59
60 // Check to see if this first directory contains the executable...
Reid Spencer25659432004-09-13 21:48:44 +000061 Path FilePath;
Reid Spencer07adb282004-11-05 22:15:36 +000062 if (FilePath.setDirectory(std::string(PathStr,Colon))) {
63 FilePath.appendFile(progName);
Reid Spencer52a7efa2004-08-29 19:20:41 +000064 if (FilePath.executable())
65 return FilePath; // Found the executable!
66 }
67
68 // Nope it wasn't in this directory, check the next path in the list!
69 PathLen -= Colon-PathStr;
70 PathStr = Colon;
71
72 // Advance past duplicate colons
73 while (*PathStr == ':') {
74 PathStr++;
75 PathLen--;
76 }
77 }
Reid Spencer25659432004-09-13 21:48:44 +000078 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000079}
80
Reid Spencer2a7d9e92004-12-19 18:00:44 +000081static void RedirectFD(const std::string &File, int FD) {
82 if (File.empty()) return; // Noop
83
84 // Open the file
85 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
86 if (InFD == -1) {
87 ThrowErrno("Cannot open file '" + File + "' for "
88 + (FD == 0 ? "input" : "output") + "!\n");
89 }
90
91 dup2(InFD, FD); // Install it as the requested FD
92 close(InFD); // Close the original FD
93}
94
95static bool Timeout = false;
96static void TimeOutHandler(int Sig) {
97 Timeout = true;
98}
99
Reid Spencer52a7efa2004-08-29 19:20:41 +0000100int
Reid Spencer25659432004-09-13 21:48:44 +0000101Program::ExecuteAndWait(const Path& path,
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000102 const char** args,
103 const char** envp,
104 const Path** redirects,
105 unsigned secondsToWait
106) {
Reid Spencer25659432004-09-13 21:48:44 +0000107 if (!path.executable())
Reid Spencer1fce0912004-12-11 00:14:15 +0000108 throw path.toString() + " is not executable";
Reid Spencer52a7efa2004-08-29 19:20:41 +0000109
110#ifdef HAVE_SYS_WAIT_H
Reid Spencer52a7efa2004-08-29 19:20:41 +0000111 // Create a child process.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000112 int child = fork();
113 switch (child) {
Reid Spencer52a7efa2004-08-29 19:20:41 +0000114 // An error occured: Return to the caller.
115 case -1:
Reid Spencer1fce0912004-12-11 00:14:15 +0000116 ThrowErrno(std::string("Couldn't execute program '") + path.toString() +
117 "'");
Reid Spencer52a7efa2004-08-29 19:20:41 +0000118 break;
119
120 // Child process: Execute the program.
Reid Spencere2e24112004-12-14 04:18:51 +0000121 case 0: {
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000122 // Redirect file descriptors...
123 if (redirects) {
124 if (redirects[0])
125 if (redirects[0]->isEmpty())
126 RedirectFD("/dev/null",0);
127 else
128 RedirectFD(redirects[0]->toString(), 0);
129 if (redirects[1])
130 if (redirects[1]->isEmpty())
131 RedirectFD("/dev/null",1);
132 else
133 RedirectFD(redirects[1]->toString(), 1);
134 if (redirects[1] && redirects[2] &&
135 *(redirects[1]) != *(redirects[2])) {
136 if (redirects[2]->isEmpty())
137 RedirectFD("/dev/null",2);
138 else
139 RedirectFD(redirects[2]->toString(), 2);
140 } else {
141 dup2(1, 2);
142 }
143 }
144
145 // Set up the environment
Reid Spencere2e24112004-12-14 04:18:51 +0000146 char** env = environ;
147 if (envp != 0)
148 env = (char**) envp;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000149
150 // Execute!
151 execve (path.c_str(), (char** const)args, env);
Reid Spencer52a7efa2004-08-29 19:20:41 +0000152 // If the execve() failed, we should exit and let the parent pick up
153 // our non-zero exit status.
154 exit (errno);
Reid Spencere2e24112004-12-14 04:18:51 +0000155 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000156
157 // Parent process: Break out of the switch to do our processing.
158 default:
159 break;
160 }
161
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000162 // Make sure stderr and stdout have been flushed
163 std::cerr << std::flush;
164 std::cout << std::flush;
165 fsync(1);
166 fsync(2);
167
168 struct sigaction Act, Old;
169
170 // Install a timeout handler.
171 if (secondsToWait) {
172 Timeout = false;
173 Act.sa_sigaction = 0;
174 Act.sa_handler = TimeOutHandler;
175 sigemptyset(&Act.sa_mask);
176 Act.sa_flags = 0;
177 sigaction(SIGALRM, &Act, &Old);
178 alarm(secondsToWait);
179 }
180
Reid Spencer52a7efa2004-08-29 19:20:41 +0000181 // Parent process: Wait for the child process to terminate.
182 int status;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000183 while (wait(&status) != child)
184 if (secondsToWait && errno == EINTR) {
185 // Kill the child.
186 kill(child, SIGKILL);
187
188 // Turn off the alarm and restore the signal handler
189 alarm(0);
190 sigaction(SIGALRM, &Old, 0);
191
192 // Wait for child to die
193 if (wait(&status) != child)
194 ThrowErrno("Child timedout but wouldn't die");
195
196 return -1; // Timeout detected
197 } else {
198 ThrowErrno("Error waiting for child process");
199 }
200
201 // We exited normally without timeout, so turn off the timer.
202 if (secondsToWait) {
203 alarm(0);
204 sigaction(SIGALRM, &Old, 0);
205 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000206
207 // If the program exited normally with a zero exit status, return success!
208 if (WIFEXITED (status))
209 return WEXITSTATUS(status);
210 else if (WIFSIGNALED(status))
Reid Spencer1fce0912004-12-11 00:14:15 +0000211 throw std::string("Program '") + path.toString() +
212 "' received terminating signal.";
Reid Spencer52a7efa2004-08-29 19:20:41 +0000213
214#else
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000215 throw std::string(
216 "Program::ExecuteAndWait not implemented on this platform!\n");
Reid Spencer52a7efa2004-08-29 19:20:41 +0000217#endif
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000218 return 0;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000219}
220
221}
222// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab