1 //===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file contains functions used to do a variety of low-level, often
11 // system-specific, tasks.
13 //===----------------------------------------------------------------------===//
15 #include "Support/SystemUtils.h"
20 #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"
28 /// isExecutableFile - This function returns true if the filename specified
29 /// exists and is executable.
31 bool llvm::isExecutableFile(const std::string &ExeFileName) {
33 if (stat(ExeFileName.c_str(), &Buf))
34 return false; // Must not be executable!
36 if (!(Buf.st_mode & S_IFREG))
37 return false; // Not a regular file?
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;
47 /// FindExecutable - Find a named executable, giving the argv[0] of program
48 /// 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
53 std::string llvm::FindExecutable(const std::string &ExeName,
54 const std::string &ProgramPath) {
55 // 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.
59 std::string Result = ProgramPath;
60 while (!Result.empty() && Result[Result.size()-1] != '/')
61 Result.erase(Result.size()-1, 1);
63 if (!Result.empty()) {
65 if (isExecutableFile(Result)) return Result; // Found it?
68 // Okay, if the path to the program didn't tell us anything, try using the
69 // PATH environment variable.
70 const char *PathStr = getenv("PATH");
71 if (PathStr == 0) return "";
73 // Now we have a colon separated list of directories to search... try them...
74 unsigned PathLen = strlen(PathStr);
76 // Find the first colon...
77 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
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!
84 // Nope it wasn't in this directory, check the next range!
85 PathLen -= Colon-PathStr;
87 while (*PathStr == ':') { // Advance past colons
93 // If we fell out, we ran out of directories in PATH to search, return failure
97 static void RedirectFD(const std::string &File, int FD) {
98 if (File.empty()) return; // Noop
101 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
103 std::cerr << "Error opening file '" << File << "' for "
104 << (FD == 0 ? "input" : "output") << "!\n";
108 dup2(InFD, FD); // Install it as the requested FD
109 close(InFD); // Close the original FD
112 /// RunProgramWithTimeout - This function executes the specified program, with
113 /// the specified null-terminated argument array, with the stdin/out/err fd's
114 /// redirected, with a timeout specified on the command line. This terminates
115 /// 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.
118 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
120 const std::string &StdInFile,
121 const std::string &StdOutFile,
122 const std::string &StdErrFile) {
123 // FIXME: install sigalarm handler here for timeout...
128 std::cerr << "ERROR forking!\n";
131 RedirectFD(StdInFile, 0); // Redirect file descriptors...
132 RedirectFD(StdOutFile, 1);
133 RedirectFD(StdErrFile, 2);
135 execv(ProgramPath.c_str(), (char *const *)Args);
136 std::cerr << "Error executing program: '" << ProgramPath;
137 for (; *Args; ++Args)
138 std::cerr << " " << *Args;
145 // Make sure all output has been written while waiting
146 std::cout << std::flush;
149 if (wait(&Status) != Child) {
150 if (errno == EINTR) {
151 static bool FirstTimeout = true;
154 "*** 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";
158 FirstTimeout = false;
160 return -1; // Timeout detected
163 std::cerr << "Error waiting for child process!\n";
171 // Function: ExecWait ()
174 // This function executes a program with the specified arguments and
175 // environment. It then waits for the progarm to termiante and then returns
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.
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
192 // 1 - The program could not be executed.
193 // 1 - The program returned a non-zero exit status.
194 // 1 - The program terminated abnormally.
197 // The program will inherit the stdin, stdout, and stderr file descriptors
198 // as well as other various configuration settings (umask).
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.
204 // This function does not use $PATH to find programs.
206 int llvm::ExecWait(const char * const old_argv[],
207 const char * const old_envp[]) {
211 // Status from child process when it exits
215 // Create local versions of the parameters that can be passed into execve()
216 // without creating const problems.
218 char ** const argv = (char ** const) old_argv;
219 char ** const envp = (char ** const) old_envp;
222 // Create a child process.
224 switch (child=fork())
227 // An error occured: Return to the caller.
234 // Child process: Execute the program.
237 execve (argv[0], argv, envp);
240 // If the execve() failed, we should exit and let the parent pick up
241 // our non-zero exit status.
247 // Parent process: Break out of the switch to do our processing.
254 // Parent process: Wait for the child process to termiante.
256 if ((wait (&status)) == -1)
262 // If the program exited normally with a zero exit status, return success!
264 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
270 // Otherwise, return failure.