blob: c0fb7720ca8ea2bce191045ac4faa42b389d33e3 [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
Chris Lattnerc89fe6d2004-05-28 00:59:40 +000015#define _POSIX_MAPPED_FILES
Misha Brukman3d1b0c72003-08-07 21:28:50 +000016#include "Support/SystemUtils.h"
John Criswell7a73b802003-06-30 21:59:07 +000017#include "Config/sys/types.h"
18#include "Config/sys/stat.h"
19#include "Config/fcntl.h"
20#include "Config/sys/wait.h"
Chris Lattnerc89fe6d2004-05-28 00:59:40 +000021#include "Config/sys/mman.h"
John Criswell7a73b802003-06-30 21:59:07 +000022#include "Config/unistd.h"
Chris Lattner74b1f452004-01-10 19:15:14 +000023#include <algorithm>
24#include <fstream>
25#include <iostream>
26#include <cstdlib>
27#include <cerrno>
Chris Lattner49f61c42004-05-28 01:20:58 +000028#include "Config/windows.h"
Chris Lattner2cdd21c2003-12-14 21:35:53 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner4a106452002-12-23 23:50:16 +000031/// isExecutableFile - This function returns true if the filename specified
32/// exists and is executable.
33///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000034bool llvm::isExecutableFile(const std::string &ExeFileName) {
Chris Lattner4a106452002-12-23 23:50:16 +000035 struct stat Buf;
36 if (stat(ExeFileName.c_str(), &Buf))
37 return false; // Must not be executable!
38
39 if (!(Buf.st_mode & S_IFREG))
40 return false; // Not a regular file?
41
42 if (Buf.st_uid == getuid()) // Owner of file?
43 return Buf.st_mode & S_IXUSR;
44 else if (Buf.st_gid == getgid()) // In group of file?
45 return Buf.st_mode & S_IXGRP;
46 else // Unrelated to file?
47 return Buf.st_mode & S_IXOTH;
48}
49
Chris Lattnerb234d462004-04-02 05:04:03 +000050/// isStandardOutAConsole - Return true if we can tell that the standard output
51/// stream goes to a terminal window or console.
52bool llvm::isStandardOutAConsole() {
Brian Gaeke8507ecb2004-04-02 21:26:04 +000053#if HAVE_ISATTY
Chris Lattnerb234d462004-04-02 05:04:03 +000054 return isatty(1);
Brian Gaeke8507ecb2004-04-02 21:26:04 +000055#endif
56 // If we don't have isatty, just return false.
57 return false;
Chris Lattnerb234d462004-04-02 05:04:03 +000058}
59
60
Misha Brukmanf7066c72003-08-07 21:34:25 +000061/// FindExecutable - Find a named executable, giving the argv[0] of program
Misha Brukman44f8a342003-09-29 22:40:07 +000062/// being executed. This allows us to find another LLVM tool if it is built
63/// into the same directory, but that directory is neither the current
64/// directory, nor in the PATH. If the executable cannot be found, return an
65/// empty string.
Misha Brukmanf7066c72003-08-07 21:34:25 +000066///
Chris Lattner49f61c42004-05-28 01:20:58 +000067#undef FindExecutable // needed on windows :(
Chris Lattner2cdd21c2003-12-14 21:35:53 +000068std::string llvm::FindExecutable(const std::string &ExeName,
69 const std::string &ProgramPath) {
Chris Lattner4a106452002-12-23 23:50:16 +000070 // First check the directory that bugpoint is in. We can do this if
71 // BugPointPath contains at least one / character, indicating that it is a
72 // relative path to bugpoint itself.
73 //
Misha Brukman35d402f2003-08-07 21:33:33 +000074 std::string Result = ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +000075 while (!Result.empty() && Result[Result.size()-1] != '/')
76 Result.erase(Result.size()-1, 1);
77
78 if (!Result.empty()) {
79 Result += ExeName;
80 if (isExecutableFile(Result)) return Result; // Found it?
81 }
82
Misha Brukman35d402f2003-08-07 21:33:33 +000083 // Okay, if the path to the program didn't tell us anything, try using the
84 // PATH environment variable.
Chris Lattner4a106452002-12-23 23:50:16 +000085 const char *PathStr = getenv("PATH");
86 if (PathStr == 0) return "";
87
Misha Brukmanbc0e9982003-07-14 17:20:40 +000088 // Now we have a colon separated list of directories to search... try them...
Chris Lattner4a106452002-12-23 23:50:16 +000089 unsigned PathLen = strlen(PathStr);
90 while (PathLen) {
91 // Find the first colon...
92 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
93
94 // Check to see if this first directory contains the executable...
95 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
96 if (isExecutableFile(FilePath))
97 return FilePath; // Found the executable!
98
99 // Nope it wasn't in this directory, check the next range!
100 PathLen -= Colon-PathStr;
101 PathStr = Colon;
102 while (*PathStr == ':') { // Advance past colons
103 PathStr++;
104 PathLen--;
105 }
106 }
107
108 // If we fell out, we ran out of directories in PATH to search, return failure
109 return "";
110}
111
112static void RedirectFD(const std::string &File, int FD) {
113 if (File.empty()) return; // Noop
114
115 // Open the file
116 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
117 if (InFD == -1) {
118 std::cerr << "Error opening file '" << File << "' for "
Misha Brukman44f8a342003-09-29 22:40:07 +0000119 << (FD == 0 ? "input" : "output") << "!\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000120 exit(1);
121 }
122
123 dup2(InFD, FD); // Install it as the requested FD
124 close(InFD); // Close the original FD
125}
126
127/// RunProgramWithTimeout - This function executes the specified program, with
128/// the specified null-terminated argument array, with the stdin/out/err fd's
Misha Brukman950971d2003-09-16 15:31:46 +0000129/// redirected, with a timeout specified on the command line. This terminates
Chris Lattner4a106452002-12-23 23:50:16 +0000130/// the calling program if there is an error executing the specified program.
131/// It returns the return value of the program, or -1 if a timeout is detected.
132///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000133int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
134 const char **Args,
135 const std::string &StdInFile,
136 const std::string &StdOutFile,
137 const std::string &StdErrFile) {
Chris Lattner4a106452002-12-23 23:50:16 +0000138 // FIXME: install sigalarm handler here for timeout...
139
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000140#ifdef HAVE_SYS_WAIT_H
Chris Lattner4a106452002-12-23 23:50:16 +0000141 int Child = fork();
142 switch (Child) {
143 case -1:
144 std::cerr << "ERROR forking!\n";
145 exit(1);
146 case 0: // Child
147 RedirectFD(StdInFile, 0); // Redirect file descriptors...
148 RedirectFD(StdOutFile, 1);
Chris Lattnerbf3d2e22004-04-16 05:35:58 +0000149 if (StdOutFile != StdErrFile)
150 RedirectFD(StdErrFile, 2);
151 else
152 dup2(1, 2);
Chris Lattner4a106452002-12-23 23:50:16 +0000153
154 execv(ProgramPath.c_str(), (char *const *)Args);
Brian Gaeke53e557d2003-10-15 20:46:58 +0000155 std::cerr << "Error executing program: '" << ProgramPath;
Chris Lattner4a106452002-12-23 23:50:16 +0000156 for (; *Args; ++Args)
157 std::cerr << " " << *Args;
Brian Gaeke53e557d2003-10-15 20:46:58 +0000158 std::cerr << "'\n";
Chris Lattner4a106452002-12-23 23:50:16 +0000159 exit(1);
160
161 default: break;
162 }
163
164 // Make sure all output has been written while waiting
165 std::cout << std::flush;
166
167 int Status;
168 if (wait(&Status) != Child) {
169 if (errno == EINTR) {
170 static bool FirstTimeout = true;
171 if (FirstTimeout) {
Misha Brukman44f8a342003-09-29 22:40:07 +0000172 std::cout <<
Chris Lattner4a106452002-12-23 23:50:16 +0000173 "*** Program execution timed out! This mechanism is designed to handle\n"
174 " programs stuck in infinite loops gracefully. The -timeout option\n"
175 " can be used to change the timeout threshold or disable it completely\n"
176 " (with -timeout=0). This message is only displayed once.\n";
Misha Brukman44f8a342003-09-29 22:40:07 +0000177 FirstTimeout = false;
Chris Lattner4a106452002-12-23 23:50:16 +0000178 }
179 return -1; // Timeout detected
180 }
181
182 std::cerr << "Error waiting for child process!\n";
183 exit(1);
184 }
185 return Status;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000186
187#else
188 std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
189 return -1;
190#endif
Chris Lattner4a106452002-12-23 23:50:16 +0000191}
John Criswell5afb5f62003-09-17 15:13:59 +0000192
193
194//
195// Function: ExecWait ()
196//
197// Description:
198// This function executes a program with the specified arguments and
199// environment. It then waits for the progarm to termiante and then returns
200// to the caller.
201//
202// Inputs:
203// argv - The arguments to the program as an array of C strings. The first
204// argument should be the name of the program to execute, and the
205// last argument should be a pointer to NULL.
206//
207// envp - The environment passes to the program as an array of C strings in
208// the form of "name=value" pairs. The last element should be a
209// pointer to NULL.
210//
211// Outputs:
212// None.
213//
214// Return value:
215// 0 - No errors.
216// 1 - The program could not be executed.
217// 1 - The program returned a non-zero exit status.
218// 1 - The program terminated abnormally.
219//
220// Notes:
221// The program will inherit the stdin, stdout, and stderr file descriptors
222// as well as other various configuration settings (umask).
223//
224// This function should not print anything to stdout/stderr on its own. It is
225// a generic library function. The caller or executed program should report
226// errors in the way it sees fit.
227//
John Criswelle5b3e152003-09-17 19:02:49 +0000228// This function does not use $PATH to find programs.
229//
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000230int llvm::ExecWait(const char * const old_argv[],
231 const char * const old_envp[]) {
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000232#ifdef HAVE_SYS_WAIT_H
John Criswell5afb5f62003-09-17 15:13:59 +0000233 //
John Criswelle5b3e152003-09-17 19:02:49 +0000234 // Create local versions of the parameters that can be passed into execve()
235 // without creating const problems.
John Criswell5afb5f62003-09-17 15:13:59 +0000236 //
John Criswelle5b3e152003-09-17 19:02:49 +0000237 char ** const argv = (char ** const) old_argv;
238 char ** const envp = (char ** const) old_envp;
John Criswell5afb5f62003-09-17 15:13:59 +0000239
John Criswell5afb5f62003-09-17 15:13:59 +0000240 // Create a child process.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000241 switch (fork()) {
John Criswelle5b3e152003-09-17 19:02:49 +0000242 // An error occured: Return to the caller.
John Criswell5afb5f62003-09-17 15:13:59 +0000243 case -1:
244 return 1;
245 break;
246
John Criswelle5b3e152003-09-17 19:02:49 +0000247 // Child process: Execute the program.
John Criswell5afb5f62003-09-17 15:13:59 +0000248 case 0:
John Criswelle5b3e152003-09-17 19:02:49 +0000249 execve (argv[0], argv, envp);
John Criswelle5b3e152003-09-17 19:02:49 +0000250 // If the execve() failed, we should exit and let the parent pick up
251 // our non-zero exit status.
John Criswelle5b3e152003-09-17 19:02:49 +0000252 exit (1);
John Criswell5afb5f62003-09-17 15:13:59 +0000253
John Criswelle5b3e152003-09-17 19:02:49 +0000254 // Parent process: Break out of the switch to do our processing.
John Criswell5afb5f62003-09-17 15:13:59 +0000255 default:
256 break;
257 }
258
John Criswell5afb5f62003-09-17 15:13:59 +0000259 // Parent process: Wait for the child process to termiante.
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000260 int status;
John Criswell5afb5f62003-09-17 15:13:59 +0000261 if ((wait (&status)) == -1)
John Criswell5afb5f62003-09-17 15:13:59 +0000262 return 1;
John Criswell5afb5f62003-09-17 15:13:59 +0000263
John Criswell5afb5f62003-09-17 15:13:59 +0000264 // If the program exited normally with a zero exit status, return success!
John Criswell5afb5f62003-09-17 15:13:59 +0000265 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
John Criswell5afb5f62003-09-17 15:13:59 +0000266 return 0;
Chris Lattnerd895ffe2004-05-27 01:20:55 +0000267#else
268 std::cerr << "llvm::ExecWait not implemented on this platform!\n";
269#endif
John Criswell5afb5f62003-09-17 15:13:59 +0000270
John Criswell5afb5f62003-09-17 15:13:59 +0000271 // Otherwise, return failure.
John Criswell5afb5f62003-09-17 15:13:59 +0000272 return 1;
273}
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000274
275/// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
276/// permissions. This is typically used for JIT applications where we want
277/// to emit code to the memory then jump to it. Getting this type of memory
278/// is very OS specific.
279///
280void *llvm::AllocateRWXMemory(unsigned NumBytes) {
281 if (NumBytes == 0) return 0;
Chris Lattner49f61c42004-05-28 01:20:58 +0000282
283#if defined(HAVE_WINDOWS_H)
284 // On windows we use VirtualAlloc.
285 void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
286 if (P == 0) {
287 std::cerr << "Error allocating executable memory!\n";
288 abort();
289 }
290 return P;
291
292#elif defined(HAVE_MMAP)
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000293 static const long pageSize = sysconf(_SC_PAGESIZE);
294 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
295
296/* FIXME: This should use the proper autoconf flags */
297#if defined(i386) || defined(__i386__) || defined(__x86__)
298 /* Linux and *BSD tend to have these flags named differently. */
299#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
300# define MAP_ANONYMOUS MAP_ANON
301#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
302#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
303/* nothing */
304#else
Chris Lattner49f61c42004-05-28 01:20:58 +0000305 std::cerr << "This architecture has an unknown MMAP implementation!\n";
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000306 abort();
307 return 0;
308#endif
309
Chris Lattnerc89fe6d2004-05-28 00:59:40 +0000310 int fd = -1;
311#if defined(__linux__)
312 fd = 0;
313#endif
314
315 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
316#ifdef MAP_NORESERVE
317 mmapFlags |= MAP_NORESERVE;
318#endif
319
320 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
321 mmapFlags, fd, 0);
322 if (pa == MAP_FAILED) {
323 perror("mmap");
324 abort();
325 }
326 return pa;
327#else
328 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
329 abort();
330 return 0;
331#endif
332}
333
334