blob: e198c7ec063ef73de36dff4d7ffbd3c710498a78 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
2//
3// This file contains functions used to do a variety of low-level, often
4// system-specific, tasks.
5//
6//===----------------------------------------------------------------------===//
7
Misha Brukman3d1b0c72003-08-07 21:28:50 +00008#include "Support/SystemUtils.h"
Chris Lattner4a106452002-12-23 23:50:16 +00009#include <algorithm>
10#include <fstream>
Chris Lattnere1b52b72002-12-24 00:44:34 +000011#include <iostream>
Chris Lattner3301b692003-01-29 18:15:34 +000012#include <cstdlib>
John Criswell7a73b802003-06-30 21:59:07 +000013#include "Config/sys/types.h"
14#include "Config/sys/stat.h"
15#include "Config/fcntl.h"
16#include "Config/sys/wait.h"
17#include "Config/unistd.h"
18#include "Config/errno.h"
Chris Lattner4a106452002-12-23 23:50:16 +000019
Chris Lattner4a106452002-12-23 23:50:16 +000020/// isExecutableFile - This function returns true if the filename specified
21/// exists and is executable.
22///
23bool isExecutableFile(const std::string &ExeFileName) {
24 struct stat Buf;
25 if (stat(ExeFileName.c_str(), &Buf))
26 return false; // Must not be executable!
27
28 if (!(Buf.st_mode & S_IFREG))
29 return false; // Not a regular file?
30
31 if (Buf.st_uid == getuid()) // Owner of file?
32 return Buf.st_mode & S_IXUSR;
33 else if (Buf.st_gid == getgid()) // In group of file?
34 return Buf.st_mode & S_IXGRP;
35 else // Unrelated to file?
36 return Buf.st_mode & S_IXOTH;
37}
38
Misha Brukmanf7066c72003-08-07 21:34:25 +000039/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000040/// being executed. This allows us to find another LLVM tool if it is built
41/// into the same directory, but that directory is neither the current
42/// directory, nor in the PATH. If the executable cannot be found, return an
43/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000044///
Chris Lattner4a106452002-12-23 23:50:16 +000045std::string FindExecutable(const std::string &ExeName,
Misha Brukman44f8a342003-09-29 22:40:07 +000046 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000047 // First check the directory that bugpoint is in. We can do this if
48 // BugPointPath contains at least one / character, indicating that it is a
49 // relative path to bugpoint itself.
50 //
Misha Brukman35d402f2003-08-07 21:33:33 +000051 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000052 while (!Result.empty() && Result[Result.size()-1] != '/')
53 Result.erase(Result.size()-1, 1);
54
55 if (!Result.empty()) {
56 Result += ExeName;
57 if (isExecutableFile(Result)) return Result; // Found it?
58 }
59
Misha Brukman35d402f2003-08-07 21:33:33 +000060 // Okay, if the path to the program didn't tell us anything, try using the
61 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000062 const char *PathStr = getenv("PATH");
63 if (PathStr == 0) return "";
64
Misha Brukmanbc0e9982003-07-14 17:20:40 +000065 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000066 unsigned PathLen = strlen(PathStr);
67 while (PathLen) {
68 // Find the first colon...
69 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
70
71 // Check to see if this first directory contains the executable...
72 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
73 if (isExecutableFile(FilePath))
74 return FilePath; // Found the executable!
75
76 // Nope it wasn't in this directory, check the next range!
77 PathLen -= Colon-PathStr;
78 PathStr = Colon;
79 while (*PathStr == ':') { // Advance past colons
80 PathStr++;
81 PathLen--;
82 }
83 }
84
85 // If we fell out, we ran out of directories in PATH to search, return failure
86 return "";
87}
88
89static void RedirectFD(const std::string &File, int FD) {
90 if (File.empty()) return; // Noop
91
92 // Open the file
93 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
94 if (InFD == -1) {
95 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +000096 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +000097 exit(1);
98 }
99
100 dup2(InFD, FD); // Install it as the requested FD
101 close(InFD); // Close the original FD
102}
103
104/// RunProgramWithTimeout - This function executes the specified program, with
105/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000106/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000107/// the calling program if there is an error executing the specified program.
108/// It returns the return value of the program, or -1 if a timeout is detected.
109///
110int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
Misha Brukman44f8a342003-09-29 22:40:07 +0000111 const std::string &StdInFile,
112 const std::string &StdOutFile,
113 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000114
115 // FIXME: install sigalarm handler here for timeout...
116
117 int Child = fork();
118 switch (Child) {
119 case -1:
120 std::cerr << "ERROR forking!\n";
121 exit(1);
122 case 0: // Child
123 RedirectFD(StdInFile, 0); // Redirect file descriptors...
124 RedirectFD(StdOutFile, 1);
125 RedirectFD(StdErrFile, 2);
126
127 execv(ProgramPath.c_str(), (char *const *)Args);
128 std::cerr << "Error executing program '" << ProgramPath;
129 for (; *Args; ++Args)
130 std::cerr << " " << *Args;
131 exit(1);
132
133 default: break;
134 }
135
136 // Make sure all output has been written while waiting
137 std::cout << std::flush;
138
139 int Status;
140 if (wait(&Status) != Child) {
141 if (errno == EINTR) {
142 static bool FirstTimeout = true;
143 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000144 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000145 "*** Program execution timed out! This mechanism is designed to handle\n"
146 " programs stuck in infinite loops gracefully. The -timeout option\n"
147 " can be used to change the timeout threshold or disable it completely\n"
148 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000149 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000150 }
151 return -1; // Timeout detected
152 }
153
154 std::cerr << "Error waiting for child process!\n";
155 exit(1);
156 }
157 return Status;
158}
John Criswell5afb5f62003-09-17 15:13:59 +0000159
160
161//
162// Function: ExecWait ()
163//
164// Description:
165// This function executes a program with the specified arguments and
166// environment. It then waits for the progarm to termiante and then returns
167// to the caller.
168//
169// Inputs:
170// argv - The arguments to the program as an array of C strings. The first
171// argument should be the name of the program to execute, and the
172// last argument should be a pointer to NULL.
173//
174// envp - The environment passes to the program as an array of C strings in
175// the form of "name=value" pairs. The last element should be a
176// pointer to NULL.
177//
178// Outputs:
179// None.
180//
181// Return value:
182// 0 - No errors.
183// 1 - The program could not be executed.
184// 1 - The program returned a non-zero exit status.
185// 1 - The program terminated abnormally.
186//
187// Notes:
188// The program will inherit the stdin, stdout, and stderr file descriptors
189// as well as other various configuration settings (umask).
190//
191// This function should not print anything to stdout/stderr on its own. It is
192// a generic library function. The caller or executed program should report
193// errors in the way it sees fit.
194//
John Criswelle5b3e152003-09-17 19:02:49 +0000195// This function does not use $PATH to find programs.
196//
John Criswell5afb5f62003-09-17 15:13:59 +0000197int
John Criswelle5b3e152003-09-17 19:02:49 +0000198ExecWait (const char * const old_argv[], const char * const old_envp[])
John Criswell5afb5f62003-09-17 15:13:59 +0000199{
200 // Child process ID
201 register int child;
202
203 // Status from child process when it exits
204 int status;
205
206 //
John Criswelle5b3e152003-09-17 19:02:49 +0000207 // Create local versions of the parameters that can be passed into execve()
208 // without creating const problems.
John Criswell5afb5f62003-09-17 15:13:59 +0000209 //
John Criswelle5b3e152003-09-17 19:02:49 +0000210 char ** const argv = (char ** const) old_argv;
211 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000212
213 //
214 // Create a child process.
215 //
216 switch (child=fork())
217 {
John Criswelle5b3e152003-09-17 19:02:49 +0000218 //
219 // An error occured: Return to the caller.
220 //
John Criswell5afb5f62003-09-17 15:13:59 +0000221 case -1:
222 return 1;
223 break;
224
John Criswelle5b3e152003-09-17 19:02:49 +0000225 //
226 // Child process: Execute the program.
227 //
John Criswell5afb5f62003-09-17 15:13:59 +0000228 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000229 execve (argv[0], argv, envp);
230
231 //
232 // If the execve() failed, we should exit and let the parent pick up
233 // our non-zero exit status.
234 //
235 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000236 break;
237
John Criswelle5b3e152003-09-17 19:02:49 +0000238 //
239 // Parent process: Break out of the switch to do our processing.
240 //
John Criswell5afb5f62003-09-17 15:13:59 +0000241 default:
242 break;
243 }
244
245 //
246 // Parent process: Wait for the child process to termiante.
247 //
248 if ((wait (&status)) == -1)
249 {
250 return 1;
251 }
252
253 //
254 // If the program exited normally with a zero exit status, return success!
255 //
256 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
257 {
258 return 0;
259 }
260
261 //
262 // Otherwise, return failure.
263 //
264 return 1;
265}
266