blob: dafbf98da8392d3d73232dee507373f10f5e3ce5 [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"
John Criswell7a73b802003-06-30 21:59:07 +000016#include "Config/sys/types.h"
17#include "Config/sys/stat.h"
18#include "Config/fcntl.h"
19#include "Config/sys/wait.h"
20#include "Config/unistd.h"
Brian Gaeke8507ecb2004-04-02 21:26:04 +000021#include "Config/config.h"
Chris Lattner74b1f452004-01-10 19:15:14 +000022#include <algorithm>
23#include <fstream>
24#include <iostream>
25#include <cstdlib>
26#include <cerrno>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner4a106452002-12-23 23:50:16 +000029/// isExecutableFile - This function returns true if the filename specified
30/// exists and is executable.
31///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000032bool llvm::isExecutableFile(const std::string &ExeFileName) {
Chris Lattner4a106452002-12-23 23:50:16 +000033 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
Chris Lattnerb234d462004-04-02 05:04:03 +000048/// isStandardOutAConsole - Return true if we can tell that the standard output
49/// stream goes to a terminal window or console.
50bool llvm::isStandardOutAConsole() {
Brian Gaeke8507ecb2004-04-02 21:26:04 +000051#if HAVE_ISATTY
Chris Lattnerb234d462004-04-02 05:04:03 +000052 return isatty(1);
Brian Gaeke8507ecb2004-04-02 21:26:04 +000053#endif
54 // If we don't have isatty, just return false.
55 return false;
Chris Lattnerb234d462004-04-02 05:04:03 +000056}
57
58
Misha Brukmanf7066c72003-08-07 21:34:25 +000059/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000060/// being executed. This allows us to find another LLVM tool if it is built
61/// into the same directory, but that directory is neither the current
62/// directory, nor in the PATH. If the executable cannot be found, return an
63/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000064///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000065std::string llvm::FindExecutable(const std::string &ExeName,
66 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000067 // First check the directory that bugpoint is in. We can do this if
68 // BugPointPath contains at least one / character, indicating that it is a
69 // relative path to bugpoint itself.
70 //
Misha Brukman35d402f2003-08-07 21:33:33 +000071 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000072 while (!Result.empty() && Result[Result.size()-1] != '/')
73 Result.erase(Result.size()-1, 1);
74
75 if (!Result.empty()) {
76 Result += ExeName;
77 if (isExecutableFile(Result)) return Result; // Found it?
78 }
79
Misha Brukman35d402f2003-08-07 21:33:33 +000080 // Okay, if the path to the program didn't tell us anything, try using the
81 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000082 const char *PathStr = getenv("PATH");
83 if (PathStr == 0) return "";
84
Misha Brukmanbc0e9982003-07-14 17:20:40 +000085 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000086 unsigned PathLen = strlen(PathStr);
87 while (PathLen) {
88 // Find the first colon...
89 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
90
91 // Check to see if this first directory contains the executable...
92 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
93 if (isExecutableFile(FilePath))
94 return FilePath; // Found the executable!
95
96 // Nope it wasn't in this directory, check the next range!
97 PathLen -= Colon-PathStr;
98 PathStr = Colon;
99 while (*PathStr == ':') { // Advance past colons
100 PathStr++;
101 PathLen--;
102 }
103 }
104
105 // If we fell out, we ran out of directories in PATH to search, return failure
106 return "";
107}
108
109static void RedirectFD(const std::string &File, int FD) {
110 if (File.empty()) return; // Noop
111
112 // Open the file
113 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
114 if (InFD == -1) {
115 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000116 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000117 exit(1);
118 }
119
120 dup2(InFD, FD); // Install it as the requested FD
121 close(InFD); // Close the original FD
122}
123
124/// RunProgramWithTimeout - This function executes the specified program, with
125/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000126/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000127/// the calling program if there is an error executing the specified program.
128/// It returns the return value of the program, or -1 if a timeout is detected.
129///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000130int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
131 const char **Args,
132 const std::string &StdInFile,
133 const std::string &StdOutFile,
134 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000135 // FIXME: install sigalarm handler here for timeout...
136
137 int Child = fork();
138 switch (Child) {
139 case -1:
140 std::cerr << "ERROR forking!\n";
141 exit(1);
142 case 0: // Child
143 RedirectFD(StdInFile, 0); // Redirect file descriptors...
144 RedirectFD(StdOutFile, 1);
145 RedirectFD(StdErrFile, 2);
146
147 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000148 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000149 for (; *Args; ++Args)
150 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000151 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000152 exit(1);
153
154 default: break;
155 }
156
157 // Make sure all output has been written while waiting
158 std::cout << std::flush;
159
160 int Status;
161 if (wait(&Status) != Child) {
162 if (errno == EINTR) {
163 static bool FirstTimeout = true;
164 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000165 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000166 "*** Program execution timed out! This mechanism is designed to handle\n"
167 " programs stuck in infinite loops gracefully. The -timeout option\n"
168 " can be used to change the timeout threshold or disable it completely\n"
169 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000170 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000171 }
172 return -1; // Timeout detected
173 }
174
175 std::cerr << "Error waiting for child process!\n";
176 exit(1);
177 }
178 return Status;
179}
John Criswell5afb5f62003-09-17 15:13:59 +0000180
181
182//
183// Function: ExecWait ()
184//
185// Description:
186// This function executes a program with the specified arguments and
187// environment. It then waits for the progarm to termiante and then returns
188// to the caller.
189//
190// Inputs:
191// argv - The arguments to the program as an array of C strings. The first
192// argument should be the name of the program to execute, and the
193// last argument should be a pointer to NULL.
194//
195// envp - The environment passes to the program as an array of C strings in
196// the form of "name=value" pairs. The last element should be a
197// pointer to NULL.
198//
199// Outputs:
200// None.
201//
202// Return value:
203// 0 - No errors.
204// 1 - The program could not be executed.
205// 1 - The program returned a non-zero exit status.
206// 1 - The program terminated abnormally.
207//
208// Notes:
209// The program will inherit the stdin, stdout, and stderr file descriptors
210// as well as other various configuration settings (umask).
211//
212// This function should not print anything to stdout/stderr on its own. It is
213// a generic library function. The caller or executed program should report
214// errors in the way it sees fit.
215//
John Criswelle5b3e152003-09-17 19:02:49 +0000216// This function does not use $PATH to find programs.
217//
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000218int llvm::ExecWait(const char * const old_argv[],
219 const char * const old_envp[]) {
John Criswell5afb5f62003-09-17 15:13:59 +0000220 // Child process ID
221 register int child;
222
223 // Status from child process when it exits
224 int status;
225
226 //
John Criswelle5b3e152003-09-17 19:02:49 +0000227 // Create local versions of the parameters that can be passed into execve()
228 // without creating const problems.
John Criswell5afb5f62003-09-17 15:13:59 +0000229 //
John Criswelle5b3e152003-09-17 19:02:49 +0000230 char ** const argv = (char ** const) old_argv;
231 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000232
233 //
234 // Create a child process.
235 //
236 switch (child=fork())
237 {
John Criswelle5b3e152003-09-17 19:02:49 +0000238 //
239 // An error occured: Return to the caller.
240 //
John Criswell5afb5f62003-09-17 15:13:59 +0000241 case -1:
242 return 1;
243 break;
244
John Criswelle5b3e152003-09-17 19:02:49 +0000245 //
246 // Child process: Execute the program.
247 //
John Criswell5afb5f62003-09-17 15:13:59 +0000248 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000249 execve (argv[0], argv, envp);
250
251 //
252 // If the execve() failed, we should exit and let the parent pick up
253 // our non-zero exit status.
254 //
255 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000256 break;
257
John Criswelle5b3e152003-09-17 19:02:49 +0000258 //
259 // Parent process: Break out of the switch to do our processing.
260 //
John Criswell5afb5f62003-09-17 15:13:59 +0000261 default:
262 break;
263 }
264
265 //
266 // Parent process: Wait for the child process to termiante.
267 //
268 if ((wait (&status)) == -1)
269 {
270 return 1;
271 }
272
273 //
274 // If the program exited normally with a zero exit status, return success!
275 //
276 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
277 {
278 return 0;
279 }
280
281 //
282 // Otherwise, return failure.
283 //
284 return 1;
285}