blob: e1a0bd04d4555cdd7d1156b25623dbd7545d9caf [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 Lattner2cdd21c2003-12-14 21:35:53 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner4a106452002-12-23 23:50:16 +000028/// isExecutableFile - This function returns true if the filename specified
29/// exists and is executable.
30///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000031bool llvm::isExecutableFile(const std::string &ExeFileName) {
Chris Lattner4a106452002-12-23 23:50:16 +000032 struct stat Buf;
33 if (stat(ExeFileName.c_str(), &Buf))
34 return false; // Must not be executable!
35
36 if (!(Buf.st_mode & S_IFREG))
37 return false; // Not a regular file?
38
39 if (Buf.st_uid == getuid()) // Owner of file?
40 return Buf.st_mode & S_IXUSR;
41 else if (Buf.st_gid == getgid()) // In group of file?
42 return Buf.st_mode & S_IXGRP;
43 else // Unrelated to file?
44 return Buf.st_mode & S_IXOTH;
45}
46
Misha Brukmanf7066c72003-08-07 21:34:25 +000047/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000048/// being executed. This allows us to find another LLVM tool if it is built
49/// into the same directory, but that directory is neither the current
50/// directory, nor in the PATH. If the executable cannot be found, return an
51/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000052///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000053std::string llvm::FindExecutable(const std::string &ExeName,
54 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000055 // First check the directory that bugpoint is in. We can do this if
56 // BugPointPath contains at least one / character, indicating that it is a
57 // relative path to bugpoint itself.
58 //
Misha Brukman35d402f2003-08-07 21:33:33 +000059 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000060 while (!Result.empty() && Result[Result.size()-1] != '/')
61 Result.erase(Result.size()-1, 1);
62
63 if (!Result.empty()) {
64 Result += ExeName;
65 if (isExecutableFile(Result)) return Result; // Found it?
66 }
67
Misha Brukman35d402f2003-08-07 21:33:33 +000068 // Okay, if the path to the program didn't tell us anything, try using the
69 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000070 const char *PathStr = getenv("PATH");
71 if (PathStr == 0) return "";
72
Misha Brukmanbc0e9982003-07-14 17:20:40 +000073 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000074 unsigned PathLen = strlen(PathStr);
75 while (PathLen) {
76 // Find the first colon...
77 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
78
79 // Check to see if this first directory contains the executable...
80 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
81 if (isExecutableFile(FilePath))
82 return FilePath; // Found the executable!
83
84 // Nope it wasn't in this directory, check the next range!
85 PathLen -= Colon-PathStr;
86 PathStr = Colon;
87 while (*PathStr == ':') { // Advance past colons
88 PathStr++;
89 PathLen--;
90 }
91 }
92
93 // If we fell out, we ran out of directories in PATH to search, return failure
94 return "";
95}
96
97static void RedirectFD(const std::string &File, int FD) {
98 if (File.empty()) return; // Noop
99
100 // Open the file
101 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
102 if (InFD == -1) {
103 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000104 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000105 exit(1);
106 }
107
108 dup2(InFD, FD); // Install it as the requested FD
109 close(InFD); // Close the original FD
110}
111
112/// RunProgramWithTimeout - This function executes the specified program, with
113/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000114/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000115/// the calling program if there is an error executing the specified program.
116/// It returns the return value of the program, or -1 if a timeout is detected.
117///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000118int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
119 const char **Args,
120 const std::string &StdInFile,
121 const std::string &StdOutFile,
122 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000123 // FIXME: install sigalarm handler here for timeout...
124
125 int Child = fork();
126 switch (Child) {
127 case -1:
128 std::cerr << "ERROR forking!\n";
129 exit(1);
130 case 0: // Child
131 RedirectFD(StdInFile, 0); // Redirect file descriptors...
132 RedirectFD(StdOutFile, 1);
133 RedirectFD(StdErrFile, 2);
134
135 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000136 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000137 for (; *Args; ++Args)
138 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000139 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000140 exit(1);
141
142 default: break;
143 }
144
145 // Make sure all output has been written while waiting
146 std::cout << std::flush;
147
148 int Status;
149 if (wait(&Status) != Child) {
150 if (errno == EINTR) {
151 static bool FirstTimeout = true;
152 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000153 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000154 "*** Program execution timed out! This mechanism is designed to handle\n"
155 " programs stuck in infinite loops gracefully. The -timeout option\n"
156 " can be used to change the timeout threshold or disable it completely\n"
157 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000158 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000159 }
160 return -1; // Timeout detected
161 }
162
163 std::cerr << "Error waiting for child process!\n";
164 exit(1);
165 }
166 return Status;
167}
John Criswell5afb5f62003-09-17 15:13:59 +0000168
169
170//
171// Function: ExecWait ()
172//
173// Description:
174// This function executes a program with the specified arguments and
175// environment. It then waits for the progarm to termiante and then returns
176// to the caller.
177//
178// Inputs:
179// argv - The arguments to the program as an array of C strings. The first
180// argument should be the name of the program to execute, and the
181// last argument should be a pointer to NULL.
182//
183// envp - The environment passes to the program as an array of C strings in
184// the form of "name=value" pairs. The last element should be a
185// pointer to NULL.
186//
187// Outputs:
188// None.
189//
190// Return value:
191// 0 - No errors.
192// 1 - The program could not be executed.
193// 1 - The program returned a non-zero exit status.
194// 1 - The program terminated abnormally.
195//
196// Notes:
197// The program will inherit the stdin, stdout, and stderr file descriptors
198// as well as other various configuration settings (umask).
199//
200// This function should not print anything to stdout/stderr on its own. It is
201// a generic library function. The caller or executed program should report
202// errors in the way it sees fit.
203//
John Criswelle5b3e152003-09-17 19:02:49 +0000204// This function does not use $PATH to find programs.
205//
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000206int llvm::ExecWait(const char * const old_argv[],
207 const char * const old_envp[]) {
John Criswell5afb5f62003-09-17 15:13:59 +0000208 // 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}