blob: ec535ad45a2d4d38d4f6b63bba4c55b07fe0f0b8 [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
Brian Gaeked0fde302003-11-11 22:41:34 +000027namespace llvm {
28
Chris Lattner4a106452002-12-23 23:50:16 +000029/// isExecutableFile - This function returns true if the filename specified
30/// exists and is executable.
31///
32bool isExecutableFile(const std::string &ExeFileName) {
33 struct stat Buf;
34 if (stat(ExeFileName.c_str(), &Buf))
35 return false; // Must not be executable!
36
37 if (!(Buf.st_mode & S_IFREG))
38 return false; // Not a regular file?
39
40 if (Buf.st_uid == getuid()) // Owner of file?
41 return Buf.st_mode & S_IXUSR;
42 else if (Buf.st_gid == getgid()) // In group of file?
43 return Buf.st_mode & S_IXGRP;
44 else // Unrelated to file?
45 return Buf.st_mode & S_IXOTH;
46}
47
Misha Brukmanf7066c72003-08-07 21:34:25 +000048/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000049/// being executed. This allows us to find another LLVM tool if it is built
50/// into the same directory, but that directory is neither the current
51/// directory, nor in the PATH. If the executable cannot be found, return an
52/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000053///
Chris Lattner4a106452002-12-23 23:50:16 +000054std::string FindExecutable(const std::string &ExeName,
Misha Brukman44f8a342003-09-29 22:40:07 +000055 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000056 // First check the directory that bugpoint is in. We can do this if
57 // BugPointPath contains at least one / character, indicating that it is a
58 // relative path to bugpoint itself.
59 //
Misha Brukman35d402f2003-08-07 21:33:33 +000060 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000061 while (!Result.empty() && Result[Result.size()-1] != '/')
62 Result.erase(Result.size()-1, 1);
63
64 if (!Result.empty()) {
65 Result += ExeName;
66 if (isExecutableFile(Result)) return Result; // Found it?
67 }
68
Misha Brukman35d402f2003-08-07 21:33:33 +000069 // Okay, if the path to the program didn't tell us anything, try using the
70 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000071 const char *PathStr = getenv("PATH");
72 if (PathStr == 0) return "";
73
Misha Brukmanbc0e9982003-07-14 17:20:40 +000074 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000075 unsigned PathLen = strlen(PathStr);
76 while (PathLen) {
77 // Find the first colon...
78 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
79
80 // Check to see if this first directory contains the executable...
81 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
82 if (isExecutableFile(FilePath))
83 return FilePath; // Found the executable!
84
85 // Nope it wasn't in this directory, check the next range!
86 PathLen -= Colon-PathStr;
87 PathStr = Colon;
88 while (*PathStr == ':') { // Advance past colons
89 PathStr++;
90 PathLen--;
91 }
92 }
93
94 // If we fell out, we ran out of directories in PATH to search, return failure
95 return "";
96}
97
98static void RedirectFD(const std::string &File, int FD) {
99 if (File.empty()) return; // Noop
100
101 // Open the file
102 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
103 if (InFD == -1) {
104 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000105 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000106 exit(1);
107 }
108
109 dup2(InFD, FD); // Install it as the requested FD
110 close(InFD); // Close the original FD
111}
112
113/// RunProgramWithTimeout - This function executes the specified program, with
114/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000115/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000116/// the calling program if there is an error executing the specified program.
117/// It returns the return value of the program, or -1 if a timeout is detected.
118///
119int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
Misha Brukman44f8a342003-09-29 22:40:07 +0000120 const std::string &StdInFile,
121 const std::string &StdOutFile,
122 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000123
124 // FIXME: install sigalarm handler here for timeout...
125
126 int Child = fork();
127 switch (Child) {
128 case -1:
129 std::cerr << "ERROR forking!\n";
130 exit(1);
131 case 0: // Child
132 RedirectFD(StdInFile, 0); // Redirect file descriptors...
133 RedirectFD(StdOutFile, 1);
134 RedirectFD(StdErrFile, 2);
135
136 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000137 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000138 for (; *Args; ++Args)
139 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000140 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000141 exit(1);
142
143 default: break;
144 }
145
146 // Make sure all output has been written while waiting
147 std::cout << std::flush;
148
149 int Status;
150 if (wait(&Status) != Child) {
151 if (errno == EINTR) {
152 static bool FirstTimeout = true;
153 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000154 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000155 "*** Program execution timed out! This mechanism is designed to handle\n"
156 " programs stuck in infinite loops gracefully. The -timeout option\n"
157 " can be used to change the timeout threshold or disable it completely\n"
158 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000159 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000160 }
161 return -1; // Timeout detected
162 }
163
164 std::cerr << "Error waiting for child process!\n";
165 exit(1);
166 }
167 return Status;
168}
John Criswell5afb5f62003-09-17 15:13:59 +0000169
170
171//
172// Function: ExecWait ()
173//
174// Description:
175// This function executes a program with the specified arguments and
176// environment. It then waits for the progarm to termiante and then returns
177// to the caller.
178//
179// Inputs:
180// argv - The arguments to the program as an array of C strings. The first
181// argument should be the name of the program to execute, and the
182// last argument should be a pointer to NULL.
183//
184// envp - The environment passes to the program as an array of C strings in
185// the form of "name=value" pairs. The last element should be a
186// pointer to NULL.
187//
188// Outputs:
189// None.
190//
191// Return value:
192// 0 - No errors.
193// 1 - The program could not be executed.
194// 1 - The program returned a non-zero exit status.
195// 1 - The program terminated abnormally.
196//
197// Notes:
198// The program will inherit the stdin, stdout, and stderr file descriptors
199// as well as other various configuration settings (umask).
200//
201// This function should not print anything to stdout/stderr on its own. It is
202// a generic library function. The caller or executed program should report
203// errors in the way it sees fit.
204//
John Criswelle5b3e152003-09-17 19:02:49 +0000205// This function does not use $PATH to find programs.
206//
John Criswell5afb5f62003-09-17 15:13:59 +0000207int
John Criswelle5b3e152003-09-17 19:02:49 +0000208ExecWait (const char * const old_argv[], const char * const old_envp[])
John Criswell5afb5f62003-09-17 15:13:59 +0000209{
210 // Child process ID
211 register int child;
212
213 // Status from child process when it exits
214 int status;
215
216 //
John Criswelle5b3e152003-09-17 19:02:49 +0000217 // Create local versions of the parameters that can be passed into execve()
218 // without creating const problems.
John Criswell5afb5f62003-09-17 15:13:59 +0000219 //
John Criswelle5b3e152003-09-17 19:02:49 +0000220 char ** const argv = (char ** const) old_argv;
221 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000222
223 //
224 // Create a child process.
225 //
226 switch (child=fork())
227 {
John Criswelle5b3e152003-09-17 19:02:49 +0000228 //
229 // An error occured: Return to the caller.
230 //
John Criswell5afb5f62003-09-17 15:13:59 +0000231 case -1:
232 return 1;
233 break;
234
John Criswelle5b3e152003-09-17 19:02:49 +0000235 //
236 // Child process: Execute the program.
237 //
John Criswell5afb5f62003-09-17 15:13:59 +0000238 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000239 execve (argv[0], argv, envp);
240
241 //
242 // If the execve() failed, we should exit and let the parent pick up
243 // our non-zero exit status.
244 //
245 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000246 break;
247
John Criswelle5b3e152003-09-17 19:02:49 +0000248 //
249 // Parent process: Break out of the switch to do our processing.
250 //
John Criswell5afb5f62003-09-17 15:13:59 +0000251 default:
252 break;
253 }
254
255 //
256 // Parent process: Wait for the child process to termiante.
257 //
258 if ((wait (&status)) == -1)
259 {
260 return 1;
261 }
262
263 //
264 // If the program exited normally with a zero exit status, return success!
265 //
266 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
267 {
268 return 0;
269 }
270
271 //
272 // Otherwise, return failure.
273 //
274 return 1;
275}
276
Brian Gaeked0fde302003-11-11 22:41:34 +0000277} // End llvm namespace