blob: 8c009ffb5737a35dde89d69a4d337ace57312225 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
10// This file contains functions used to do a variety of low-level, often
11// system-specific, tasks.
12//
13//===----------------------------------------------------------------------===//
14
Misha Brukman3d1b0c72003-08-07 21:28:50 +000015#include "Support/SystemUtils.h"
Chris Lattner4a106452002-12-23 23:50:16 +000016#include <algorithm>
17#include <fstream>
Chris Lattnere1b52b72002-12-24 00:44:34 +000018#include <iostream>
Chris Lattner3301b692003-01-29 18:15:34 +000019#include <cstdlib>
John Criswell7a73b802003-06-30 21:59:07 +000020#include "Config/sys/types.h"
21#include "Config/sys/stat.h"
22#include "Config/fcntl.h"
23#include "Config/sys/wait.h"
24#include "Config/unistd.h"
25#include "Config/errno.h"
Chris Lattner4a106452002-12-23 23:50:16 +000026
Chris Lattner4a106452002-12-23 23:50:16 +000027/// isExecutableFile - This function returns true if the filename specified
28/// exists and is executable.
29///
30bool isExecutableFile(const std::string &ExeFileName) {
31 struct stat Buf;
32 if (stat(ExeFileName.c_str(), &Buf))
33 return false; // Must not be executable!
34
35 if (!(Buf.st_mode & S_IFREG))
36 return false; // Not a regular file?
37
38 if (Buf.st_uid == getuid()) // Owner of file?
39 return Buf.st_mode & S_IXUSR;
40 else if (Buf.st_gid == getgid()) // In group of file?
41 return Buf.st_mode & S_IXGRP;
42 else // Unrelated to file?
43 return Buf.st_mode & S_IXOTH;
44}
45
Misha Brukmanf7066c72003-08-07 21:34:25 +000046/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000047/// being executed. This allows us to find another LLVM tool if it is built
48/// into the same directory, but that directory is neither the current
49/// directory, nor in the PATH. If the executable cannot be found, return an
50/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000051///
Chris Lattner4a106452002-12-23 23:50:16 +000052std::string FindExecutable(const std::string &ExeName,
Misha Brukman44f8a342003-09-29 22:40:07 +000053 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000054 // First check the directory that bugpoint is in. We can do this if
55 // BugPointPath contains at least one / character, indicating that it is a
56 // relative path to bugpoint itself.
57 //
Misha Brukman35d402f2003-08-07 21:33:33 +000058 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000059 while (!Result.empty() && Result[Result.size()-1] != '/')
60 Result.erase(Result.size()-1, 1);
61
62 if (!Result.empty()) {
63 Result += ExeName;
64 if (isExecutableFile(Result)) return Result; // Found it?
65 }
66
Misha Brukman35d402f2003-08-07 21:33:33 +000067 // Okay, if the path to the program didn't tell us anything, try using the
68 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000069 const char *PathStr = getenv("PATH");
70 if (PathStr == 0) return "";
71
Misha Brukmanbc0e9982003-07-14 17:20:40 +000072 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000073 unsigned PathLen = strlen(PathStr);
74 while (PathLen) {
75 // Find the first colon...
76 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
77
78 // Check to see if this first directory contains the executable...
79 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
80 if (isExecutableFile(FilePath))
81 return FilePath; // Found the executable!
82
83 // Nope it wasn't in this directory, check the next range!
84 PathLen -= Colon-PathStr;
85 PathStr = Colon;
86 while (*PathStr == ':') { // Advance past colons
87 PathStr++;
88 PathLen--;
89 }
90 }
91
92 // If we fell out, we ran out of directories in PATH to search, return failure
93 return "";
94}
95
96static void RedirectFD(const std::string &File, int FD) {
97 if (File.empty()) return; // Noop
98
99 // Open the file
100 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
101 if (InFD == -1) {
102 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000103 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000104 exit(1);
105 }
106
107 dup2(InFD, FD); // Install it as the requested FD
108 close(InFD); // Close the original FD
109}
110
111/// RunProgramWithTimeout - This function executes the specified program, with
112/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000113/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000114/// the calling program if there is an error executing the specified program.
115/// It returns the return value of the program, or -1 if a timeout is detected.
116///
117int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
Misha Brukman44f8a342003-09-29 22:40:07 +0000118 const std::string &StdInFile,
119 const std::string &StdOutFile,
120 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000121
122 // FIXME: install sigalarm handler here for timeout...
123
124 int Child = fork();
125 switch (Child) {
126 case -1:
127 std::cerr << "ERROR forking!\n";
128 exit(1);
129 case 0: // Child
130 RedirectFD(StdInFile, 0); // Redirect file descriptors...
131 RedirectFD(StdOutFile, 1);
132 RedirectFD(StdErrFile, 2);
133
134 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000135 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000136 for (; *Args; ++Args)
137 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000138 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000139 exit(1);
140
141 default: break;
142 }
143
144 // Make sure all output has been written while waiting
145 std::cout << std::flush;
146
147 int Status;
148 if (wait(&Status) != Child) {
149 if (errno == EINTR) {
150 static bool FirstTimeout = true;
151 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000152 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000153 "*** Program execution timed out! This mechanism is designed to handle\n"
154 " programs stuck in infinite loops gracefully. The -timeout option\n"
155 " can be used to change the timeout threshold or disable it completely\n"
156 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000157 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000158 }
159 return -1; // Timeout detected
160 }
161
162 std::cerr << "Error waiting for child process!\n";
163 exit(1);
164 }
165 return Status;
166}
John Criswell5afb5f62003-09-17 15:13:59 +0000167
168
169//
170// Function: ExecWait ()
171//
172// Description:
173// This function executes a program with the specified arguments and
174// environment. It then waits for the progarm to termiante and then returns
175// to the caller.
176//
177// Inputs:
178// argv - The arguments to the program as an array of C strings. The first
179// argument should be the name of the program to execute, and the
180// last argument should be a pointer to NULL.
181//
182// envp - The environment passes to the program as an array of C strings in
183// the form of "name=value" pairs. The last element should be a
184// pointer to NULL.
185//
186// Outputs:
187// None.
188//
189// Return value:
190// 0 - No errors.
191// 1 - The program could not be executed.
192// 1 - The program returned a non-zero exit status.
193// 1 - The program terminated abnormally.
194//
195// Notes:
196// The program will inherit the stdin, stdout, and stderr file descriptors
197// as well as other various configuration settings (umask).
198//
199// This function should not print anything to stdout/stderr on its own. It is
200// a generic library function. The caller or executed program should report
201// errors in the way it sees fit.
202//
John Criswelle5b3e152003-09-17 19:02:49 +0000203// This function does not use $PATH to find programs.
204//
John Criswell5afb5f62003-09-17 15:13:59 +0000205int
John Criswelle5b3e152003-09-17 19:02:49 +0000206ExecWait (const char * const old_argv[], const char * const old_envp[])
John Criswell5afb5f62003-09-17 15:13:59 +0000207{
208 // Child process ID
209 register int child;
210
211 // Status from child process when it exits
212 int status;
213
214 //
John Criswelle5b3e152003-09-17 19:02:49 +0000215 // Create local versions of the parameters that can be passed into execve()
216 // without creating const problems.
John Criswell5afb5f62003-09-17 15:13:59 +0000217 //
John Criswelle5b3e152003-09-17 19:02:49 +0000218 char ** const argv = (char ** const) old_argv;
219 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000220
221 //
222 // Create a child process.
223 //
224 switch (child=fork())
225 {
John Criswelle5b3e152003-09-17 19:02:49 +0000226 //
227 // An error occured: Return to the caller.
228 //
John Criswell5afb5f62003-09-17 15:13:59 +0000229 case -1:
230 return 1;
231 break;
232
John Criswelle5b3e152003-09-17 19:02:49 +0000233 //
234 // Child process: Execute the program.
235 //
John Criswell5afb5f62003-09-17 15:13:59 +0000236 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000237 execve (argv[0], argv, envp);
238
239 //
240 // If the execve() failed, we should exit and let the parent pick up
241 // our non-zero exit status.
242 //
243 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000244 break;
245
John Criswelle5b3e152003-09-17 19:02:49 +0000246 //
247 // Parent process: Break out of the switch to do our processing.
248 //
John Criswell5afb5f62003-09-17 15:13:59 +0000249 default:
250 break;
251 }
252
253 //
254 // Parent process: Wait for the child process to termiante.
255 //
256 if ((wait (&status)) == -1)
257 {
258 return 1;
259 }
260
261 //
262 // If the program exited normally with a zero exit status, return success!
263 //
264 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
265 {
266 return 0;
267 }
268
269 //
270 // Otherwise, return failure.
271 //
272 return 1;
273}
274